Misc simplifications to InstCombiner::commonIntCastTransforms. Most of
[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/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/PatternMatch.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include <algorithm>
63 #include <climits>
64 #include <sstream>
65 using namespace llvm;
66 using namespace llvm::PatternMatch;
67
68 STATISTIC(NumCombined , "Number of insts combined");
69 STATISTIC(NumConstProp, "Number of constant folds");
70 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72 STATISTIC(NumSunkInst , "Number of instructions sunk");
73
74 namespace {
75   class VISIBILITY_HIDDEN InstCombiner
76     : public FunctionPass,
77       public InstVisitor<InstCombiner, Instruction*> {
78     // Worklist of all of the instructions that need to be simplified.
79     SmallVector<Instruction*, 256> Worklist;
80     DenseMap<Instruction*, unsigned> WorklistMap;
81     TargetData *TD;
82     bool MustPreserveLCSSA;
83   public:
84     static char ID; // Pass identification, replacement for typeid
85     InstCombiner() : FunctionPass(&ID) {}
86
87     LLVMContext *getContext() { return Context; }
88
89     /// AddToWorkList - Add the specified instruction to the worklist if it
90     /// isn't already in it.
91     void AddToWorkList(Instruction *I) {
92       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
93         Worklist.push_back(I);
94     }
95     
96     // RemoveFromWorkList - remove I from the worklist if it exists.
97     void RemoveFromWorkList(Instruction *I) {
98       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99       if (It == WorklistMap.end()) return; // Not in worklist.
100       
101       // Don't bother moving everything down, just null out the slot.
102       Worklist[It->second] = 0;
103       
104       WorklistMap.erase(It);
105     }
106     
107     Instruction *RemoveOneFromWorkList() {
108       Instruction *I = Worklist.back();
109       Worklist.pop_back();
110       WorklistMap.erase(I);
111       return I;
112     }
113
114     
115     /// AddUsersToWorkList - When an instruction is simplified, add all users of
116     /// the instruction to the work lists because they might get more simplified
117     /// now.
118     ///
119     void AddUsersToWorkList(Value &I) {
120       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
121            UI != UE; ++UI)
122         AddToWorkList(cast<Instruction>(*UI));
123     }
124
125     /// AddUsesToWorkList - When an instruction is simplified, add operands to
126     /// the work lists because they might get more simplified now.
127     ///
128     void AddUsesToWorkList(Instruction &I) {
129       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130         if (Instruction *Op = dyn_cast<Instruction>(*i))
131           AddToWorkList(Op);
132     }
133     
134     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135     /// dead.  Add all of its operands to the worklist, turning them into
136     /// undef's to reduce the number of uses of those instructions.
137     ///
138     /// Return the specified operand before it is turned into an undef.
139     ///
140     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141       Value *R = I.getOperand(op);
142       
143       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
145           AddToWorkList(Op);
146           // Set the operand to undef to drop the use.
147           *i = Context->getUndef(Op->getType());
148         }
149       
150       return R;
151     }
152
153   public:
154     virtual bool runOnFunction(Function &F);
155     
156     bool DoOneIteration(Function &F, unsigned ItNum);
157
158     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159       AU.addRequired<TargetData>();
160       AU.addPreservedID(LCSSAID);
161       AU.setPreservesCFG();
162     }
163
164     TargetData &getTargetData() const { return *TD; }
165
166     // Visitation implementation - Implement instruction combining for different
167     // instruction types.  The semantics are as follows:
168     // Return Value:
169     //    null        - No change was made
170     //     I          - Change was made, I is still valid, I may be dead though
171     //   otherwise    - Change was made, replace I with returned instruction
172     //
173     Instruction *visitAdd(BinaryOperator &I);
174     Instruction *visitFAdd(BinaryOperator &I);
175     Instruction *visitSub(BinaryOperator &I);
176     Instruction *visitFSub(BinaryOperator &I);
177     Instruction *visitMul(BinaryOperator &I);
178     Instruction *visitFMul(BinaryOperator &I);
179     Instruction *visitURem(BinaryOperator &I);
180     Instruction *visitSRem(BinaryOperator &I);
181     Instruction *visitFRem(BinaryOperator &I);
182     bool SimplifyDivRemOfSelect(BinaryOperator &I);
183     Instruction *commonRemTransforms(BinaryOperator &I);
184     Instruction *commonIRemTransforms(BinaryOperator &I);
185     Instruction *commonDivTransforms(BinaryOperator &I);
186     Instruction *commonIDivTransforms(BinaryOperator &I);
187     Instruction *visitUDiv(BinaryOperator &I);
188     Instruction *visitSDiv(BinaryOperator &I);
189     Instruction *visitFDiv(BinaryOperator &I);
190     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
191     Instruction *visitAnd(BinaryOperator &I);
192     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
194                                      Value *A, Value *B, Value *C);
195     Instruction *visitOr (BinaryOperator &I);
196     Instruction *visitXor(BinaryOperator &I);
197     Instruction *visitShl(BinaryOperator &I);
198     Instruction *visitAShr(BinaryOperator &I);
199     Instruction *visitLShr(BinaryOperator &I);
200     Instruction *commonShiftTransforms(BinaryOperator &I);
201     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202                                       Constant *RHSC);
203     Instruction *visitFCmpInst(FCmpInst &I);
204     Instruction *visitICmpInst(ICmpInst &I);
205     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
206     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207                                                 Instruction *LHS,
208                                                 ConstantInt *RHS);
209     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210                                 ConstantInt *DivRHS);
211
212     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213                              ICmpInst::Predicate Cond, Instruction &I);
214     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
215                                      BinaryOperator &I);
216     Instruction *commonCastTransforms(CastInst &CI);
217     Instruction *commonIntCastTransforms(CastInst &CI);
218     Instruction *commonPointerCastTransforms(CastInst &CI);
219     Instruction *visitTrunc(TruncInst &CI);
220     Instruction *visitZExt(ZExtInst &CI);
221     Instruction *visitSExt(SExtInst &CI);
222     Instruction *visitFPTrunc(FPTruncInst &CI);
223     Instruction *visitFPExt(CastInst &CI);
224     Instruction *visitFPToUI(FPToUIInst &FI);
225     Instruction *visitFPToSI(FPToSIInst &FI);
226     Instruction *visitUIToFP(CastInst &CI);
227     Instruction *visitSIToFP(CastInst &CI);
228     Instruction *visitPtrToInt(PtrToIntInst &CI);
229     Instruction *visitIntToPtr(IntToPtrInst &CI);
230     Instruction *visitBitCast(BitCastInst &CI);
231     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232                                 Instruction *FI);
233     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
234     Instruction *visitSelectInst(SelectInst &SI);
235     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
236     Instruction *visitCallInst(CallInst &CI);
237     Instruction *visitInvokeInst(InvokeInst &II);
238     Instruction *visitPHINode(PHINode &PN);
239     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
240     Instruction *visitAllocationInst(AllocationInst &AI);
241     Instruction *visitFreeInst(FreeInst &FI);
242     Instruction *visitLoadInst(LoadInst &LI);
243     Instruction *visitStoreInst(StoreInst &SI);
244     Instruction *visitBranchInst(BranchInst &BI);
245     Instruction *visitSwitchInst(SwitchInst &SI);
246     Instruction *visitInsertElementInst(InsertElementInst &IE);
247     Instruction *visitExtractElementInst(ExtractElementInst &EI);
248     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
249     Instruction *visitExtractValueInst(ExtractValueInst &EV);
250
251     // visitInstruction - Specify what to return for unhandled instructions...
252     Instruction *visitInstruction(Instruction &I) { return 0; }
253
254   private:
255     Instruction *visitCallSite(CallSite CS);
256     bool transformConstExprCastCall(CallSite CS);
257     Instruction *transformCallThroughTrampoline(CallSite CS);
258     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259                                    bool DoXform = true);
260     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
261     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
263
264   public:
265     // InsertNewInstBefore - insert an instruction New before instruction Old
266     // in the program.  Add the new instruction to the worklist.
267     //
268     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
269       assert(New && New->getParent() == 0 &&
270              "New instruction already inserted into a basic block!");
271       BasicBlock *BB = Old.getParent();
272       BB->getInstList().insert(&Old, New);  // Insert inst
273       AddToWorkList(New);
274       return New;
275     }
276
277     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278     /// This also adds the cast to the worklist.  Finally, this returns the
279     /// cast.
280     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281                             Instruction &Pos) {
282       if (V->getType() == Ty) return V;
283
284       if (Constant *CV = dyn_cast<Constant>(V))
285         return Context->getConstantExprCast(opc, CV, Ty);
286       
287       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
288       AddToWorkList(C);
289       return C;
290     }
291         
292     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294     }
295
296
297     // ReplaceInstUsesWith - This method is to be used when an instruction is
298     // found to be dead, replacable with another preexisting expression.  Here
299     // we add all uses of I to the worklist, replace all uses of I with the new
300     // value, then return I, so that the inst combiner will know that I was
301     // modified.
302     //
303     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
304       AddUsersToWorkList(I);         // Add all modified instrs to worklist
305       if (&I != V) {
306         I.replaceAllUsesWith(V);
307         return &I;
308       } else {
309         // If we are replacing the instruction with itself, this must be in a
310         // segment of unreachable code, so just clobber the instruction.
311         I.replaceAllUsesWith(Context->getUndef(I.getType()));
312         return &I;
313       }
314     }
315
316     // EraseInstFromFunction - When dealing with an instruction that has side
317     // effects or produces a void value, we can't rely on DCE to delete the
318     // instruction.  Instead, visit methods should return the value returned by
319     // this function.
320     Instruction *EraseInstFromFunction(Instruction &I) {
321       assert(I.use_empty() && "Cannot erase instruction that is used!");
322       AddUsesToWorkList(I);
323       RemoveFromWorkList(&I);
324       I.eraseFromParent();
325       return 0;  // Don't do anything with FI
326     }
327         
328     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329                            APInt &KnownOne, unsigned Depth = 0) const {
330       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331     }
332     
333     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
334                            unsigned Depth = 0) const {
335       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336     }
337     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338       return llvm::ComputeNumSignBits(Op, TD, Depth);
339     }
340
341   private:
342
343     /// SimplifyCommutative - This performs a few simplifications for 
344     /// commutative operators.
345     bool SimplifyCommutative(BinaryOperator &I);
346
347     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348     /// most-complex to least-complex order.
349     bool SimplifyCompare(CmpInst &I);
350
351     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352     /// based on the demanded bits.
353     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
354                                    APInt& KnownZero, APInt& KnownOne,
355                                    unsigned Depth);
356     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
357                               APInt& KnownZero, APInt& KnownOne,
358                               unsigned Depth=0);
359         
360     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361     /// SimplifyDemandedBits knows about.  See if the instruction has any
362     /// properties that allow us to simplify its operands.
363     bool SimplifyDemandedInstructionBits(Instruction &Inst);
364         
365     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366                                       APInt& UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
380     
381     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
383     
384     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385                               bool isSub, Instruction &I);
386     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387                                  bool isSigned, bool Inside, Instruction &IB);
388     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389     Instruction *MatchBSwap(BinaryOperator &I);
390     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392     Instruction *SimplifyMemSet(MemSetInst *MI);
393
394
395     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396
397     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
398                                     unsigned CastOpc, int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(LLVMContext *Context, Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(*Context, V) ||
414         BinaryOperator::isFNeg(*Context, V) ||
415         BinaryOperator::isNot(V))
416       return 3;
417     return 4;
418   }
419   if (isa<Argument>(V)) return 3;
420   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421 }
422
423 // isOnlyUse - Return true if this instruction will be deleted if we stop using
424 // it.
425 static bool isOnlyUse(Value *V) {
426   return V->hasOneUse() || isa<Constant>(V);
427 }
428
429 // getPromotedType - Return the specified type promoted as it would be to pass
430 // though a va_arg area...
431 static const Type *getPromotedType(const Type *Ty) {
432   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433     if (ITy->getBitWidth() < 32)
434       return Type::Int32Ty;
435   }
436   return Ty;
437 }
438
439 /// getBitCastOperand - If the specified operand is a CastInst, a constant
440 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441 /// operand value, otherwise return null.
442 static Value *getBitCastOperand(Value *V) {
443   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
444     // BitCastInst?
445     return I->getOperand(0);
446   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447     // GetElementPtrInst?
448     if (GEP->hasAllZeroIndices())
449       return GEP->getOperand(0);
450   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
451     if (CE->getOpcode() == Instruction::BitCast)
452       // BitCast ConstantExp?
453       return CE->getOperand(0);
454     else if (CE->getOpcode() == Instruction::GetElementPtr) {
455       // GetElementPtr ConstantExp?
456       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
457            I != E; ++I) {
458         ConstantInt *CI = dyn_cast<ConstantInt>(I);
459         if (!CI || !CI->isZero())
460           // Any non-zero indices? Not cast-like.
461           return 0;
462       }
463       // All-zero indices? This is just like casting.
464       return CE->getOperand(0);
465     }
466   }
467   return 0;
468 }
469
470 /// This function is a wrapper around CastInst::isEliminableCastPair. It
471 /// simply extracts arguments and returns what that function returns.
472 static Instruction::CastOps 
473 isEliminableCastPair(
474   const CastInst *CI, ///< The first cast instruction
475   unsigned opcode,       ///< The opcode of the second cast instruction
476   const Type *DstTy,     ///< The target type for the second cast instruction
477   TargetData *TD         ///< The target data for pointer size
478 ) {
479   
480   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
481   const Type *MidTy = CI->getType();                  // B from above
482
483   // Get the opcodes of the two Cast instructions
484   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
486
487   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488                                                 DstTy, TD->getIntPtrType());
489   
490   // We don't want to form an inttoptr or ptrtoint that converts to an integer
491   // type that differs from the pointer size.
492   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494     Res = 0;
495   
496   return Instruction::CastOps(Res);
497 }
498
499 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500 /// in any code being generated.  It does not require codegen if V is simple
501 /// enough or if the cast can be folded into other casts.
502 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
503                               const Type *Ty, TargetData *TD) {
504   if (V->getType() == Ty || isa<Constant>(V)) return false;
505   
506   // If this is another cast that can be eliminated, it isn't codegen either.
507   if (const CastInst *CI = dyn_cast<CastInst>(V))
508     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
509       return false;
510   return true;
511 }
512
513 // SimplifyCommutative - This performs a few simplifications for commutative
514 // operators:
515 //
516 //  1. Order operands such that they are listed from right (least complex) to
517 //     left (most complex).  This puts constants before unary operators before
518 //     binary operators.
519 //
520 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
522 //
523 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
524   bool Changed = false;
525   if (getComplexity(Context, I.getOperand(0)) < 
526       getComplexity(Context, I.getOperand(1)))
527     Changed = !I.swapOperands();
528
529   if (!I.isAssociative()) return Changed;
530   Instruction::BinaryOps Opcode = I.getOpcode();
531   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533       if (isa<Constant>(I.getOperand(1))) {
534         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
535                                              cast<Constant>(I.getOperand(1)),
536                                              cast<Constant>(Op->getOperand(1)));
537         I.setOperand(0, Op->getOperand(0));
538         I.setOperand(1, Folded);
539         return true;
540       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542             isOnlyUse(Op) && isOnlyUse(Op1)) {
543           Constant *C1 = cast<Constant>(Op->getOperand(1));
544           Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
548           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549                                                     Op1->getOperand(0),
550                                                     Op1->getName(), &I);
551           AddToWorkList(New);
552           I.setOperand(0, New);
553           I.setOperand(1, Folded);
554           return true;
555         }
556     }
557   return Changed;
558 }
559
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564   if (getComplexity(Context, I.getOperand(0)) >=
565       getComplexity(Context, I.getOperand(1)))
566     return false;
567   I.swapOperands();
568   // Compare instructions are not associative so there's nothing else we can do.
569   return true;
570 }
571
572 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573 // if the LHS is a constant zero (which is the 'negate' form).
574 //
575 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
576   if (BinaryOperator::isNeg(*Context, V))
577     return BinaryOperator::getNegArgument(V);
578
579   // Constants can be considered to be negated values if they can be folded.
580   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
581     return Context->getConstantExprNeg(C);
582
583   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584     if (C->getType()->getElementType()->isInteger())
585       return Context->getConstantExprNeg(C);
586
587   return 0;
588 }
589
590 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591 // instruction if the LHS is a constant negative zero (which is the 'negate'
592 // form).
593 //
594 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
595   if (BinaryOperator::isFNeg(*Context, V))
596     return BinaryOperator::getFNegArgument(V);
597
598   // Constants can be considered to be negated values if they can be folded.
599   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
600     return Context->getConstantExprFNeg(C);
601
602   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603     if (C->getType()->getElementType()->isFloatingPoint())
604       return Context->getConstantExprFNeg(C);
605
606   return 0;
607 }
608
609 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
610   if (BinaryOperator::isNot(V))
611     return BinaryOperator::getNotArgument(V);
612
613   // Constants can be considered to be not'ed values...
614   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
615     return Context->getConstantInt(~C->getValue());
616   return 0;
617 }
618
619 // dyn_castFoldableMul - If this value is a multiply that can be folded into
620 // other computations (because it has a constant operand), return the
621 // non-constant operand of the multiply, and set CST to point to the multiplier.
622 // Otherwise, return null.
623 //
624 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
625                                          LLVMContext *Context) {
626   if (V->hasOneUse() && V->getType()->isInteger())
627     if (Instruction *I = dyn_cast<Instruction>(V)) {
628       if (I->getOpcode() == Instruction::Mul)
629         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
630           return I->getOperand(0);
631       if (I->getOpcode() == Instruction::Shl)
632         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
633           // The multiplier is really 1 << CST.
634           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
635           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
636           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
637           return I->getOperand(0);
638         }
639     }
640   return 0;
641 }
642
643 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644 /// expression, return it.
645 static User *dyn_castGetElementPtr(Value *V) {
646   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648     if (CE->getOpcode() == Instruction::GetElementPtr)
649       return cast<User>(V);
650   return false;
651 }
652
653 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
654 /// opcode value. Otherwise return UserOp1.
655 static unsigned getOpcode(const Value *V) {
656   if (const Instruction *I = dyn_cast<Instruction>(V))
657     return I->getOpcode();
658   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
659     return CE->getOpcode();
660   // Use UserOp1 to mean there's no opcode.
661   return Instruction::UserOp1;
662 }
663
664 /// AddOne - Add one to a ConstantInt
665 static Constant *AddOne(Constant *C, LLVMContext *Context) {
666   return Context->getConstantExprAdd(C, 
667     Context->getConstantInt(C->getType(), 1));
668 }
669 /// SubOne - Subtract one from a ConstantInt
670 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
671   return Context->getConstantExprSub(C, 
672     Context->getConstantInt(C->getType(), 1));
673 }
674 /// MultiplyOverflows - True if the multiply can not be expressed in an int
675 /// this size.
676 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
677                               LLVMContext *Context) {
678   uint32_t W = C1->getBitWidth();
679   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
680   if (sign) {
681     LHSExt.sext(W * 2);
682     RHSExt.sext(W * 2);
683   } else {
684     LHSExt.zext(W * 2);
685     RHSExt.zext(W * 2);
686   }
687
688   APInt MulExt = LHSExt * RHSExt;
689
690   if (sign) {
691     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693     return MulExt.slt(Min) || MulExt.sgt(Max);
694   } else 
695     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
696 }
697
698
699 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
700 /// specified instruction is a constant integer.  If so, check to see if there
701 /// are any bits set in the constant that are not demanded.  If so, shrink the
702 /// constant and return true.
703 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
704                                    APInt Demanded, LLVMContext *Context) {
705   assert(I && "No instruction?");
706   assert(OpNo < I->getNumOperands() && "Operand index too large");
707
708   // If the operand is not a constant integer, nothing to do.
709   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710   if (!OpC) return false;
711
712   // If there are no bits set that aren't demanded, nothing to do.
713   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714   if ((~Demanded & OpC->getValue()) == 0)
715     return false;
716
717   // This instruction is producing bits that are not demanded. Shrink the RHS.
718   Demanded &= OpC->getValue();
719   I->setOperand(OpNo, Context->getConstantInt(Demanded));
720   return true;
721 }
722
723 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
724 // set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
726 // min/max.
727 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
728                                                    const APInt& KnownOne,
729                                                    APInt& Min, APInt& Max) {
730   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731          KnownZero.getBitWidth() == Min.getBitWidth() &&
732          KnownZero.getBitWidth() == Max.getBitWidth() &&
733          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
734   APInt UnknownBits = ~(KnownZero|KnownOne);
735
736   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737   // bit if it is unknown.
738   Min = KnownOne;
739   Max = KnownOne|UnknownBits;
740   
741   if (UnknownBits.isNegative()) { // Sign bit is unknown
742     Min.set(Min.getBitWidth()-1);
743     Max.clear(Max.getBitWidth()-1);
744   }
745 }
746
747 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748 // a set of known zero and one bits, compute the maximum and minimum values that
749 // could have the specified known zero and known one bits, returning them in
750 // min/max.
751 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
752                                                      const APInt &KnownOne,
753                                                      APInt &Min, APInt &Max) {
754   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755          KnownZero.getBitWidth() == Min.getBitWidth() &&
756          KnownZero.getBitWidth() == Max.getBitWidth() &&
757          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
758   APInt UnknownBits = ~(KnownZero|KnownOne);
759   
760   // The minimum value is when the unknown bits are all zeros.
761   Min = KnownOne;
762   // The maximum value is when the unknown bits are all ones.
763   Max = KnownOne|UnknownBits;
764 }
765
766 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767 /// SimplifyDemandedBits knows about.  See if the instruction has any
768 /// properties that allow us to simplify its operands.
769 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
770   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
771   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
773   
774   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
775                                      KnownZero, KnownOne, 0);
776   if (V == 0) return false;
777   if (V == &Inst) return true;
778   ReplaceInstUsesWith(Inst, V);
779   return true;
780 }
781
782 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783 /// specified instruction operand if possible, updating it in place.  It returns
784 /// true if it made any change and false otherwise.
785 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
786                                         APInt &KnownZero, APInt &KnownOne,
787                                         unsigned Depth) {
788   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789                                           KnownZero, KnownOne, Depth);
790   if (NewVal == 0) return false;
791   U.set(NewVal);
792   return true;
793 }
794
795
796 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797 /// value based on the demanded bits.  When this function is called, it is known
798 /// that only the bits set in DemandedMask of the result of V are ever used
799 /// downstream. Consequently, depending on the mask and V, it may be possible
800 /// to replace V with a constant or one of its operands. In such cases, this
801 /// function does the replacement and returns true. In all other cases, it
802 /// returns false after analyzing the expression and setting KnownOne and known
803 /// to be one in the expression.  KnownZero contains all the bits that are known
804 /// to be zero in the expression. These are provided to potentially allow the
805 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806 /// the expression. KnownOne and KnownZero always follow the invariant that 
807 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
809 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810 /// and KnownOne must all be the same.
811 ///
812 /// This returns null if it did not change anything and it permits no
813 /// simplification.  This returns V itself if it did some simplification of V's
814 /// operands based on the information about what bits are demanded. This returns
815 /// some other non-null value if it found out that V is equal to another value
816 /// in the context where the specified bits are demanded, but not for all users.
817 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818                                              APInt &KnownZero, APInt &KnownOne,
819                                              unsigned Depth) {
820   assert(V != 0 && "Null pointer of Value???");
821   assert(Depth <= 6 && "Limit Search Depth");
822   uint32_t BitWidth = DemandedMask.getBitWidth();
823   const Type *VTy = V->getType();
824   assert((TD || !isa<PointerType>(VTy)) &&
825          "SimplifyDemandedBits needs to know bit widths!");
826   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827          (!VTy->isIntOrIntVector() ||
828           VTy->getScalarSizeInBits() == BitWidth) &&
829          KnownZero.getBitWidth() == BitWidth &&
830          KnownOne.getBitWidth() == BitWidth &&
831          "Value *V, DemandedMask, KnownZero and KnownOne "
832          "must have same BitWidth");
833   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834     // We know all of the bits for a constant!
835     KnownOne = CI->getValue() & DemandedMask;
836     KnownZero = ~KnownOne & DemandedMask;
837     return 0;
838   }
839   if (isa<ConstantPointerNull>(V)) {
840     // We know all of the bits for a constant!
841     KnownOne.clear();
842     KnownZero = DemandedMask;
843     return 0;
844   }
845
846   KnownZero.clear();
847   KnownOne.clear();
848   if (DemandedMask == 0) {   // Not demanding any bits from V.
849     if (isa<UndefValue>(V))
850       return 0;
851     return Context->getUndef(VTy);
852   }
853   
854   if (Depth == 6)        // Limit search depth.
855     return 0;
856   
857   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
859
860   Instruction *I = dyn_cast<Instruction>(V);
861   if (!I) {
862     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863     return 0;        // Only analyze instructions.
864   }
865
866   // If there are multiple uses of this value and we aren't at the root, then
867   // we can't do any simplifications of the operands, because DemandedMask
868   // only reflects the bits demanded by *one* of the users.
869   if (Depth != 0 && !I->hasOneUse()) {
870     // Despite the fact that we can't simplify this instruction in all User's
871     // context, we can at least compute the knownzero/knownone bits, and we can
872     // do simplifications that apply to *just* the one user if we know that
873     // this instruction has a simpler value in that context.
874     if (I->getOpcode() == Instruction::And) {
875       // If either the LHS or the RHS are Zero, the result is zero.
876       ComputeMaskedBits(I->getOperand(1), DemandedMask,
877                         RHSKnownZero, RHSKnownOne, Depth+1);
878       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879                         LHSKnownZero, LHSKnownOne, Depth+1);
880       
881       // If all of the demanded bits are known 1 on one side, return the other.
882       // These bits cannot contribute to the result of the 'and' in this
883       // context.
884       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
885           (DemandedMask & ~LHSKnownZero))
886         return I->getOperand(0);
887       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
888           (DemandedMask & ~RHSKnownZero))
889         return I->getOperand(1);
890       
891       // If all of the demanded bits in the inputs are known zeros, return zero.
892       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
893         return Context->getNullValue(VTy);
894       
895     } else if (I->getOpcode() == Instruction::Or) {
896       // We can simplify (X|Y) -> X or Y in the user's context if we know that
897       // only bits from X or Y are demanded.
898       
899       // If either the LHS or the RHS are One, the result is One.
900       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
901                         RHSKnownZero, RHSKnownOne, Depth+1);
902       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
903                         LHSKnownZero, LHSKnownOne, Depth+1);
904       
905       // If all of the demanded bits are known zero on one side, return the
906       // other.  These bits cannot contribute to the result of the 'or' in this
907       // context.
908       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
909           (DemandedMask & ~LHSKnownOne))
910         return I->getOperand(0);
911       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
912           (DemandedMask & ~RHSKnownOne))
913         return I->getOperand(1);
914       
915       // If all of the potentially set bits on one side are known to be set on
916       // the other side, just use the 'other' side.
917       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
918           (DemandedMask & (~RHSKnownZero)))
919         return I->getOperand(0);
920       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
921           (DemandedMask & (~LHSKnownZero)))
922         return I->getOperand(1);
923     }
924     
925     // Compute the KnownZero/KnownOne bits to simplify things downstream.
926     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
927     return 0;
928   }
929   
930   // If this is the root being simplified, allow it to have multiple uses,
931   // just set the DemandedMask to all bits so that we can try to simplify the
932   // operands.  This allows visitTruncInst (for example) to simplify the
933   // operand of a trunc without duplicating all the logic below.
934   if (Depth == 0 && !V->hasOneUse())
935     DemandedMask = APInt::getAllOnesValue(BitWidth);
936   
937   switch (I->getOpcode()) {
938   default:
939     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
940     break;
941   case Instruction::And:
942     // If either the LHS or the RHS are Zero, the result is zero.
943     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944                              RHSKnownZero, RHSKnownOne, Depth+1) ||
945         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
946                              LHSKnownZero, LHSKnownOne, Depth+1))
947       return I;
948     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
949     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
950
951     // If all of the demanded bits are known 1 on one side, return the other.
952     // These bits cannot contribute to the result of the 'and'.
953     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
954         (DemandedMask & ~LHSKnownZero))
955       return I->getOperand(0);
956     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
957         (DemandedMask & ~RHSKnownZero))
958       return I->getOperand(1);
959     
960     // If all of the demanded bits in the inputs are known zeros, return zero.
961     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
962       return Context->getNullValue(VTy);
963       
964     // If the RHS is a constant, see if we can simplify it.
965     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
966       return I;
967       
968     // Output known-1 bits are only known if set in both the LHS & RHS.
969     RHSKnownOne &= LHSKnownOne;
970     // Output known-0 are known to be clear if zero in either the LHS | RHS.
971     RHSKnownZero |= LHSKnownZero;
972     break;
973   case Instruction::Or:
974     // If either the LHS or the RHS are One, the result is One.
975     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
976                              RHSKnownZero, RHSKnownOne, Depth+1) ||
977         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
978                              LHSKnownZero, LHSKnownOne, Depth+1))
979       return I;
980     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
981     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
982     
983     // If all of the demanded bits are known zero on one side, return the other.
984     // These bits cannot contribute to the result of the 'or'.
985     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
986         (DemandedMask & ~LHSKnownOne))
987       return I->getOperand(0);
988     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
989         (DemandedMask & ~RHSKnownOne))
990       return I->getOperand(1);
991
992     // If all of the potentially set bits on one side are known to be set on
993     // the other side, just use the 'other' side.
994     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
995         (DemandedMask & (~RHSKnownZero)))
996       return I->getOperand(0);
997     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
998         (DemandedMask & (~LHSKnownZero)))
999       return I->getOperand(1);
1000         
1001     // If the RHS is a constant, see if we can simplify it.
1002     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1003       return I;
1004           
1005     // Output known-0 bits are only known if clear in both the LHS & RHS.
1006     RHSKnownZero &= LHSKnownZero;
1007     // Output known-1 are known to be set if set in either the LHS | RHS.
1008     RHSKnownOne |= LHSKnownOne;
1009     break;
1010   case Instruction::Xor: {
1011     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1013         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1014                              LHSKnownZero, LHSKnownOne, Depth+1))
1015       return I;
1016     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1017     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1018     
1019     // If all of the demanded bits are known zero on one side, return the other.
1020     // These bits cannot contribute to the result of the 'xor'.
1021     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1022       return I->getOperand(0);
1023     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1024       return I->getOperand(1);
1025     
1026     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1028                          (RHSKnownOne & LHSKnownOne);
1029     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1031                         (RHSKnownOne & LHSKnownZero);
1032     
1033     // If all of the demanded bits are known to be zero on one side or the
1034     // other, turn this into an *inclusive* or.
1035     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1037       Instruction *Or =
1038         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1039                                  I->getName());
1040       return InsertNewInstBefore(Or, *I);
1041     }
1042     
1043     // If all of the demanded bits on one side are known, and all of the set
1044     // bits on that side are also known to be set on the other side, turn this
1045     // into an AND, as we know the bits will be cleared.
1046     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1048       // all known
1049       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1050         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1051         Instruction *And = 
1052           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1053         return InsertNewInstBefore(And, *I);
1054       }
1055     }
1056     
1057     // If the RHS is a constant, see if we can simplify it.
1058     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1059     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1060       return I;
1061     
1062     RHSKnownZero = KnownZeroOut;
1063     RHSKnownOne  = KnownOneOut;
1064     break;
1065   }
1066   case Instruction::Select:
1067     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1069         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1070                              LHSKnownZero, LHSKnownOne, Depth+1))
1071       return I;
1072     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1073     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1074     
1075     // If the operands are constants, see if we can simplify them.
1076     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1078       return I;
1079     
1080     // Only known if known in both the LHS and RHS.
1081     RHSKnownOne &= LHSKnownOne;
1082     RHSKnownZero &= LHSKnownZero;
1083     break;
1084   case Instruction::Trunc: {
1085     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1086     DemandedMask.zext(truncBf);
1087     RHSKnownZero.zext(truncBf);
1088     RHSKnownOne.zext(truncBf);
1089     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1090                              RHSKnownZero, RHSKnownOne, Depth+1))
1091       return I;
1092     DemandedMask.trunc(BitWidth);
1093     RHSKnownZero.trunc(BitWidth);
1094     RHSKnownOne.trunc(BitWidth);
1095     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1096     break;
1097   }
1098   case Instruction::BitCast:
1099     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1100       return false;  // vector->int or fp->int?
1101
1102     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103       if (const VectorType *SrcVTy =
1104             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106           // Don't touch a bitcast between vectors of different element counts.
1107           return false;
1108       } else
1109         // Don't touch a scalar-to-vector bitcast.
1110         return false;
1111     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112       // Don't touch a vector-to-scalar bitcast.
1113       return false;
1114
1115     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1116                              RHSKnownZero, RHSKnownOne, Depth+1))
1117       return I;
1118     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1119     break;
1120   case Instruction::ZExt: {
1121     // Compute the bits in the result that are not present in the input.
1122     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1123     
1124     DemandedMask.trunc(SrcBitWidth);
1125     RHSKnownZero.trunc(SrcBitWidth);
1126     RHSKnownOne.trunc(SrcBitWidth);
1127     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return I;
1130     DemandedMask.zext(BitWidth);
1131     RHSKnownZero.zext(BitWidth);
1132     RHSKnownOne.zext(BitWidth);
1133     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1134     // The top bits are known to be zero.
1135     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1136     break;
1137   }
1138   case Instruction::SExt: {
1139     // Compute the bits in the result that are not present in the input.
1140     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1141     
1142     APInt InputDemandedBits = DemandedMask & 
1143                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1144
1145     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1146     // If any of the sign extended bits are demanded, we know that the sign
1147     // bit is demanded.
1148     if ((NewBits & DemandedMask) != 0)
1149       InputDemandedBits.set(SrcBitWidth-1);
1150       
1151     InputDemandedBits.trunc(SrcBitWidth);
1152     RHSKnownZero.trunc(SrcBitWidth);
1153     RHSKnownOne.trunc(SrcBitWidth);
1154     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1155                              RHSKnownZero, RHSKnownOne, Depth+1))
1156       return I;
1157     InputDemandedBits.zext(BitWidth);
1158     RHSKnownZero.zext(BitWidth);
1159     RHSKnownOne.zext(BitWidth);
1160     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1161       
1162     // If the sign bit of the input is known set or clear, then we know the
1163     // top bits of the result.
1164
1165     // If the input sign bit is known zero, or if the NewBits are not demanded
1166     // convert this into a zero extension.
1167     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1168       // Convert to ZExt cast
1169       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170       return InsertNewInstBefore(NewCast, *I);
1171     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1172       RHSKnownOne |= NewBits;
1173     }
1174     break;
1175   }
1176   case Instruction::Add: {
1177     // Figure out what the input bits are.  If the top bits of the and result
1178     // are not demanded, then the add doesn't demand them from its input
1179     // either.
1180     unsigned NLZ = DemandedMask.countLeadingZeros();
1181       
1182     // If there is a constant on the RHS, there are a variety of xformations
1183     // we can do.
1184     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       // If null, this should be simplified elsewhere.  Some of the xforms here
1186       // won't work if the RHS is zero.
1187       if (RHS->isZero())
1188         break;
1189       
1190       // If the top bit of the output is demanded, demand everything from the
1191       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1192       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1193
1194       // Find information about known zero/one bits in the input.
1195       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1196                                LHSKnownZero, LHSKnownOne, Depth+1))
1197         return I;
1198
1199       // If the RHS of the add has bits set that can't affect the input, reduce
1200       // the constant.
1201       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1202         return I;
1203       
1204       // Avoid excess work.
1205       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1206         break;
1207       
1208       // Turn it into OR if input bits are zero.
1209       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1210         Instruction *Or =
1211           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1212                                    I->getName());
1213         return InsertNewInstBefore(Or, *I);
1214       }
1215       
1216       // We can say something about the output known-zero and known-one bits,
1217       // depending on potential carries from the input constant and the
1218       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1219       // bits set and the RHS constant is 0x01001, then we know we have a known
1220       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1221       
1222       // To compute this, we first compute the potential carry bits.  These are
1223       // the bits which may be modified.  I'm not aware of a better way to do
1224       // this scan.
1225       const APInt &RHSVal = RHS->getValue();
1226       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1227       
1228       // Now that we know which bits have carries, compute the known-1/0 sets.
1229       
1230       // Bits are known one if they are known zero in one operand and one in the
1231       // other, and there is no input carry.
1232       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1233                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1234       
1235       // Bits are known zero if they are known zero in both operands and there
1236       // is no input carry.
1237       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1238     } else {
1239       // If the high-bits of this ADD are not demanded, then it does not demand
1240       // the high bits of its LHS or RHS.
1241       if (DemandedMask[BitWidth-1] == 0) {
1242         // Right fill the mask of bits for this ADD to demand the most
1243         // significant bit and all those below it.
1244         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1245         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1247             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1248                                  LHSKnownZero, LHSKnownOne, Depth+1))
1249           return I;
1250       }
1251     }
1252     break;
1253   }
1254   case Instruction::Sub:
1255     // If the high-bits of this SUB are not demanded, then it does not demand
1256     // the high bits of its LHS or RHS.
1257     if (DemandedMask[BitWidth-1] == 0) {
1258       // Right fill the mask of bits for this SUB to demand the most
1259       // significant bit and all those below it.
1260       uint32_t NLZ = DemandedMask.countLeadingZeros();
1261       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1262       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1264           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1265                                LHSKnownZero, LHSKnownOne, Depth+1))
1266         return I;
1267     }
1268     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269     // the known zeros and ones.
1270     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1271     break;
1272   case Instruction::Shl:
1273     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1274       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1275       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1276       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1277                                RHSKnownZero, RHSKnownOne, Depth+1))
1278         return I;
1279       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1280       RHSKnownZero <<= ShiftAmt;
1281       RHSKnownOne  <<= ShiftAmt;
1282       // low bits known zero.
1283       if (ShiftAmt)
1284         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1285     }
1286     break;
1287   case Instruction::LShr:
1288     // For a logical shift right
1289     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1290       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1291       
1292       // Unsigned shift right.
1293       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1294       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1295                                RHSKnownZero, RHSKnownOne, Depth+1))
1296         return I;
1297       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1298       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1300       if (ShiftAmt) {
1301         // Compute the new bits that are at the top now.
1302         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1303         RHSKnownZero |= HighBits;  // high bits known zero.
1304       }
1305     }
1306     break;
1307   case Instruction::AShr:
1308     // If this is an arithmetic shift right and only the low-bit is set, we can
1309     // always convert this into a logical shr, even if the shift amount is
1310     // variable.  The low bit of the shift cannot be an input sign bit unless
1311     // the shift amount is >= the size of the datatype, which is undefined.
1312     if (DemandedMask == 1) {
1313       // Perform the logical shift right.
1314       Instruction *NewVal = BinaryOperator::CreateLShr(
1315                         I->getOperand(0), I->getOperand(1), I->getName());
1316       return InsertNewInstBefore(NewVal, *I);
1317     }    
1318
1319     // If the sign bit is the only bit demanded by this ashr, then there is no
1320     // need to do it, the shift doesn't change the high bit.
1321     if (DemandedMask.isSignBit())
1322       return I->getOperand(0);
1323     
1324     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1326       
1327       // Signed shift right.
1328       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1329       // If any of the "high bits" are demanded, we should set the sign bit as
1330       // demanded.
1331       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332         DemandedMaskIn.set(BitWidth-1);
1333       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1334                                RHSKnownZero, RHSKnownOne, Depth+1))
1335         return I;
1336       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1337       // Compute the new bits that are at the top now.
1338       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1339       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341         
1342       // Handle the sign bits.
1343       APInt SignBit(APInt::getSignBit(BitWidth));
1344       // Adjust to where it is now in the mask.
1345       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1346         
1347       // If the input sign bit is known to be zero, or if none of the top bits
1348       // are demanded, turn this into an unsigned shift right.
1349       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1350           (HighBits & ~DemandedMask) == HighBits) {
1351         // Perform the logical shift right.
1352         Instruction *NewVal = BinaryOperator::CreateLShr(
1353                           I->getOperand(0), SA, I->getName());
1354         return InsertNewInstBefore(NewVal, *I);
1355       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356         RHSKnownOne |= HighBits;
1357       }
1358     }
1359     break;
1360   case Instruction::SRem:
1361     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1362       APInt RA = Rem->getValue().abs();
1363       if (RA.isPowerOf2()) {
1364         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1365           return I->getOperand(0);
1366
1367         APInt LowBits = RA - 1;
1368         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1369         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1370                                  LHSKnownZero, LHSKnownOne, Depth+1))
1371           return I;
1372
1373         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374           LHSKnownZero |= ~LowBits;
1375
1376         KnownZero |= LHSKnownZero & DemandedMask;
1377
1378         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1379       }
1380     }
1381     break;
1382   case Instruction::URem: {
1383     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1385     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386                              KnownZero2, KnownOne2, Depth+1) ||
1387         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1388                              KnownZero2, KnownOne2, Depth+1))
1389       return I;
1390
1391     unsigned Leaders = KnownZero2.countLeadingOnes();
1392     Leaders = std::max(Leaders,
1393                        KnownZero2.countLeadingOnes());
1394     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1395     break;
1396   }
1397   case Instruction::Call:
1398     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399       switch (II->getIntrinsicID()) {
1400       default: break;
1401       case Intrinsic::bswap: {
1402         // If the only bits demanded come from one byte of the bswap result,
1403         // just shift the input byte into position to eliminate the bswap.
1404         unsigned NLZ = DemandedMask.countLeadingZeros();
1405         unsigned NTZ = DemandedMask.countTrailingZeros();
1406           
1407         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1408         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1409         // have 14 leading zeros, round to 8.
1410         NLZ &= ~7;
1411         NTZ &= ~7;
1412         // If we need exactly one byte, we can do this transformation.
1413         if (BitWidth-NLZ-NTZ == 8) {
1414           unsigned ResultBit = NTZ;
1415           unsigned InputBit = BitWidth-NTZ-8;
1416           
1417           // Replace this with either a left or right shift to get the byte into
1418           // the right place.
1419           Instruction *NewVal;
1420           if (InputBit > ResultBit)
1421             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1422                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1423           else
1424             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1425                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1426           NewVal->takeName(I);
1427           return InsertNewInstBefore(NewVal, *I);
1428         }
1429           
1430         // TODO: Could compute known zero/one bits based on the input.
1431         break;
1432       }
1433       }
1434     }
1435     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1436     break;
1437   }
1438   
1439   // If the client is only demanding bits that we know, return the known
1440   // constant.
1441   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1442     Constant *C = Context->getConstantInt(RHSKnownOne);
1443     if (isa<PointerType>(V->getType()))
1444       C = Context->getConstantExprIntToPtr(C, V->getType());
1445     return C;
1446   }
1447   return false;
1448 }
1449
1450
1451 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1452 /// any number of elements. DemandedElts contains the set of elements that are
1453 /// actually used by the caller.  This method analyzes which elements of the
1454 /// operand are undef and returns that information in UndefElts.
1455 ///
1456 /// If the information about demanded elements can be used to simplify the
1457 /// operation, the operation is simplified, then the resultant value is
1458 /// returned.  This returns null if no change was made.
1459 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1460                                                 APInt& UndefElts,
1461                                                 unsigned Depth) {
1462   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1463   APInt EltMask(APInt::getAllOnesValue(VWidth));
1464   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1465
1466   if (isa<UndefValue>(V)) {
1467     // If the entire vector is undefined, just return this info.
1468     UndefElts = EltMask;
1469     return 0;
1470   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471     UndefElts = EltMask;
1472     return Context->getUndef(V->getType());
1473   }
1474
1475   UndefElts = 0;
1476   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1478     Constant *Undef = Context->getUndef(EltTy);
1479
1480     std::vector<Constant*> Elts;
1481     for (unsigned i = 0; i != VWidth; ++i)
1482       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1483         Elts.push_back(Undef);
1484         UndefElts.set(i);
1485       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1486         Elts.push_back(Undef);
1487         UndefElts.set(i);
1488       } else {                               // Otherwise, defined.
1489         Elts.push_back(CP->getOperand(i));
1490       }
1491
1492     // If we changed the constant, return it.
1493     Constant *NewCP = Context->getConstantVector(Elts);
1494     return NewCP != CP ? NewCP : 0;
1495   } else if (isa<ConstantAggregateZero>(V)) {
1496     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1497     // set to undef.
1498     
1499     // Check if this is identity. If so, return 0 since we are not simplifying
1500     // anything.
1501     if (DemandedElts == ((1ULL << VWidth) -1))
1502       return 0;
1503     
1504     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1505     Constant *Zero = Context->getNullValue(EltTy);
1506     Constant *Undef = Context->getUndef(EltTy);
1507     std::vector<Constant*> Elts;
1508     for (unsigned i = 0; i != VWidth; ++i) {
1509       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510       Elts.push_back(Elt);
1511     }
1512     UndefElts = DemandedElts ^ EltMask;
1513     return Context->getConstantVector(Elts);
1514   }
1515   
1516   // Limit search depth.
1517   if (Depth == 10)
1518     return 0;
1519
1520   // If multiple users are using the root value, procede with
1521   // simplification conservatively assuming that all elements
1522   // are needed.
1523   if (!V->hasOneUse()) {
1524     // Quit if we find multiple users of a non-root value though.
1525     // They'll be handled when it's their turn to be visited by
1526     // the main instcombine process.
1527     if (Depth != 0)
1528       // TODO: Just compute the UndefElts information recursively.
1529       return 0;
1530
1531     // Conservatively assume that all elements are needed.
1532     DemandedElts = EltMask;
1533   }
1534   
1535   Instruction *I = dyn_cast<Instruction>(V);
1536   if (!I) return 0;        // Only analyze instructions.
1537   
1538   bool MadeChange = false;
1539   APInt UndefElts2(VWidth, 0);
1540   Value *TmpV;
1541   switch (I->getOpcode()) {
1542   default: break;
1543     
1544   case Instruction::InsertElement: {
1545     // If this is a variable index, we don't know which element it overwrites.
1546     // demand exactly the same input as we produce.
1547     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1548     if (Idx == 0) {
1549       // Note that we can't propagate undef elt info, because we don't know
1550       // which elt is getting updated.
1551       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552                                         UndefElts2, Depth+1);
1553       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554       break;
1555     }
1556     
1557     // If this is inserting an element that isn't demanded, remove this
1558     // insertelement.
1559     unsigned IdxNo = Idx->getZExtValue();
1560     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1561       return AddSoonDeadInstToWorklist(*I, 0);
1562     
1563     // Otherwise, the element inserted overwrites whatever was there, so the
1564     // input demanded set is simpler than the output set.
1565     APInt DemandedElts2 = DemandedElts;
1566     DemandedElts2.clear(IdxNo);
1567     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1568                                       UndefElts, Depth+1);
1569     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571     // The inserted element is defined.
1572     UndefElts.clear(IdxNo);
1573     break;
1574   }
1575   case Instruction::ShuffleVector: {
1576     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1577     uint64_t LHSVWidth =
1578       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1579     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1580     for (unsigned i = 0; i < VWidth; i++) {
1581       if (DemandedElts[i]) {
1582         unsigned MaskVal = Shuffle->getMaskValue(i);
1583         if (MaskVal != -1u) {
1584           assert(MaskVal < LHSVWidth * 2 &&
1585                  "shufflevector mask index out of range!");
1586           if (MaskVal < LHSVWidth)
1587             LeftDemanded.set(MaskVal);
1588           else
1589             RightDemanded.set(MaskVal - LHSVWidth);
1590         }
1591       }
1592     }
1593
1594     APInt UndefElts4(LHSVWidth, 0);
1595     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1596                                       UndefElts4, Depth+1);
1597     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599     APInt UndefElts3(LHSVWidth, 0);
1600     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601                                       UndefElts3, Depth+1);
1602     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1603
1604     bool NewUndefElts = false;
1605     for (unsigned i = 0; i < VWidth; i++) {
1606       unsigned MaskVal = Shuffle->getMaskValue(i);
1607       if (MaskVal == -1u) {
1608         UndefElts.set(i);
1609       } else if (MaskVal < LHSVWidth) {
1610         if (UndefElts4[MaskVal]) {
1611           NewUndefElts = true;
1612           UndefElts.set(i);
1613         }
1614       } else {
1615         if (UndefElts3[MaskVal - LHSVWidth]) {
1616           NewUndefElts = true;
1617           UndefElts.set(i);
1618         }
1619       }
1620     }
1621
1622     if (NewUndefElts) {
1623       // Add additional discovered undefs.
1624       std::vector<Constant*> Elts;
1625       for (unsigned i = 0; i < VWidth; ++i) {
1626         if (UndefElts[i])
1627           Elts.push_back(Context->getUndef(Type::Int32Ty));
1628         else
1629           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1630                                           Shuffle->getMaskValue(i)));
1631       }
1632       I->setOperand(2, Context->getConstantVector(Elts));
1633       MadeChange = true;
1634     }
1635     break;
1636   }
1637   case Instruction::BitCast: {
1638     // Vector->vector casts only.
1639     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1640     if (!VTy) break;
1641     unsigned InVWidth = VTy->getNumElements();
1642     APInt InputDemandedElts(InVWidth, 0);
1643     unsigned Ratio;
1644
1645     if (VWidth == InVWidth) {
1646       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1647       // elements as are demanded of us.
1648       Ratio = 1;
1649       InputDemandedElts = DemandedElts;
1650     } else if (VWidth > InVWidth) {
1651       // Untested so far.
1652       break;
1653       
1654       // If there are more elements in the result than there are in the source,
1655       // then an input element is live if any of the corresponding output
1656       // elements are live.
1657       Ratio = VWidth/InVWidth;
1658       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1659         if (DemandedElts[OutIdx])
1660           InputDemandedElts.set(OutIdx/Ratio);
1661       }
1662     } else {
1663       // Untested so far.
1664       break;
1665       
1666       // If there are more elements in the source than there are in the result,
1667       // then an input element is live if the corresponding output element is
1668       // live.
1669       Ratio = InVWidth/VWidth;
1670       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1671         if (DemandedElts[InIdx/Ratio])
1672           InputDemandedElts.set(InIdx);
1673     }
1674     
1675     // div/rem demand all inputs, because they don't want divide by zero.
1676     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677                                       UndefElts2, Depth+1);
1678     if (TmpV) {
1679       I->setOperand(0, TmpV);
1680       MadeChange = true;
1681     }
1682     
1683     UndefElts = UndefElts2;
1684     if (VWidth > InVWidth) {
1685       LLVM_UNREACHABLE("Unimp");
1686       // If there are more elements in the result than there are in the source,
1687       // then an output element is undef if the corresponding input element is
1688       // undef.
1689       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1690         if (UndefElts2[OutIdx/Ratio])
1691           UndefElts.set(OutIdx);
1692     } else if (VWidth < InVWidth) {
1693       LLVM_UNREACHABLE("Unimp");
1694       // If there are more elements in the source than there are in the result,
1695       // then a result element is undef if all of the corresponding input
1696       // elements are undef.
1697       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1698       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1699         if (!UndefElts2[InIdx])            // Not undef?
1700           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1701     }
1702     break;
1703   }
1704   case Instruction::And:
1705   case Instruction::Or:
1706   case Instruction::Xor:
1707   case Instruction::Add:
1708   case Instruction::Sub:
1709   case Instruction::Mul:
1710     // div/rem demand all inputs, because they don't want divide by zero.
1711     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712                                       UndefElts, Depth+1);
1713     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715                                       UndefElts2, Depth+1);
1716     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1717       
1718     // Output elements are undefined if both are undefined.  Consider things
1719     // like undef&0.  The result is known zero, not undef.
1720     UndefElts &= UndefElts2;
1721     break;
1722     
1723   case Instruction::Call: {
1724     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1725     if (!II) break;
1726     switch (II->getIntrinsicID()) {
1727     default: break;
1728       
1729     // Binary vector operations that work column-wise.  A dest element is a
1730     // function of the corresponding input elements from the two inputs.
1731     case Intrinsic::x86_sse_sub_ss:
1732     case Intrinsic::x86_sse_mul_ss:
1733     case Intrinsic::x86_sse_min_ss:
1734     case Intrinsic::x86_sse_max_ss:
1735     case Intrinsic::x86_sse2_sub_sd:
1736     case Intrinsic::x86_sse2_mul_sd:
1737     case Intrinsic::x86_sse2_min_sd:
1738     case Intrinsic::x86_sse2_max_sd:
1739       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740                                         UndefElts, Depth+1);
1741       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743                                         UndefElts2, Depth+1);
1744       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1745
1746       // If only the low elt is demanded and this is a scalarizable intrinsic,
1747       // scalarize it now.
1748       if (DemandedElts == 1) {
1749         switch (II->getIntrinsicID()) {
1750         default: break;
1751         case Intrinsic::x86_sse_sub_ss:
1752         case Intrinsic::x86_sse_mul_ss:
1753         case Intrinsic::x86_sse2_sub_sd:
1754         case Intrinsic::x86_sse2_mul_sd:
1755           // TODO: Lower MIN/MAX/ABS/etc
1756           Value *LHS = II->getOperand(1);
1757           Value *RHS = II->getOperand(2);
1758           // Extract the element as scalars.
1759           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1760           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1761           
1762           switch (II->getIntrinsicID()) {
1763           default: LLVM_UNREACHABLE("Case stmts out of sync!");
1764           case Intrinsic::x86_sse_sub_ss:
1765           case Intrinsic::x86_sse2_sub_sd:
1766             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1767                                                         II->getName()), *II);
1768             break;
1769           case Intrinsic::x86_sse_mul_ss:
1770           case Intrinsic::x86_sse2_mul_sd:
1771             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1772                                                          II->getName()), *II);
1773             break;
1774           }
1775           
1776           Instruction *New =
1777             InsertElementInst::Create(
1778               Context->getUndef(II->getType()), TmpV, 0U, II->getName());
1779           InsertNewInstBefore(New, *II);
1780           AddSoonDeadInstToWorklist(*II, 0);
1781           return New;
1782         }            
1783       }
1784         
1785       // Output elements are undefined if both are undefined.  Consider things
1786       // like undef&0.  The result is known zero, not undef.
1787       UndefElts &= UndefElts2;
1788       break;
1789     }
1790     break;
1791   }
1792   }
1793   return MadeChange ? I : 0;
1794 }
1795
1796
1797 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1798 /// function is designed to check a chain of associative operators for a
1799 /// potential to apply a certain optimization.  Since the optimization may be
1800 /// applicable if the expression was reassociated, this checks the chain, then
1801 /// reassociates the expression as necessary to expose the optimization
1802 /// opportunity.  This makes use of a special Functor, which must define
1803 /// 'shouldApply' and 'apply' methods.
1804 ///
1805 template<typename Functor>
1806 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1807                                    LLVMContext *Context) {
1808   unsigned Opcode = Root.getOpcode();
1809   Value *LHS = Root.getOperand(0);
1810
1811   // Quick check, see if the immediate LHS matches...
1812   if (F.shouldApply(LHS))
1813     return F.apply(Root);
1814
1815   // Otherwise, if the LHS is not of the same opcode as the root, return.
1816   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1817   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1818     // Should we apply this transform to the RHS?
1819     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1820
1821     // If not to the RHS, check to see if we should apply to the LHS...
1822     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1824       ShouldApply = true;
1825     }
1826
1827     // If the functor wants to apply the optimization to the RHS of LHSI,
1828     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1829     if (ShouldApply) {
1830       // Now all of the instructions are in the current basic block, go ahead
1831       // and perform the reassociation.
1832       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1833
1834       // First move the selected RHS to the LHS of the root...
1835       Root.setOperand(0, LHSI->getOperand(1));
1836
1837       // Make what used to be the LHS of the root be the user of the root...
1838       Value *ExtraOperand = TmpLHSI->getOperand(1);
1839       if (&Root == TmpLHSI) {
1840         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1841         return 0;
1842       }
1843       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1844       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1845       BasicBlock::iterator ARI = &Root; ++ARI;
1846       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1847       ARI = Root;
1848
1849       // Now propagate the ExtraOperand down the chain of instructions until we
1850       // get to LHSI.
1851       while (TmpLHSI != LHSI) {
1852         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1853         // Move the instruction to immediately before the chain we are
1854         // constructing to avoid breaking dominance properties.
1855         NextLHSI->moveBefore(ARI);
1856         ARI = NextLHSI;
1857
1858         Value *NextOp = NextLHSI->getOperand(1);
1859         NextLHSI->setOperand(1, ExtraOperand);
1860         TmpLHSI = NextLHSI;
1861         ExtraOperand = NextOp;
1862       }
1863
1864       // Now that the instructions are reassociated, have the functor perform
1865       // the transformation...
1866       return F.apply(Root);
1867     }
1868
1869     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1870   }
1871   return 0;
1872 }
1873
1874 namespace {
1875
1876 // AddRHS - Implements: X + X --> X << 1
1877 struct AddRHS {
1878   Value *RHS;
1879   LLVMContext *Context;
1880   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1881   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1882   Instruction *apply(BinaryOperator &Add) const {
1883     return BinaryOperator::CreateShl(Add.getOperand(0),
1884                                      Context->getConstantInt(Add.getType(), 1));
1885   }
1886 };
1887
1888 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1889 //                 iff C1&C2 == 0
1890 struct AddMaskingAnd {
1891   Constant *C2;
1892   LLVMContext *Context;
1893   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1894   bool shouldApply(Value *LHS) const {
1895     ConstantInt *C1;
1896     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1897            Context->getConstantExprAnd(C1, C2)->isNullValue();
1898   }
1899   Instruction *apply(BinaryOperator &Add) const {
1900     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1901   }
1902 };
1903
1904 }
1905
1906 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1907                                              InstCombiner *IC) {
1908   LLVMContext *Context = IC->getContext();
1909   
1910   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1911     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1912   }
1913
1914   // Figure out if the constant is the left or the right argument.
1915   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1916   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1917
1918   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1919     if (ConstIsRHS)
1920       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1921     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1922   }
1923
1924   Value *Op0 = SO, *Op1 = ConstOperand;
1925   if (!ConstIsRHS)
1926     std::swap(Op0, Op1);
1927   Instruction *New;
1928   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1929     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1930   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1931     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1932                           Op0, Op1, SO->getName()+".cmp");
1933   else {
1934     LLVM_UNREACHABLE("Unknown binary instruction type!");
1935   }
1936   return IC->InsertNewInstBefore(New, I);
1937 }
1938
1939 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1940 // constant as the other operand, try to fold the binary operator into the
1941 // select arguments.  This also works for Cast instructions, which obviously do
1942 // not have a second operand.
1943 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1944                                      InstCombiner *IC) {
1945   // Don't modify shared select instructions
1946   if (!SI->hasOneUse()) return 0;
1947   Value *TV = SI->getOperand(1);
1948   Value *FV = SI->getOperand(2);
1949
1950   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1951     // Bool selects with constant operands can be folded to logical ops.
1952     if (SI->getType() == Type::Int1Ty) return 0;
1953
1954     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1955     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1956
1957     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1958                               SelectFalseVal);
1959   }
1960   return 0;
1961 }
1962
1963
1964 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1965 /// node as operand #0, see if we can fold the instruction into the PHI (which
1966 /// is only possible if all operands to the PHI are constants).
1967 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1968   PHINode *PN = cast<PHINode>(I.getOperand(0));
1969   unsigned NumPHIValues = PN->getNumIncomingValues();
1970   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1971
1972   // Check to see if all of the operands of the PHI are constants.  If there is
1973   // one non-constant value, remember the BB it is.  If there is more than one
1974   // or if *it* is a PHI, bail out.
1975   BasicBlock *NonConstBB = 0;
1976   for (unsigned i = 0; i != NumPHIValues; ++i)
1977     if (!isa<Constant>(PN->getIncomingValue(i))) {
1978       if (NonConstBB) return 0;  // More than one non-const value.
1979       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1980       NonConstBB = PN->getIncomingBlock(i);
1981       
1982       // If the incoming non-constant value is in I's block, we have an infinite
1983       // loop.
1984       if (NonConstBB == I.getParent())
1985         return 0;
1986     }
1987   
1988   // If there is exactly one non-constant value, we can insert a copy of the
1989   // operation in that block.  However, if this is a critical edge, we would be
1990   // inserting the computation one some other paths (e.g. inside a loop).  Only
1991   // do this if the pred block is unconditionally branching into the phi block.
1992   if (NonConstBB) {
1993     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1994     if (!BI || !BI->isUnconditional()) return 0;
1995   }
1996
1997   // Okay, we can do the transformation: create the new PHI node.
1998   PHINode *NewPN = PHINode::Create(I.getType(), "");
1999   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2000   InsertNewInstBefore(NewPN, *PN);
2001   NewPN->takeName(PN);
2002
2003   // Next, add all of the operands to the PHI.
2004   if (I.getNumOperands() == 2) {
2005     Constant *C = cast<Constant>(I.getOperand(1));
2006     for (unsigned i = 0; i != NumPHIValues; ++i) {
2007       Value *InV = 0;
2008       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2009         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2010           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2011         else
2012           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2013       } else {
2014         assert(PN->getIncomingBlock(i) == NonConstBB);
2015         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2016           InV = BinaryOperator::Create(BO->getOpcode(),
2017                                        PN->getIncomingValue(i), C, "phitmp",
2018                                        NonConstBB->getTerminator());
2019         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2020           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2021                                 CI->getPredicate(),
2022                                 PN->getIncomingValue(i), C, "phitmp",
2023                                 NonConstBB->getTerminator());
2024         else
2025           LLVM_UNREACHABLE("Unknown binop!");
2026         
2027         AddToWorkList(cast<Instruction>(InV));
2028       }
2029       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2030     }
2031   } else { 
2032     CastInst *CI = cast<CastInst>(&I);
2033     const Type *RetTy = CI->getType();
2034     for (unsigned i = 0; i != NumPHIValues; ++i) {
2035       Value *InV;
2036       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2037         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2038       } else {
2039         assert(PN->getIncomingBlock(i) == NonConstBB);
2040         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2041                                I.getType(), "phitmp", 
2042                                NonConstBB->getTerminator());
2043         AddToWorkList(cast<Instruction>(InV));
2044       }
2045       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2046     }
2047   }
2048   return ReplaceInstUsesWith(I, NewPN);
2049 }
2050
2051
2052 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2053 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2054 /// This basically requires proving that the add in the original type would not
2055 /// overflow to change the sign bit or have a carry out.
2056 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057   // There are different heuristics we can use for this.  Here are some simple
2058   // ones.
2059   
2060   // Add has the property that adding any two 2's complement numbers can only 
2061   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2062   // have at least two sign bits, we know that the addition of the two values will
2063   // sign extend fine.
2064   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065     return true;
2066   
2067   
2068   // If one of the operands only has one non-zero bit, and if the other operand
2069   // has a known-zero bit in a more significant place than it (not including the
2070   // sign bit) the ripple may go up to and fill the zero, but won't change the
2071   // sign.  For example, (X & ~4) + 1.
2072   
2073   // TODO: Implement.
2074   
2075   return false;
2076 }
2077
2078
2079 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2080   bool Changed = SimplifyCommutative(I);
2081   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2082
2083   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2084     // X + undef -> undef
2085     if (isa<UndefValue>(RHS))
2086       return ReplaceInstUsesWith(I, RHS);
2087
2088     // X + 0 --> X
2089     if (RHSC->isNullValue())
2090       return ReplaceInstUsesWith(I, LHS);
2091
2092     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2093       // X + (signbit) --> X ^ signbit
2094       const APInt& Val = CI->getValue();
2095       uint32_t BitWidth = Val.getBitWidth();
2096       if (Val == APInt::getSignBit(BitWidth))
2097         return BinaryOperator::CreateXor(LHS, RHS);
2098       
2099       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2100       // (X & 254)+1 -> (X&254)|1
2101       if (SimplifyDemandedInstructionBits(I))
2102         return &I;
2103
2104       // zext(i1) - 1  ->  select i1, 0, -1
2105       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106         if (CI->isAllOnesValue() &&
2107             ZI->getOperand(0)->getType() == Type::Int1Ty)
2108           return SelectInst::Create(ZI->getOperand(0),
2109                                     Context->getNullValue(I.getType()),
2110                               Context->getAllOnesValue(I.getType()));
2111     }
2112
2113     if (isa<PHINode>(LHS))
2114       if (Instruction *NV = FoldOpIntoPhi(I))
2115         return NV;
2116     
2117     ConstantInt *XorRHS = 0;
2118     Value *XorLHS = 0;
2119     if (isa<ConstantInt>(RHSC) &&
2120         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2121       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2122       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2123       
2124       uint32_t Size = TySizeBits / 2;
2125       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2126       APInt CFF80Val(-C0080Val);
2127       do {
2128         if (TySizeBits > Size) {
2129           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2130           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2131           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2132               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2133             // This is a sign extend if the top bits are known zero.
2134             if (!MaskedValueIsZero(XorLHS, 
2135                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2136               Size = 0;  // Not a sign ext, but can't be any others either.
2137             break;
2138           }
2139         }
2140         Size >>= 1;
2141         C0080Val = APIntOps::lshr(C0080Val, Size);
2142         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2143       } while (Size >= 1);
2144       
2145       // FIXME: This shouldn't be necessary. When the backends can handle types
2146       // with funny bit widths then this switch statement should be removed. It
2147       // is just here to get the size of the "middle" type back up to something
2148       // that the back ends can handle.
2149       const Type *MiddleType = 0;
2150       switch (Size) {
2151         default: break;
2152         case 32: MiddleType = Type::Int32Ty; break;
2153         case 16: MiddleType = Type::Int16Ty; break;
2154         case  8: MiddleType = Type::Int8Ty; break;
2155       }
2156       if (MiddleType) {
2157         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2158         InsertNewInstBefore(NewTrunc, I);
2159         return new SExtInst(NewTrunc, I.getType(), I.getName());
2160       }
2161     }
2162   }
2163
2164   if (I.getType() == Type::Int1Ty)
2165     return BinaryOperator::CreateXor(LHS, RHS);
2166
2167   // X + X --> X << 1
2168   if (I.getType()->isInteger()) {
2169     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2170       return Result;
2171
2172     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2173       if (RHSI->getOpcode() == Instruction::Sub)
2174         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2175           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2176     }
2177     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2178       if (LHSI->getOpcode() == Instruction::Sub)
2179         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2180           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2181     }
2182   }
2183
2184   // -A + B  -->  B - A
2185   // -A + -B  -->  -(A + B)
2186   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2187     if (LHS->getType()->isIntOrIntVector()) {
2188       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2189         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2190         InsertNewInstBefore(NewAdd, I);
2191         return BinaryOperator::CreateNeg(*Context, NewAdd);
2192       }
2193     }
2194     
2195     return BinaryOperator::CreateSub(RHS, LHSV);
2196   }
2197
2198   // A + -B  -->  A - B
2199   if (!isa<Constant>(RHS))
2200     if (Value *V = dyn_castNegVal(RHS, Context))
2201       return BinaryOperator::CreateSub(LHS, V);
2202
2203
2204   ConstantInt *C2;
2205   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2206     if (X == RHS)   // X*C + X --> X * (C+1)
2207       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2208
2209     // X*C1 + X*C2 --> X * (C1+C2)
2210     ConstantInt *C1;
2211     if (X == dyn_castFoldableMul(RHS, C1, Context))
2212       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2213   }
2214
2215   // X + X*C --> X * (C+1)
2216   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2217     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2218
2219   // X + ~X --> -1   since   ~X = -X-1
2220   if (dyn_castNotVal(LHS, Context) == RHS ||
2221       dyn_castNotVal(RHS, Context) == LHS)
2222     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2223   
2224
2225   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2226   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2227     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2228       return R;
2229   
2230   // A+B --> A|B iff A and B have no bits set in common.
2231   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2232     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2233     APInt LHSKnownOne(IT->getBitWidth(), 0);
2234     APInt LHSKnownZero(IT->getBitWidth(), 0);
2235     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2236     if (LHSKnownZero != 0) {
2237       APInt RHSKnownOne(IT->getBitWidth(), 0);
2238       APInt RHSKnownZero(IT->getBitWidth(), 0);
2239       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2240       
2241       // No bits in common -> bitwise or.
2242       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2243         return BinaryOperator::CreateOr(LHS, RHS);
2244     }
2245   }
2246
2247   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2248   if (I.getType()->isIntOrIntVector()) {
2249     Value *W, *X, *Y, *Z;
2250     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2251         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2252       if (W != Y) {
2253         if (W == Z) {
2254           std::swap(Y, Z);
2255         } else if (Y == X) {
2256           std::swap(W, X);
2257         } else if (X == Z) {
2258           std::swap(Y, Z);
2259           std::swap(W, X);
2260         }
2261       }
2262
2263       if (W == Y) {
2264         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2265                                                             LHS->getName()), I);
2266         return BinaryOperator::CreateMul(W, NewAdd);
2267       }
2268     }
2269   }
2270
2271   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2272     Value *X = 0;
2273     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2274       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2275
2276     // (X & FF00) + xx00  -> (X+xx00) & FF00
2277     if (LHS->hasOneUse() &&
2278         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2279       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2280       if (Anded == CRHS) {
2281         // See if all bits from the first bit set in the Add RHS up are included
2282         // in the mask.  First, get the rightmost bit.
2283         const APInt& AddRHSV = CRHS->getValue();
2284
2285         // Form a mask of all bits from the lowest bit added through the top.
2286         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2287
2288         // See if the and mask includes all of these bits.
2289         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2290
2291         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292           // Okay, the xform is safe.  Insert the new add pronto.
2293           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2294                                                             LHS->getName()), I);
2295           return BinaryOperator::CreateAnd(NewAdd, C2);
2296         }
2297       }
2298     }
2299
2300     // Try to fold constant add into select arguments.
2301     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2302       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2303         return R;
2304   }
2305
2306   // add (cast *A to intptrtype) B -> 
2307   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2308   {
2309     CastInst *CI = dyn_cast<CastInst>(LHS);
2310     Value *Other = RHS;
2311     if (!CI) {
2312       CI = dyn_cast<CastInst>(RHS);
2313       Other = LHS;
2314     }
2315     if (CI && CI->getType()->isSized() && 
2316         (CI->getType()->getScalarSizeInBits() ==
2317          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2318         && isa<PointerType>(CI->getOperand(0)->getType())) {
2319       unsigned AS =
2320         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2321       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2322                                   Context->getPointerType(Type::Int8Ty, AS), I);
2323       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2324       return new PtrToIntInst(I2, CI->getType());
2325     }
2326   }
2327   
2328   // add (select X 0 (sub n A)) A  -->  select X A n
2329   {
2330     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2331     Value *A = RHS;
2332     if (!SI) {
2333       SI = dyn_cast<SelectInst>(RHS);
2334       A = LHS;
2335     }
2336     if (SI && SI->hasOneUse()) {
2337       Value *TV = SI->getTrueValue();
2338       Value *FV = SI->getFalseValue();
2339       Value *N;
2340
2341       // Can we fold the add into the argument of the select?
2342       // We check both true and false select arguments for a matching subtract.
2343       if (match(FV, m_Zero(), *Context) &&
2344           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2345         // Fold the add into the true select value.
2346         return SelectInst::Create(SI->getCondition(), N, A);
2347       if (match(TV, m_Zero(), *Context) &&
2348           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2349         // Fold the add into the false select value.
2350         return SelectInst::Create(SI->getCondition(), A, N);
2351     }
2352   }
2353
2354   // Check for (add (sext x), y), see if we can merge this into an
2355   // integer add followed by a sext.
2356   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2357     // (add (sext x), cst) --> (sext (add x, cst'))
2358     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2359       Constant *CI = 
2360         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2361       if (LHSConv->hasOneUse() &&
2362           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2363           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364         // Insert the new, smaller add.
2365         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2366                                                         CI, "addconv");
2367         InsertNewInstBefore(NewAdd, I);
2368         return new SExtInst(NewAdd, I.getType());
2369       }
2370     }
2371     
2372     // (add (sext x), (sext y)) --> (sext (add int x, y))
2373     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2374       // Only do this if x/y have the same type, if at last one of them has a
2375       // single use (so we don't increase the number of sexts), and if the
2376       // integer add will not overflow.
2377       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380                                    RHSConv->getOperand(0))) {
2381         // Insert the new integer add.
2382         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2383                                                         RHSConv->getOperand(0),
2384                                                         "addconv");
2385         InsertNewInstBefore(NewAdd, I);
2386         return new SExtInst(NewAdd, I.getType());
2387       }
2388     }
2389   }
2390
2391   return Changed ? &I : 0;
2392 }
2393
2394 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2395   bool Changed = SimplifyCommutative(I);
2396   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2397
2398   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2399     // X + 0 --> X
2400     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2401       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2402                               (I.getType())->getValueAPF()))
2403         return ReplaceInstUsesWith(I, LHS);
2404     }
2405
2406     if (isa<PHINode>(LHS))
2407       if (Instruction *NV = FoldOpIntoPhi(I))
2408         return NV;
2409   }
2410
2411   // -A + B  -->  B - A
2412   // -A + -B  -->  -(A + B)
2413   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2414     return BinaryOperator::CreateFSub(RHS, LHSV);
2415
2416   // A + -B  -->  A - B
2417   if (!isa<Constant>(RHS))
2418     if (Value *V = dyn_castFNegVal(RHS, Context))
2419       return BinaryOperator::CreateFSub(LHS, V);
2420
2421   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2422   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2423     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2424       return ReplaceInstUsesWith(I, LHS);
2425
2426   // Check for (add double (sitofp x), y), see if we can merge this into an
2427   // integer add followed by a promotion.
2428   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2429     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2430     // ... if the constant fits in the integer value.  This is useful for things
2431     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2432     // requires a constant pool load, and generally allows the add to be better
2433     // instcombined.
2434     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2435       Constant *CI = 
2436       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2437       if (LHSConv->hasOneUse() &&
2438           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2439           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2440         // Insert the new integer add.
2441         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2442                                                         CI, "addconv");
2443         InsertNewInstBefore(NewAdd, I);
2444         return new SIToFPInst(NewAdd, I.getType());
2445       }
2446     }
2447     
2448     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2449     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2450       // Only do this if x/y have the same type, if at last one of them has a
2451       // single use (so we don't increase the number of int->fp conversions),
2452       // and if the integer add will not overflow.
2453       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2454           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2455           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2456                                    RHSConv->getOperand(0))) {
2457         // Insert the new integer add.
2458         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2459                                                         RHSConv->getOperand(0),
2460                                                         "addconv");
2461         InsertNewInstBefore(NewAdd, I);
2462         return new SIToFPInst(NewAdd, I.getType());
2463       }
2464     }
2465   }
2466   
2467   return Changed ? &I : 0;
2468 }
2469
2470 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2471   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2472
2473   if (Op0 == Op1)                        // sub X, X  -> 0
2474     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2475
2476   // If this is a 'B = x-(-A)', change to B = x+A...
2477   if (Value *V = dyn_castNegVal(Op1, Context))
2478     return BinaryOperator::CreateAdd(Op0, V);
2479
2480   if (isa<UndefValue>(Op0))
2481     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2482   if (isa<UndefValue>(Op1))
2483     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2484
2485   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2486     // Replace (-1 - A) with (~A)...
2487     if (C->isAllOnesValue())
2488       return BinaryOperator::CreateNot(*Context, Op1);
2489
2490     // C - ~X == X + (1+C)
2491     Value *X = 0;
2492     if (match(Op1, m_Not(m_Value(X)), *Context))
2493       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2494
2495     // -(X >>u 31) -> (X >>s 31)
2496     // -(X >>s 31) -> (X >>u 31)
2497     if (C->isZero()) {
2498       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2499         if (SI->getOpcode() == Instruction::LShr) {
2500           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2501             // Check to see if we are shifting out everything but the sign bit.
2502             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2503                 SI->getType()->getPrimitiveSizeInBits()-1) {
2504               // Ok, the transformation is safe.  Insert AShr.
2505               return BinaryOperator::Create(Instruction::AShr, 
2506                                           SI->getOperand(0), CU, SI->getName());
2507             }
2508           }
2509         }
2510         else if (SI->getOpcode() == Instruction::AShr) {
2511           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2512             // Check to see if we are shifting out everything but the sign bit.
2513             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2514                 SI->getType()->getPrimitiveSizeInBits()-1) {
2515               // Ok, the transformation is safe.  Insert LShr. 
2516               return BinaryOperator::CreateLShr(
2517                                           SI->getOperand(0), CU, SI->getName());
2518             }
2519           }
2520         }
2521       }
2522     }
2523
2524     // Try to fold constant sub into select arguments.
2525     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2526       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2527         return R;
2528   }
2529
2530   if (I.getType() == Type::Int1Ty)
2531     return BinaryOperator::CreateXor(Op0, Op1);
2532
2533   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2534     if (Op1I->getOpcode() == Instruction::Add) {
2535       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2536         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2537                                          I.getName());
2538       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2539         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2540                                          I.getName());
2541       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2542         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2543           // C1-(X+C2) --> (C1-C2)-X
2544           return BinaryOperator::CreateSub(
2545             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2546       }
2547     }
2548
2549     if (Op1I->hasOneUse()) {
2550       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2551       // is not used by anyone else...
2552       //
2553       if (Op1I->getOpcode() == Instruction::Sub) {
2554         // Swap the two operands of the subexpr...
2555         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2556         Op1I->setOperand(0, IIOp1);
2557         Op1I->setOperand(1, IIOp0);
2558
2559         // Create the new top level add instruction...
2560         return BinaryOperator::CreateAdd(Op0, Op1);
2561       }
2562
2563       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2564       //
2565       if (Op1I->getOpcode() == Instruction::And &&
2566           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2567         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2568
2569         Value *NewNot =
2570           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2571                                                         OtherOp, "B.not"), I);
2572         return BinaryOperator::CreateAnd(Op0, NewNot);
2573       }
2574
2575       // 0 - (X sdiv C)  -> (X sdiv -C)
2576       if (Op1I->getOpcode() == Instruction::SDiv)
2577         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2578           if (CSI->isZero())
2579             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2580               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2581                                           Context->getConstantExprNeg(DivRHS));
2582
2583       // X - X*C --> X * (1-C)
2584       ConstantInt *C2 = 0;
2585       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2586         Constant *CP1 = 
2587           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2588                                              C2);
2589         return BinaryOperator::CreateMul(Op0, CP1);
2590       }
2591     }
2592   }
2593
2594   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2595     if (Op0I->getOpcode() == Instruction::Add) {
2596       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2597         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2598       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2599         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2600     } else if (Op0I->getOpcode() == Instruction::Sub) {
2601       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2602         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2603                                          I.getName());
2604     }
2605   }
2606
2607   ConstantInt *C1;
2608   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2609     if (X == Op1)  // X*C - X --> X * (C-1)
2610       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2611
2612     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2613     if (X == dyn_castFoldableMul(Op1, C2, Context))
2614       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2615   }
2616   return 0;
2617 }
2618
2619 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2620   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
2622   // If this is a 'B = x-(-A)', change to B = x+A...
2623   if (Value *V = dyn_castFNegVal(Op1, Context))
2624     return BinaryOperator::CreateFAdd(Op0, V);
2625
2626   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2627     if (Op1I->getOpcode() == Instruction::FAdd) {
2628       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2629         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2630                                           I.getName());
2631       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2632         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2633                                           I.getName());
2634     }
2635   }
2636
2637   return 0;
2638 }
2639
2640 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2641 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2642 /// TrueIfSigned if the result of the comparison is true when the input value is
2643 /// signed.
2644 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2645                            bool &TrueIfSigned) {
2646   switch (pred) {
2647   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2648     TrueIfSigned = true;
2649     return RHS->isZero();
2650   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2651     TrueIfSigned = true;
2652     return RHS->isAllOnesValue();
2653   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2654     TrueIfSigned = false;
2655     return RHS->isAllOnesValue();
2656   case ICmpInst::ICMP_UGT:
2657     // True if LHS u> RHS and RHS == high-bit-mask - 1
2658     TrueIfSigned = true;
2659     return RHS->getValue() ==
2660       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2661   case ICmpInst::ICMP_UGE: 
2662     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2663     TrueIfSigned = true;
2664     return RHS->getValue().isSignBit();
2665   default:
2666     return false;
2667   }
2668 }
2669
2670 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2671   bool Changed = SimplifyCommutative(I);
2672   Value *Op0 = I.getOperand(0);
2673
2674   // TODO: If Op1 is undef and Op0 is finite, return zero.
2675   if (!I.getType()->isFPOrFPVector() &&
2676       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2677     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2678
2679   // Simplify mul instructions with a constant RHS...
2680   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2681     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2682
2683       // ((X << C1)*C2) == (X * (C2 << C1))
2684       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2685         if (SI->getOpcode() == Instruction::Shl)
2686           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2687             return BinaryOperator::CreateMul(SI->getOperand(0),
2688                                         Context->getConstantExprShl(CI, ShOp));
2689
2690       if (CI->isZero())
2691         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2692       if (CI->equalsInt(1))                  // X * 1  == X
2693         return ReplaceInstUsesWith(I, Op0);
2694       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2695         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2696
2697       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2698       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2699         return BinaryOperator::CreateShl(Op0,
2700                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2701       }
2702     } else if (isa<VectorType>(Op1->getType())) {
2703       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2704
2705       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2706         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2707           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2708
2709         // As above, vector X*splat(1.0) -> X in all defined cases.
2710         if (Constant *Splat = Op1V->getSplatValue()) {
2711           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2712             if (CI->equalsInt(1))
2713               return ReplaceInstUsesWith(I, Op0);
2714         }
2715       }
2716     }
2717     
2718     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2719       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2720           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2721         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2722         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2723                                                      Op1, "tmp");
2724         InsertNewInstBefore(Add, I);
2725         Value *C1C2 = Context->getConstantExprMul(Op1, 
2726                                            cast<Constant>(Op0I->getOperand(1)));
2727         return BinaryOperator::CreateAdd(Add, C1C2);
2728         
2729       }
2730
2731     // Try to fold constant mul into select arguments.
2732     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2733       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2734         return R;
2735
2736     if (isa<PHINode>(Op0))
2737       if (Instruction *NV = FoldOpIntoPhi(I))
2738         return NV;
2739   }
2740
2741   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2742     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2743       return BinaryOperator::CreateMul(Op0v, Op1v);
2744
2745   // (X / Y) *  Y = X - (X % Y)
2746   // (X / Y) * -Y = (X % Y) - X
2747   {
2748     Value *Op1 = I.getOperand(1);
2749     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2750     if (!BO ||
2751         (BO->getOpcode() != Instruction::UDiv && 
2752          BO->getOpcode() != Instruction::SDiv)) {
2753       Op1 = Op0;
2754       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2755     }
2756     Value *Neg = dyn_castNegVal(Op1, Context);
2757     if (BO && BO->hasOneUse() &&
2758         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2759         (BO->getOpcode() == Instruction::UDiv ||
2760          BO->getOpcode() == Instruction::SDiv)) {
2761       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2762
2763       Instruction *Rem;
2764       if (BO->getOpcode() == Instruction::UDiv)
2765         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2766       else
2767         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2768
2769       InsertNewInstBefore(Rem, I);
2770       Rem->takeName(BO);
2771
2772       if (Op1BO == Op1)
2773         return BinaryOperator::CreateSub(Op0BO, Rem);
2774       else
2775         return BinaryOperator::CreateSub(Rem, Op0BO);
2776     }
2777   }
2778
2779   if (I.getType() == Type::Int1Ty)
2780     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2781
2782   // If one of the operands of the multiply is a cast from a boolean value, then
2783   // we know the bool is either zero or one, so this is a 'masking' multiply.
2784   // See if we can simplify things based on how the boolean was originally
2785   // formed.
2786   CastInst *BoolCast = 0;
2787   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2788     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2789       BoolCast = CI;
2790   if (!BoolCast)
2791     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2792       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2793         BoolCast = CI;
2794   if (BoolCast) {
2795     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2796       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2797       const Type *SCOpTy = SCIOp0->getType();
2798       bool TIS = false;
2799       
2800       // If the icmp is true iff the sign bit of X is set, then convert this
2801       // multiply into a shift/and combination.
2802       if (isa<ConstantInt>(SCIOp1) &&
2803           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2804           TIS) {
2805         // Shift the X value right to turn it into "all signbits".
2806         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2807                                           SCOpTy->getPrimitiveSizeInBits()-1);
2808         Value *V =
2809           InsertNewInstBefore(
2810             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2811                                             BoolCast->getOperand(0)->getName()+
2812                                             ".mask"), I);
2813
2814         // If the multiply type is not the same as the source type, sign extend
2815         // or truncate to the multiply type.
2816         if (I.getType() != V->getType()) {
2817           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2818           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2819           Instruction::CastOps opcode = 
2820             (SrcBits == DstBits ? Instruction::BitCast : 
2821              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2822           V = InsertCastBefore(opcode, V, I.getType(), I);
2823         }
2824
2825         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2826         return BinaryOperator::CreateAnd(V, OtherOp);
2827       }
2828     }
2829   }
2830
2831   return Changed ? &I : 0;
2832 }
2833
2834 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2835   bool Changed = SimplifyCommutative(I);
2836   Value *Op0 = I.getOperand(0);
2837
2838   // Simplify mul instructions with a constant RHS...
2839   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2840     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2841       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2842       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2843       if (Op1F->isExactlyValue(1.0))
2844         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2845     } else if (isa<VectorType>(Op1->getType())) {
2846       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2847         // As above, vector X*splat(1.0) -> X in all defined cases.
2848         if (Constant *Splat = Op1V->getSplatValue()) {
2849           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2850             if (F->isExactlyValue(1.0))
2851               return ReplaceInstUsesWith(I, Op0);
2852         }
2853       }
2854     }
2855
2856     // Try to fold constant mul into select arguments.
2857     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2858       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2859         return R;
2860
2861     if (isa<PHINode>(Op0))
2862       if (Instruction *NV = FoldOpIntoPhi(I))
2863         return NV;
2864   }
2865
2866   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2867     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2868       return BinaryOperator::CreateFMul(Op0v, Op1v);
2869
2870   return Changed ? &I : 0;
2871 }
2872
2873 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2874 /// instruction.
2875 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2876   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2877   
2878   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2879   int NonNullOperand = -1;
2880   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2881     if (ST->isNullValue())
2882       NonNullOperand = 2;
2883   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2884   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2885     if (ST->isNullValue())
2886       NonNullOperand = 1;
2887   
2888   if (NonNullOperand == -1)
2889     return false;
2890   
2891   Value *SelectCond = SI->getOperand(0);
2892   
2893   // Change the div/rem to use 'Y' instead of the select.
2894   I.setOperand(1, SI->getOperand(NonNullOperand));
2895   
2896   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2897   // problem.  However, the select, or the condition of the select may have
2898   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2899   // propagate the known value for the select into other uses of it, and
2900   // propagate a known value of the condition into its other users.
2901   
2902   // If the select and condition only have a single use, don't bother with this,
2903   // early exit.
2904   if (SI->use_empty() && SelectCond->hasOneUse())
2905     return true;
2906   
2907   // Scan the current block backward, looking for other uses of SI.
2908   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2909   
2910   while (BBI != BBFront) {
2911     --BBI;
2912     // If we found a call to a function, we can't assume it will return, so
2913     // information from below it cannot be propagated above it.
2914     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2915       break;
2916     
2917     // Replace uses of the select or its condition with the known values.
2918     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2919          I != E; ++I) {
2920       if (*I == SI) {
2921         *I = SI->getOperand(NonNullOperand);
2922         AddToWorkList(BBI);
2923       } else if (*I == SelectCond) {
2924         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2925                                    Context->getConstantIntFalse();
2926         AddToWorkList(BBI);
2927       }
2928     }
2929     
2930     // If we past the instruction, quit looking for it.
2931     if (&*BBI == SI)
2932       SI = 0;
2933     if (&*BBI == SelectCond)
2934       SelectCond = 0;
2935     
2936     // If we ran out of things to eliminate, break out of the loop.
2937     if (SelectCond == 0 && SI == 0)
2938       break;
2939     
2940   }
2941   return true;
2942 }
2943
2944
2945 /// This function implements the transforms on div instructions that work
2946 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2947 /// used by the visitors to those instructions.
2948 /// @brief Transforms common to all three div instructions
2949 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2951
2952   // undef / X -> 0        for integer.
2953   // undef / X -> undef    for FP (the undef could be a snan).
2954   if (isa<UndefValue>(Op0)) {
2955     if (Op0->getType()->isFPOrFPVector())
2956       return ReplaceInstUsesWith(I, Op0);
2957     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2958   }
2959
2960   // X / undef -> undef
2961   if (isa<UndefValue>(Op1))
2962     return ReplaceInstUsesWith(I, Op1);
2963
2964   return 0;
2965 }
2966
2967 /// This function implements the transforms common to both integer division
2968 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2969 /// division instructions.
2970 /// @brief Common integer divide transforms
2971 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2972   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2973
2974   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2975   if (Op0 == Op1) {
2976     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2977       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2978       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2979       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2980     }
2981
2982     Constant *CI = Context->getConstantInt(I.getType(), 1);
2983     return ReplaceInstUsesWith(I, CI);
2984   }
2985   
2986   if (Instruction *Common = commonDivTransforms(I))
2987     return Common;
2988   
2989   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2990   // This does not apply for fdiv.
2991   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2992     return &I;
2993
2994   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2995     // div X, 1 == X
2996     if (RHS->equalsInt(1))
2997       return ReplaceInstUsesWith(I, Op0);
2998
2999     // (X / C1) / C2  -> X / (C1*C2)
3000     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3001       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3002         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3003           if (MultiplyOverflows(RHS, LHSRHS,
3004                                 I.getOpcode()==Instruction::SDiv, Context))
3005             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3006           else 
3007             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3008                                       Context->getConstantExprMul(RHS, LHSRHS));
3009         }
3010
3011     if (!RHS->isZero()) { // avoid X udiv 0
3012       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3013         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3014           return R;
3015       if (isa<PHINode>(Op0))
3016         if (Instruction *NV = FoldOpIntoPhi(I))
3017           return NV;
3018     }
3019   }
3020
3021   // 0 / X == 0, we don't need to preserve faults!
3022   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3023     if (LHS->equalsInt(0))
3024       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3025
3026   // It can't be division by zero, hence it must be division by one.
3027   if (I.getType() == Type::Int1Ty)
3028     return ReplaceInstUsesWith(I, Op0);
3029
3030   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3031     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3032       // div X, 1 == X
3033       if (X->isOne())
3034         return ReplaceInstUsesWith(I, Op0);
3035   }
3036
3037   return 0;
3038 }
3039
3040 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3041   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3042
3043   // Handle the integer div common cases
3044   if (Instruction *Common = commonIDivTransforms(I))
3045     return Common;
3046
3047   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3048     // X udiv C^2 -> X >> C
3049     // Check to see if this is an unsigned division with an exact power of 2,
3050     // if so, convert to a right shift.
3051     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3052       return BinaryOperator::CreateLShr(Op0, 
3053             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3054
3055     // X udiv C, where C >= signbit
3056     if (C->getValue().isNegative()) {
3057       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3058                                                     ICmpInst::ICMP_ULT, Op0, C),
3059                                       I);
3060       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3061                                 Context->getConstantInt(I.getType(), 1));
3062     }
3063   }
3064
3065   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3066   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3067     if (RHSI->getOpcode() == Instruction::Shl &&
3068         isa<ConstantInt>(RHSI->getOperand(0))) {
3069       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3070       if (C1.isPowerOf2()) {
3071         Value *N = RHSI->getOperand(1);
3072         const Type *NTy = N->getType();
3073         if (uint32_t C2 = C1.logBase2()) {
3074           Constant *C2V = Context->getConstantInt(NTy, C2);
3075           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3076         }
3077         return BinaryOperator::CreateLShr(Op0, N);
3078       }
3079     }
3080   }
3081   
3082   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3083   // where C1&C2 are powers of two.
3084   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3085     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3086       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3087         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3088         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3089           // Compute the shift amounts
3090           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3091           // Construct the "on true" case of the select
3092           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3093           Instruction *TSI = BinaryOperator::CreateLShr(
3094                                                  Op0, TC, SI->getName()+".t");
3095           TSI = InsertNewInstBefore(TSI, I);
3096   
3097           // Construct the "on false" case of the select
3098           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3099           Instruction *FSI = BinaryOperator::CreateLShr(
3100                                                  Op0, FC, SI->getName()+".f");
3101           FSI = InsertNewInstBefore(FSI, I);
3102
3103           // construct the select instruction and return it.
3104           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3105         }
3106       }
3107   return 0;
3108 }
3109
3110 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3111   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113   // Handle the integer div common cases
3114   if (Instruction *Common = commonIDivTransforms(I))
3115     return Common;
3116
3117   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3118     // sdiv X, -1 == -X
3119     if (RHS->isAllOnesValue())
3120       return BinaryOperator::CreateNeg(*Context, Op0);
3121   }
3122
3123   // If the sign bits of both operands are zero (i.e. we can prove they are
3124   // unsigned inputs), turn this into a udiv.
3125   if (I.getType()->isInteger()) {
3126     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3127     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3128       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3129       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3130     }
3131   }      
3132   
3133   return 0;
3134 }
3135
3136 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3137   return commonDivTransforms(I);
3138 }
3139
3140 /// This function implements the transforms on rem instructions that work
3141 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3142 /// is used by the visitors to those instructions.
3143 /// @brief Transforms common to all three rem instructions
3144 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3145   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3146
3147   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3148     if (I.getType()->isFPOrFPVector())
3149       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3150     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3151   }
3152   if (isa<UndefValue>(Op1))
3153     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3154
3155   // Handle cases involving: rem X, (select Cond, Y, Z)
3156   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3157     return &I;
3158
3159   return 0;
3160 }
3161
3162 /// This function implements the transforms common to both integer remainder
3163 /// instructions (urem and srem). It is called by the visitors to those integer
3164 /// remainder instructions.
3165 /// @brief Common integer remainder transforms
3166 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3167   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3168
3169   if (Instruction *common = commonRemTransforms(I))
3170     return common;
3171
3172   // 0 % X == 0 for integer, we don't need to preserve faults!
3173   if (Constant *LHS = dyn_cast<Constant>(Op0))
3174     if (LHS->isNullValue())
3175       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3176
3177   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3178     // X % 0 == undef, we don't need to preserve faults!
3179     if (RHS->equalsInt(0))
3180       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3181     
3182     if (RHS->equalsInt(1))  // X % 1 == 0
3183       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3184
3185     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3186       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3187         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3188           return R;
3189       } else if (isa<PHINode>(Op0I)) {
3190         if (Instruction *NV = FoldOpIntoPhi(I))
3191           return NV;
3192       }
3193
3194       // See if we can fold away this rem instruction.
3195       if (SimplifyDemandedInstructionBits(I))
3196         return &I;
3197     }
3198   }
3199
3200   return 0;
3201 }
3202
3203 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3204   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3205
3206   if (Instruction *common = commonIRemTransforms(I))
3207     return common;
3208   
3209   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210     // X urem C^2 -> X and C
3211     // Check to see if this is an unsigned remainder with an exact power of 2,
3212     // if so, convert to a bitwise and.
3213     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3214       if (C->getValue().isPowerOf2())
3215         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3216   }
3217
3218   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3219     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3220     if (RHSI->getOpcode() == Instruction::Shl &&
3221         isa<ConstantInt>(RHSI->getOperand(0))) {
3222       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3223         Constant *N1 = Context->getAllOnesValue(I.getType());
3224         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3225                                                                    "tmp"), I);
3226         return BinaryOperator::CreateAnd(Op0, Add);
3227       }
3228     }
3229   }
3230
3231   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3232   // where C1&C2 are powers of two.
3233   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3234     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3235       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3236         // STO == 0 and SFO == 0 handled above.
3237         if ((STO->getValue().isPowerOf2()) && 
3238             (SFO->getValue().isPowerOf2())) {
3239           Value *TrueAnd = InsertNewInstBefore(
3240             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3241                                       SI->getName()+".t"), I);
3242           Value *FalseAnd = InsertNewInstBefore(
3243             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3244                                       SI->getName()+".f"), I);
3245           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3246         }
3247       }
3248   }
3249   
3250   return 0;
3251 }
3252
3253 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3254   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3255
3256   // Handle the integer rem common cases
3257   if (Instruction *common = commonIRemTransforms(I))
3258     return common;
3259   
3260   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3261     if (!isa<Constant>(RHSNeg) ||
3262         (isa<ConstantInt>(RHSNeg) &&
3263          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3264       // X % -Y -> X % Y
3265       AddUsesToWorkList(I);
3266       I.setOperand(1, RHSNeg);
3267       return &I;
3268     }
3269
3270   // If the sign bits of both operands are zero (i.e. we can prove they are
3271   // unsigned inputs), turn this into a urem.
3272   if (I.getType()->isInteger()) {
3273     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3274     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3275       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3276       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3277     }
3278   }
3279
3280   // If it's a constant vector, flip any negative values positive.
3281   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3282     unsigned VWidth = RHSV->getNumOperands();
3283
3284     bool hasNegative = false;
3285     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3286       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3287         if (RHS->getValue().isNegative())
3288           hasNegative = true;
3289
3290     if (hasNegative) {
3291       std::vector<Constant *> Elts(VWidth);
3292       for (unsigned i = 0; i != VWidth; ++i) {
3293         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3294           if (RHS->getValue().isNegative())
3295             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3296           else
3297             Elts[i] = RHS;
3298         }
3299       }
3300
3301       Constant *NewRHSV = Context->getConstantVector(Elts);
3302       if (NewRHSV != RHSV) {
3303         AddUsesToWorkList(I);
3304         I.setOperand(1, NewRHSV);
3305         return &I;
3306       }
3307     }
3308   }
3309
3310   return 0;
3311 }
3312
3313 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3314   return commonRemTransforms(I);
3315 }
3316
3317 // isOneBitSet - Return true if there is exactly one bit set in the specified
3318 // constant.
3319 static bool isOneBitSet(const ConstantInt *CI) {
3320   return CI->getValue().isPowerOf2();
3321 }
3322
3323 // isHighOnes - Return true if the constant is of the form 1+0+.
3324 // This is the same as lowones(~X).
3325 static bool isHighOnes(const ConstantInt *CI) {
3326   return (~CI->getValue() + 1).isPowerOf2();
3327 }
3328
3329 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3330 /// are carefully arranged to allow folding of expressions such as:
3331 ///
3332 ///      (A < B) | (A > B) --> (A != B)
3333 ///
3334 /// Note that this is only valid if the first and second predicates have the
3335 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3336 ///
3337 /// Three bits are used to represent the condition, as follows:
3338 ///   0  A > B
3339 ///   1  A == B
3340 ///   2  A < B
3341 ///
3342 /// <=>  Value  Definition
3343 /// 000     0   Always false
3344 /// 001     1   A >  B
3345 /// 010     2   A == B
3346 /// 011     3   A >= B
3347 /// 100     4   A <  B
3348 /// 101     5   A != B
3349 /// 110     6   A <= B
3350 /// 111     7   Always true
3351 ///  
3352 static unsigned getICmpCode(const ICmpInst *ICI) {
3353   switch (ICI->getPredicate()) {
3354     // False -> 0
3355   case ICmpInst::ICMP_UGT: return 1;  // 001
3356   case ICmpInst::ICMP_SGT: return 1;  // 001
3357   case ICmpInst::ICMP_EQ:  return 2;  // 010
3358   case ICmpInst::ICMP_UGE: return 3;  // 011
3359   case ICmpInst::ICMP_SGE: return 3;  // 011
3360   case ICmpInst::ICMP_ULT: return 4;  // 100
3361   case ICmpInst::ICMP_SLT: return 4;  // 100
3362   case ICmpInst::ICMP_NE:  return 5;  // 101
3363   case ICmpInst::ICMP_ULE: return 6;  // 110
3364   case ICmpInst::ICMP_SLE: return 6;  // 110
3365     // True -> 7
3366   default:
3367     LLVM_UNREACHABLE("Invalid ICmp predicate!");
3368     return 0;
3369   }
3370 }
3371
3372 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3373 /// predicate into a three bit mask. It also returns whether it is an ordered
3374 /// predicate by reference.
3375 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3376   isOrdered = false;
3377   switch (CC) {
3378   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3379   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3380   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3381   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3382   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3383   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3384   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3385   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3386   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3387   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3388   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3389   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3390   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3391   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3392     // True -> 7
3393   default:
3394     // Not expecting FCMP_FALSE and FCMP_TRUE;
3395     LLVM_UNREACHABLE("Unexpected FCmp predicate!");
3396     return 0;
3397   }
3398 }
3399
3400 /// getICmpValue - This is the complement of getICmpCode, which turns an
3401 /// opcode and two operands into either a constant true or false, or a brand 
3402 /// new ICmp instruction. The sign is passed in to determine which kind
3403 /// of predicate to use in the new icmp instruction.
3404 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3405                            LLVMContext *Context) {
3406   switch (code) {
3407   default: LLVM_UNREACHABLE("Illegal ICmp code!");
3408   case  0: return Context->getConstantIntFalse();
3409   case  1: 
3410     if (sign)
3411       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3412     else
3413       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3414   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3415   case  3: 
3416     if (sign)
3417       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3418     else
3419       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3420   case  4: 
3421     if (sign)
3422       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3423     else
3424       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3425   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3426   case  6: 
3427     if (sign)
3428       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3429     else
3430       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3431   case  7: return Context->getConstantIntTrue();
3432   }
3433 }
3434
3435 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3436 /// opcode and two operands into either a FCmp instruction. isordered is passed
3437 /// in to determine which kind of predicate to use in the new fcmp instruction.
3438 static Value *getFCmpValue(bool isordered, unsigned code,
3439                            Value *LHS, Value *RHS, LLVMContext *Context) {
3440   switch (code) {
3441   default: LLVM_UNREACHABLE("Illegal FCmp code!");
3442   case  0:
3443     if (isordered)
3444       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3445     else
3446       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3447   case  1: 
3448     if (isordered)
3449       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3450     else
3451       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3452   case  2: 
3453     if (isordered)
3454       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3455     else
3456       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3457   case  3: 
3458     if (isordered)
3459       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3460     else
3461       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3462   case  4: 
3463     if (isordered)
3464       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3465     else
3466       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3467   case  5: 
3468     if (isordered)
3469       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3470     else
3471       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3472   case  6: 
3473     if (isordered)
3474       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3475     else
3476       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3477   case  7: return Context->getConstantIntTrue();
3478   }
3479 }
3480
3481 /// PredicatesFoldable - Return true if both predicates match sign or if at
3482 /// least one of them is an equality comparison (which is signless).
3483 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3484   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3485          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3486          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3487 }
3488
3489 namespace { 
3490 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3491 struct FoldICmpLogical {
3492   InstCombiner &IC;
3493   Value *LHS, *RHS;
3494   ICmpInst::Predicate pred;
3495   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3496     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3497       pred(ICI->getPredicate()) {}
3498   bool shouldApply(Value *V) const {
3499     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3500       if (PredicatesFoldable(pred, ICI->getPredicate()))
3501         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3502                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3503     return false;
3504   }
3505   Instruction *apply(Instruction &Log) const {
3506     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3507     if (ICI->getOperand(0) != LHS) {
3508       assert(ICI->getOperand(1) == LHS);
3509       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3510     }
3511
3512     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3513     unsigned LHSCode = getICmpCode(ICI);
3514     unsigned RHSCode = getICmpCode(RHSICI);
3515     unsigned Code;
3516     switch (Log.getOpcode()) {
3517     case Instruction::And: Code = LHSCode & RHSCode; break;
3518     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3519     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3520     default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
3521     }
3522
3523     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3524                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3525       
3526     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3527     if (Instruction *I = dyn_cast<Instruction>(RV))
3528       return I;
3529     // Otherwise, it's a constant boolean value...
3530     return IC.ReplaceInstUsesWith(Log, RV);
3531   }
3532 };
3533 } // end anonymous namespace
3534
3535 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3536 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3537 // guaranteed to be a binary operator.
3538 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3539                                     ConstantInt *OpRHS,
3540                                     ConstantInt *AndRHS,
3541                                     BinaryOperator &TheAnd) {
3542   Value *X = Op->getOperand(0);
3543   Constant *Together = 0;
3544   if (!Op->isShift())
3545     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3546
3547   switch (Op->getOpcode()) {
3548   case Instruction::Xor:
3549     if (Op->hasOneUse()) {
3550       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3551       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3552       InsertNewInstBefore(And, TheAnd);
3553       And->takeName(Op);
3554       return BinaryOperator::CreateXor(And, Together);
3555     }
3556     break;
3557   case Instruction::Or:
3558     if (Together == AndRHS) // (X | C) & C --> C
3559       return ReplaceInstUsesWith(TheAnd, AndRHS);
3560
3561     if (Op->hasOneUse() && Together != OpRHS) {
3562       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3563       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3564       InsertNewInstBefore(Or, TheAnd);
3565       Or->takeName(Op);
3566       return BinaryOperator::CreateAnd(Or, AndRHS);
3567     }
3568     break;
3569   case Instruction::Add:
3570     if (Op->hasOneUse()) {
3571       // Adding a one to a single bit bit-field should be turned into an XOR
3572       // of the bit.  First thing to check is to see if this AND is with a
3573       // single bit constant.
3574       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3575
3576       // If there is only one bit set...
3577       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3578         // Ok, at this point, we know that we are masking the result of the
3579         // ADD down to exactly one bit.  If the constant we are adding has
3580         // no bits set below this bit, then we can eliminate the ADD.
3581         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3582
3583         // Check to see if any bits below the one bit set in AndRHSV are set.
3584         if ((AddRHS & (AndRHSV-1)) == 0) {
3585           // If not, the only thing that can effect the output of the AND is
3586           // the bit specified by AndRHSV.  If that bit is set, the effect of
3587           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3588           // no effect.
3589           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3590             TheAnd.setOperand(0, X);
3591             return &TheAnd;
3592           } else {
3593             // Pull the XOR out of the AND.
3594             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3595             InsertNewInstBefore(NewAnd, TheAnd);
3596             NewAnd->takeName(Op);
3597             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3598           }
3599         }
3600       }
3601     }
3602     break;
3603
3604   case Instruction::Shl: {
3605     // We know that the AND will not produce any of the bits shifted in, so if
3606     // the anded constant includes them, clear them now!
3607     //
3608     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3611     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3612
3613     if (CI->getValue() == ShlMask) { 
3614     // Masking out bits that the shift already masks
3615       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3616     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3617       TheAnd.setOperand(1, CI);
3618       return &TheAnd;
3619     }
3620     break;
3621   }
3622   case Instruction::LShr:
3623   {
3624     // We know that the AND will not produce any of the bits shifted in, so if
3625     // the anded constant includes them, clear them now!  This only applies to
3626     // unsigned shifts, because a signed shr may bring in set bits!
3627     //
3628     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3629     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3630     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3631     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3632
3633     if (CI->getValue() == ShrMask) {   
3634     // Masking out bits that the shift already masks.
3635       return ReplaceInstUsesWith(TheAnd, Op);
3636     } else if (CI != AndRHS) {
3637       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3638       return &TheAnd;
3639     }
3640     break;
3641   }
3642   case Instruction::AShr:
3643     // Signed shr.
3644     // See if this is shifting in some sign extension, then masking it out
3645     // with an and.
3646     if (Op->hasOneUse()) {
3647       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3648       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3649       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3650       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3651       if (C == AndRHS) {          // Masking out bits shifted in.
3652         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3653         // Make the argument unsigned.
3654         Value *ShVal = Op->getOperand(0);
3655         ShVal = InsertNewInstBefore(
3656             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3657                                    Op->getName()), TheAnd);
3658         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3659       }
3660     }
3661     break;
3662   }
3663   return 0;
3664 }
3665
3666
3667 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3668 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3669 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3670 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3671 /// insert new instructions.
3672 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3673                                            bool isSigned, bool Inside, 
3674                                            Instruction &IB) {
3675   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3676             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3677          "Lo is not <= Hi in range emission code!");
3678     
3679   if (Inside) {
3680     if (Lo == Hi)  // Trivially false.
3681       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3682
3683     // V >= Min && V < Hi --> V < Hi
3684     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3685       ICmpInst::Predicate pred = (isSigned ? 
3686         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3687       return new ICmpInst(*Context, pred, V, Hi);
3688     }
3689
3690     // Emit V-Lo <u Hi-Lo
3691     Constant *NegLo = Context->getConstantExprNeg(Lo);
3692     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3693     InsertNewInstBefore(Add, IB);
3694     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3695     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3696   }
3697
3698   if (Lo == Hi)  // Trivially true.
3699     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3700
3701   // V < Min || V >= Hi -> V > Hi-1
3702   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3703   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3704     ICmpInst::Predicate pred = (isSigned ? 
3705         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3706     return new ICmpInst(*Context, pred, V, Hi);
3707   }
3708
3709   // Emit V-Lo >u Hi-1-Lo
3710   // Note that Hi has already had one subtracted from it, above.
3711   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3712   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3713   InsertNewInstBefore(Add, IB);
3714   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3715   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3716 }
3717
3718 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3719 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3720 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3721 // not, since all 1s are not contiguous.
3722 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3723   const APInt& V = Val->getValue();
3724   uint32_t BitWidth = Val->getType()->getBitWidth();
3725   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3726
3727   // look for the first zero bit after the run of ones
3728   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3729   // look for the first non-zero bit
3730   ME = V.getActiveBits(); 
3731   return true;
3732 }
3733
3734 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3735 /// where isSub determines whether the operator is a sub.  If we can fold one of
3736 /// the following xforms:
3737 /// 
3738 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3739 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3741 ///
3742 /// return (A +/- B).
3743 ///
3744 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3745                                         ConstantInt *Mask, bool isSub,
3746                                         Instruction &I) {
3747   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3748   if (!LHSI || LHSI->getNumOperands() != 2 ||
3749       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3750
3751   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3752
3753   switch (LHSI->getOpcode()) {
3754   default: return 0;
3755   case Instruction::And:
3756     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3757       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3758       if ((Mask->getValue().countLeadingZeros() + 
3759            Mask->getValue().countPopulation()) == 
3760           Mask->getValue().getBitWidth())
3761         break;
3762
3763       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3764       // part, we don't need any explicit masks to take them out of A.  If that
3765       // is all N is, ignore it.
3766       uint32_t MB = 0, ME = 0;
3767       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3768         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3769         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3770         if (MaskedValueIsZero(RHS, Mask))
3771           break;
3772       }
3773     }
3774     return 0;
3775   case Instruction::Or:
3776   case Instruction::Xor:
3777     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3778     if ((Mask->getValue().countLeadingZeros() + 
3779          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3780         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3781       break;
3782     return 0;
3783   }
3784   
3785   Instruction *New;
3786   if (isSub)
3787     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3788   else
3789     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3790   return InsertNewInstBefore(New, I);
3791 }
3792
3793 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3794 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3795                                           ICmpInst *LHS, ICmpInst *RHS) {
3796   Value *Val, *Val2;
3797   ConstantInt *LHSCst, *RHSCst;
3798   ICmpInst::Predicate LHSCC, RHSCC;
3799   
3800   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3801   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3802                          m_ConstantInt(LHSCst)), *Context) ||
3803       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3804                          m_ConstantInt(RHSCst)), *Context))
3805     return 0;
3806   
3807   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3808   // where C is a power of 2
3809   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3810       LHSCst->getValue().isPowerOf2()) {
3811     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3812     InsertNewInstBefore(NewOr, I);
3813     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3814   }
3815   
3816   // From here on, we only handle:
3817   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3818   if (Val != Val2) return 0;
3819   
3820   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3821   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3822       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3823       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3824       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3825     return 0;
3826   
3827   // We can't fold (ugt x, C) & (sgt x, C2).
3828   if (!PredicatesFoldable(LHSCC, RHSCC))
3829     return 0;
3830     
3831   // Ensure that the larger constant is on the RHS.
3832   bool ShouldSwap;
3833   if (ICmpInst::isSignedPredicate(LHSCC) ||
3834       (ICmpInst::isEquality(LHSCC) && 
3835        ICmpInst::isSignedPredicate(RHSCC)))
3836     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3837   else
3838     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3839     
3840   if (ShouldSwap) {
3841     std::swap(LHS, RHS);
3842     std::swap(LHSCst, RHSCst);
3843     std::swap(LHSCC, RHSCC);
3844   }
3845
3846   // At this point, we know we have have two icmp instructions
3847   // comparing a value against two constants and and'ing the result
3848   // together.  Because of the above check, we know that we only have
3849   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3850   // (from the FoldICmpLogical check above), that the two constants 
3851   // are not equal and that the larger constant is on the RHS
3852   assert(LHSCst != RHSCst && "Compares not folded above?");
3853
3854   switch (LHSCC) {
3855   default: LLVM_UNREACHABLE("Unknown integer condition code!");
3856   case ICmpInst::ICMP_EQ:
3857     switch (RHSCC) {
3858     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3859     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3860     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3861     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3862       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3863     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3864     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3865     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3866       return ReplaceInstUsesWith(I, LHS);
3867     }
3868   case ICmpInst::ICMP_NE:
3869     switch (RHSCC) {
3870     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3871     case ICmpInst::ICMP_ULT:
3872       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3873         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3874       break;                        // (X != 13 & X u< 15) -> no change
3875     case ICmpInst::ICMP_SLT:
3876       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3877         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3878       break;                        // (X != 13 & X s< 15) -> no change
3879     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3880     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3881     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3882       return ReplaceInstUsesWith(I, RHS);
3883     case ICmpInst::ICMP_NE:
3884       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3885         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3886         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3887                                                      Val->getName()+".off");
3888         InsertNewInstBefore(Add, I);
3889         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3890                             Context->getConstantInt(Add->getType(), 1));
3891       }
3892       break;                        // (X != 13 & X != 15) -> no change
3893     }
3894     break;
3895   case ICmpInst::ICMP_ULT:
3896     switch (RHSCC) {
3897     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3898     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3899     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3900       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3901     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3902       break;
3903     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3904     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3905       return ReplaceInstUsesWith(I, LHS);
3906     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3907       break;
3908     }
3909     break;
3910   case ICmpInst::ICMP_SLT:
3911     switch (RHSCC) {
3912     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3914     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3915       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3916     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3919     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3920       return ReplaceInstUsesWith(I, LHS);
3921     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3922       break;
3923     }
3924     break;
3925   case ICmpInst::ICMP_UGT:
3926     switch (RHSCC) {
3927     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3928     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3929     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3930       return ReplaceInstUsesWith(I, RHS);
3931     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3932       break;
3933     case ICmpInst::ICMP_NE:
3934       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3935         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3936       break;                        // (X u> 13 & X != 15) -> no change
3937     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3938       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3939                              RHSCst, false, true, I);
3940     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3941       break;
3942     }
3943     break;
3944   case ICmpInst::ICMP_SGT:
3945     switch (RHSCC) {
3946     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3947     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3948     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3949       return ReplaceInstUsesWith(I, RHS);
3950     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3951       break;
3952     case ICmpInst::ICMP_NE:
3953       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3954         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3955       break;                        // (X s> 13 & X != 15) -> no change
3956     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3957       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3958                              RHSCst, true, true, I);
3959     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3960       break;
3961     }
3962     break;
3963   }
3964  
3965   return 0;
3966 }
3967
3968
3969 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3970   bool Changed = SimplifyCommutative(I);
3971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3972
3973   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3974     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3975
3976   // and X, X = X
3977   if (Op0 == Op1)
3978     return ReplaceInstUsesWith(I, Op1);
3979
3980   // See if we can simplify any instructions used by the instruction whose sole 
3981   // purpose is to compute bits we don't care about.
3982   if (SimplifyDemandedInstructionBits(I))
3983     return &I;
3984   if (isa<VectorType>(I.getType())) {
3985     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3986       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3987         return ReplaceInstUsesWith(I, I.getOperand(0));
3988     } else if (isa<ConstantAggregateZero>(Op1)) {
3989       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3990     }
3991   }
3992
3993   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3994     const APInt& AndRHSMask = AndRHS->getValue();
3995     APInt NotAndRHS(~AndRHSMask);
3996
3997     // Optimize a variety of ((val OP C1) & C2) combinations...
3998     if (isa<BinaryOperator>(Op0)) {
3999       Instruction *Op0I = cast<Instruction>(Op0);
4000       Value *Op0LHS = Op0I->getOperand(0);
4001       Value *Op0RHS = Op0I->getOperand(1);
4002       switch (Op0I->getOpcode()) {
4003       case Instruction::Xor:
4004       case Instruction::Or:
4005         // If the mask is only needed on one incoming arm, push it up.
4006         if (Op0I->hasOneUse()) {
4007           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4008             // Not masking anything out for the LHS, move to RHS.
4009             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4010                                                    Op0RHS->getName()+".masked");
4011             InsertNewInstBefore(NewRHS, I);
4012             return BinaryOperator::Create(
4013                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4014           }
4015           if (!isa<Constant>(Op0RHS) &&
4016               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4017             // Not masking anything out for the RHS, move to LHS.
4018             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4019                                                    Op0LHS->getName()+".masked");
4020             InsertNewInstBefore(NewLHS, I);
4021             return BinaryOperator::Create(
4022                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4023           }
4024         }
4025
4026         break;
4027       case Instruction::Add:
4028         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4029         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4031         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4032           return BinaryOperator::CreateAnd(V, AndRHS);
4033         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4034           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4035         break;
4036
4037       case Instruction::Sub:
4038         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4039         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4041         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4042           return BinaryOperator::CreateAnd(V, AndRHS);
4043
4044         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4045         // has 1's for all bits that the subtraction with A might affect.
4046         if (Op0I->hasOneUse()) {
4047           uint32_t BitWidth = AndRHSMask.getBitWidth();
4048           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4049           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4050
4051           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4052           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4053               MaskedValueIsZero(Op0LHS, Mask)) {
4054             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4055             InsertNewInstBefore(NewNeg, I);
4056             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4057           }
4058         }
4059         break;
4060
4061       case Instruction::Shl:
4062       case Instruction::LShr:
4063         // (1 << x) & 1 --> zext(x == 0)
4064         // (1 >> x) & 1 --> zext(x == 0)
4065         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4066           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4067                                     Op0RHS, Context->getNullValue(I.getType()));
4068           InsertNewInstBefore(NewICmp, I);
4069           return new ZExtInst(NewICmp, I.getType());
4070         }
4071         break;
4072       }
4073
4074       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4075         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4076           return Res;
4077     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4078       // If this is an integer truncation or change from signed-to-unsigned, and
4079       // if the source is an and/or with immediate, transform it.  This
4080       // frequently occurs for bitfield accesses.
4081       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4082         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4083             CastOp->getNumOperands() == 2)
4084           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4085             if (CastOp->getOpcode() == Instruction::And) {
4086               // Change: and (cast (and X, C1) to T), C2
4087               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4088               // This will fold the two constants together, which may allow 
4089               // other simplifications.
4090               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4091                 CastOp->getOperand(0), I.getType(), 
4092                 CastOp->getName()+".shrunk");
4093               NewCast = InsertNewInstBefore(NewCast, I);
4094               // trunc_or_bitcast(C1)&C2
4095               Constant *C3 =
4096                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4097               C3 = Context->getConstantExprAnd(C3, AndRHS);
4098               return BinaryOperator::CreateAnd(NewCast, C3);
4099             } else if (CastOp->getOpcode() == Instruction::Or) {
4100               // Change: and (cast (or X, C1) to T), C2
4101               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4102               Constant *C3 =
4103                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4104               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4105                 // trunc(C1)&C2
4106                 return ReplaceInstUsesWith(I, AndRHS);
4107             }
4108           }
4109       }
4110     }
4111
4112     // Try to fold constant and into select arguments.
4113     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4114       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4115         return R;
4116     if (isa<PHINode>(Op0))
4117       if (Instruction *NV = FoldOpIntoPhi(I))
4118         return NV;
4119   }
4120
4121   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4122   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4123
4124   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4125     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4126
4127   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4128   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4129     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4130                                                I.getName()+".demorgan");
4131     InsertNewInstBefore(Or, I);
4132     return BinaryOperator::CreateNot(*Context, Or);
4133   }
4134   
4135   {
4136     Value *A = 0, *B = 0, *C = 0, *D = 0;
4137     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4138       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4139         return ReplaceInstUsesWith(I, Op1);
4140     
4141       // (A|B) & ~(A&B) -> A^B
4142       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4143         if ((A == C && B == D) || (A == D && B == C))
4144           return BinaryOperator::CreateXor(A, B);
4145       }
4146     }
4147     
4148     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4149       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4150         return ReplaceInstUsesWith(I, Op0);
4151
4152       // ~(A&B) & (A|B) -> A^B
4153       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4154         if ((A == C && B == D) || (A == D && B == C))
4155           return BinaryOperator::CreateXor(A, B);
4156       }
4157     }
4158     
4159     if (Op0->hasOneUse() &&
4160         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4161       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4162         I.swapOperands();     // Simplify below
4163         std::swap(Op0, Op1);
4164       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4165         cast<BinaryOperator>(Op0)->swapOperands();
4166         I.swapOperands();     // Simplify below
4167         std::swap(Op0, Op1);
4168       }
4169     }
4170
4171     if (Op1->hasOneUse() &&
4172         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4173       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4174         cast<BinaryOperator>(Op1)->swapOperands();
4175         std::swap(A, B);
4176       }
4177       if (A == Op0) {                                // A&(A^B) -> A & ~B
4178         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4179         InsertNewInstBefore(NotB, I);
4180         return BinaryOperator::CreateAnd(A, NotB);
4181       }
4182     }
4183
4184     // (A&((~A)|B)) -> A&B
4185     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4186         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4187       return BinaryOperator::CreateAnd(A, Op1);
4188     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4189         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4190       return BinaryOperator::CreateAnd(A, Op0);
4191   }
4192   
4193   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4194     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4195     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4196       return R;
4197
4198     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4199       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4200         return Res;
4201   }
4202
4203   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4204   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4205     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4206       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4207         const Type *SrcTy = Op0C->getOperand(0)->getType();
4208         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4209             // Only do this if the casts both really cause code to be generated.
4210             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4211                               I.getType(), TD) &&
4212             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4213                               I.getType(), TD)) {
4214           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4215                                                          Op1C->getOperand(0),
4216                                                          I.getName());
4217           InsertNewInstBefore(NewOp, I);
4218           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4219         }
4220       }
4221     
4222   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4223   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4224     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4225       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4226           SI0->getOperand(1) == SI1->getOperand(1) &&
4227           (SI0->hasOneUse() || SI1->hasOneUse())) {
4228         Instruction *NewOp =
4229           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4230                                                         SI1->getOperand(0),
4231                                                         SI0->getName()), I);
4232         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4233                                       SI1->getOperand(1));
4234       }
4235   }
4236
4237   // If and'ing two fcmp, try combine them into one.
4238   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4239     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4240       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4241           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4242         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4243         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4244           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4245             // If either of the constants are nans, then the whole thing returns
4246             // false.
4247             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4248               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4249             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4250                                 LHS->getOperand(0), RHS->getOperand(0));
4251           }
4252       } else {
4253         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4254         FCmpInst::Predicate Op0CC, Op1CC;
4255         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4256                   m_Value(Op0RHS)), *Context) &&
4257             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4258                   m_Value(Op1RHS)), *Context)) {
4259           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4260             // Swap RHS operands to match LHS.
4261             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4262             std::swap(Op1LHS, Op1RHS);
4263           }
4264           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4265             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4266             if (Op0CC == Op1CC)
4267               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4268                                   Op0LHS, Op0RHS);
4269             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4270                      Op1CC == FCmpInst::FCMP_FALSE)
4271               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4272             else if (Op0CC == FCmpInst::FCMP_TRUE)
4273               return ReplaceInstUsesWith(I, Op1);
4274             else if (Op1CC == FCmpInst::FCMP_TRUE)
4275               return ReplaceInstUsesWith(I, Op0);
4276             bool Op0Ordered;
4277             bool Op1Ordered;
4278             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4279             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4280             if (Op1Pred == 0) {
4281               std::swap(Op0, Op1);
4282               std::swap(Op0Pred, Op1Pred);
4283               std::swap(Op0Ordered, Op1Ordered);
4284             }
4285             if (Op0Pred == 0) {
4286               // uno && ueq -> uno && (uno || eq) -> ueq
4287               // ord && olt -> ord && (ord && lt) -> olt
4288               if (Op0Ordered == Op1Ordered)
4289                 return ReplaceInstUsesWith(I, Op1);
4290               // uno && oeq -> uno && (ord && eq) -> false
4291               // uno && ord -> false
4292               if (!Op0Ordered)
4293                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4294               // ord && ueq -> ord && (uno || eq) -> oeq
4295               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4296                                                     Op0LHS, Op0RHS, Context));
4297             }
4298           }
4299         }
4300       }
4301     }
4302   }
4303
4304   return Changed ? &I : 0;
4305 }
4306
4307 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4308 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4309 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4310 /// the expression came from the corresponding "byte swapped" byte in some other
4311 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4312 /// we know that the expression deposits the low byte of %X into the high byte
4313 /// of the bswap result and that all other bytes are zero.  This expression is
4314 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4315 /// match.
4316 ///
4317 /// This function returns true if the match was unsuccessful and false if so.
4318 /// On entry to the function the "OverallLeftShift" is a signed integer value
4319 /// indicating the number of bytes that the subexpression is later shifted.  For
4320 /// example, if the expression is later right shifted by 16 bits, the
4321 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4322 /// byte of ByteValues is actually being set.
4323 ///
4324 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4325 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4326 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4327 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4328 /// always in the local (OverallLeftShift) coordinate space.
4329 ///
4330 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4331                               SmallVector<Value*, 8> &ByteValues) {
4332   if (Instruction *I = dyn_cast<Instruction>(V)) {
4333     // If this is an or instruction, it may be an inner node of the bswap.
4334     if (I->getOpcode() == Instruction::Or) {
4335       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336                                ByteValues) ||
4337              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4338                                ByteValues);
4339     }
4340   
4341     // If this is a logical shift by a constant multiple of 8, recurse with
4342     // OverallLeftShift and ByteMask adjusted.
4343     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4344       unsigned ShAmt = 
4345         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4346       // Ensure the shift amount is defined and of a byte value.
4347       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4348         return true;
4349
4350       unsigned ByteShift = ShAmt >> 3;
4351       if (I->getOpcode() == Instruction::Shl) {
4352         // X << 2 -> collect(X, +2)
4353         OverallLeftShift += ByteShift;
4354         ByteMask >>= ByteShift;
4355       } else {
4356         // X >>u 2 -> collect(X, -2)
4357         OverallLeftShift -= ByteShift;
4358         ByteMask <<= ByteShift;
4359         ByteMask &= (~0U >> (32-ByteValues.size()));
4360       }
4361
4362       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4363       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4364
4365       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4366                                ByteValues);
4367     }
4368
4369     // If this is a logical 'and' with a mask that clears bytes, clear the
4370     // corresponding bytes in ByteMask.
4371     if (I->getOpcode() == Instruction::And &&
4372         isa<ConstantInt>(I->getOperand(1))) {
4373       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4374       unsigned NumBytes = ByteValues.size();
4375       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4376       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4377       
4378       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4379         // If this byte is masked out by a later operation, we don't care what
4380         // the and mask is.
4381         if ((ByteMask & (1 << i)) == 0)
4382           continue;
4383         
4384         // If the AndMask is all zeros for this byte, clear the bit.
4385         APInt MaskB = AndMask & Byte;
4386         if (MaskB == 0) {
4387           ByteMask &= ~(1U << i);
4388           continue;
4389         }
4390         
4391         // If the AndMask is not all ones for this byte, it's not a bytezap.
4392         if (MaskB != Byte)
4393           return true;
4394
4395         // Otherwise, this byte is kept.
4396       }
4397
4398       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4399                                ByteValues);
4400     }
4401   }
4402   
4403   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4404   // the input value to the bswap.  Some observations: 1) if more than one byte
4405   // is demanded from this input, then it could not be successfully assembled
4406   // into a byteswap.  At least one of the two bytes would not be aligned with
4407   // their ultimate destination.
4408   if (!isPowerOf2_32(ByteMask)) return true;
4409   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4410   
4411   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4412   // is demanded, it needs to go into byte 0 of the result.  This means that the
4413   // byte needs to be shifted until it lands in the right byte bucket.  The
4414   // shift amount depends on the position: if the byte is coming from the high
4415   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4416   // low part, it must be shifted left.
4417   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4418   if (InputByteNo < ByteValues.size()/2) {
4419     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4420       return true;
4421   } else {
4422     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423       return true;
4424   }
4425   
4426   // If the destination byte value is already defined, the values are or'd
4427   // together, which isn't a bswap (unless it's an or of the same bits).
4428   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4429     return true;
4430   ByteValues[DestByteNo] = V;
4431   return false;
4432 }
4433
4434 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4435 /// If so, insert the new bswap intrinsic and return it.
4436 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4437   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4438   if (!ITy || ITy->getBitWidth() % 16 || 
4439       // ByteMask only allows up to 32-byte values.
4440       ITy->getBitWidth() > 32*8) 
4441     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4442   
4443   /// ByteValues - For each byte of the result, we keep track of which value
4444   /// defines each byte.
4445   SmallVector<Value*, 8> ByteValues;
4446   ByteValues.resize(ITy->getBitWidth()/8);
4447     
4448   // Try to find all the pieces corresponding to the bswap.
4449   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4450   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4451     return 0;
4452   
4453   // Check to see if all of the bytes come from the same value.
4454   Value *V = ByteValues[0];
4455   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4456   
4457   // Check to make sure that all of the bytes come from the same value.
4458   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4459     if (ByteValues[i] != V)
4460       return 0;
4461   const Type *Tys[] = { ITy };
4462   Module *M = I.getParent()->getParent()->getParent();
4463   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4464   return CallInst::Create(F, V);
4465 }
4466
4467 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4468 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4469 /// we can simplify this expression to "cond ? C : D or B".
4470 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4471                                          Value *C, Value *D,
4472                                          LLVMContext *Context) {
4473   // If A is not a select of -1/0, this cannot match.
4474   Value *Cond = 0;
4475   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4476     return 0;
4477
4478   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4479   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4480     return SelectInst::Create(Cond, C, B);
4481   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4482     return SelectInst::Create(Cond, C, B);
4483   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4484   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4485     return SelectInst::Create(Cond, C, D);
4486   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4487     return SelectInst::Create(Cond, C, D);
4488   return 0;
4489 }
4490
4491 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4492 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4493                                          ICmpInst *LHS, ICmpInst *RHS) {
4494   Value *Val, *Val2;
4495   ConstantInt *LHSCst, *RHSCst;
4496   ICmpInst::Predicate LHSCC, RHSCC;
4497   
4498   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4499   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4500              m_ConstantInt(LHSCst)), *Context) ||
4501       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4502              m_ConstantInt(RHSCst)), *Context))
4503     return 0;
4504   
4505   // From here on, we only handle:
4506   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4507   if (Val != Val2) return 0;
4508   
4509   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4510   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4511       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4512       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4513       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4514     return 0;
4515   
4516   // We can't fold (ugt x, C) | (sgt x, C2).
4517   if (!PredicatesFoldable(LHSCC, RHSCC))
4518     return 0;
4519   
4520   // Ensure that the larger constant is on the RHS.
4521   bool ShouldSwap;
4522   if (ICmpInst::isSignedPredicate(LHSCC) ||
4523       (ICmpInst::isEquality(LHSCC) && 
4524        ICmpInst::isSignedPredicate(RHSCC)))
4525     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4526   else
4527     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4528   
4529   if (ShouldSwap) {
4530     std::swap(LHS, RHS);
4531     std::swap(LHSCst, RHSCst);
4532     std::swap(LHSCC, RHSCC);
4533   }
4534   
4535   // At this point, we know we have have two icmp instructions
4536   // comparing a value against two constants and or'ing the result
4537   // together.  Because of the above check, we know that we only have
4538   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4539   // FoldICmpLogical check above), that the two constants are not
4540   // equal.
4541   assert(LHSCst != RHSCst && "Compares not folded above?");
4542
4543   switch (LHSCC) {
4544   default: LLVM_UNREACHABLE("Unknown integer condition code!");
4545   case ICmpInst::ICMP_EQ:
4546     switch (RHSCC) {
4547     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4548     case ICmpInst::ICMP_EQ:
4549       if (LHSCst == SubOne(RHSCst, Context)) {
4550         // (X == 13 | X == 14) -> X-13 <u 2
4551         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4552         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4553                                                      Val->getName()+".off");
4554         InsertNewInstBefore(Add, I);
4555         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4556         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4557       }
4558       break;                         // (X == 13 | X == 15) -> no change
4559     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4560     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4561       break;
4562     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4563     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4564     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4565       return ReplaceInstUsesWith(I, RHS);
4566     }
4567     break;
4568   case ICmpInst::ICMP_NE:
4569     switch (RHSCC) {
4570     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4571     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4572     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4573     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4574       return ReplaceInstUsesWith(I, LHS);
4575     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4576     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4577     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4578       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4579     }
4580     break;
4581   case ICmpInst::ICMP_ULT:
4582     switch (RHSCC) {
4583     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4584     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4585       break;
4586     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4587       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4588       // this can cause overflow.
4589       if (RHSCst->isMaxValue(false))
4590         return ReplaceInstUsesWith(I, LHS);
4591       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4592                              false, false, I);
4593     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4594       break;
4595     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4596     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4597       return ReplaceInstUsesWith(I, RHS);
4598     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4599       break;
4600     }
4601     break;
4602   case ICmpInst::ICMP_SLT:
4603     switch (RHSCC) {
4604     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4605     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4606       break;
4607     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4608       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4609       // this can cause overflow.
4610       if (RHSCst->isMaxValue(true))
4611         return ReplaceInstUsesWith(I, LHS);
4612       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4613                              true, false, I);
4614     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4615       break;
4616     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4617     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4618       return ReplaceInstUsesWith(I, RHS);
4619     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4620       break;
4621     }
4622     break;
4623   case ICmpInst::ICMP_UGT:
4624     switch (RHSCC) {
4625     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4626     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4627     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4628       return ReplaceInstUsesWith(I, LHS);
4629     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4630       break;
4631     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4632     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4633       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4634     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4635       break;
4636     }
4637     break;
4638   case ICmpInst::ICMP_SGT:
4639     switch (RHSCC) {
4640     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4641     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4642     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4643       return ReplaceInstUsesWith(I, LHS);
4644     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4645       break;
4646     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4647     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4648       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4649     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4650       break;
4651     }
4652     break;
4653   }
4654   return 0;
4655 }
4656
4657 /// FoldOrWithConstants - This helper function folds:
4658 ///
4659 ///     ((A | B) & C1) | (B & C2)
4660 ///
4661 /// into:
4662 /// 
4663 ///     (A & C1) | B
4664 ///
4665 /// when the XOR of the two constants is "all ones" (-1).
4666 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4667                                                Value *A, Value *B, Value *C) {
4668   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4669   if (!CI1) return 0;
4670
4671   Value *V1 = 0;
4672   ConstantInt *CI2 = 0;
4673   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4674
4675   APInt Xor = CI1->getValue() ^ CI2->getValue();
4676   if (!Xor.isAllOnesValue()) return 0;
4677
4678   if (V1 == A || V1 == B) {
4679     Instruction *NewOp =
4680       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4681     return BinaryOperator::CreateOr(NewOp, V1);
4682   }
4683
4684   return 0;
4685 }
4686
4687 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4688   bool Changed = SimplifyCommutative(I);
4689   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4690
4691   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4692     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4693
4694   // or X, X = X
4695   if (Op0 == Op1)
4696     return ReplaceInstUsesWith(I, Op0);
4697
4698   // See if we can simplify any instructions used by the instruction whose sole 
4699   // purpose is to compute bits we don't care about.
4700   if (SimplifyDemandedInstructionBits(I))
4701     return &I;
4702   if (isa<VectorType>(I.getType())) {
4703     if (isa<ConstantAggregateZero>(Op1)) {
4704       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4705     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4707         return ReplaceInstUsesWith(I, I.getOperand(1));
4708     }
4709   }
4710
4711   // or X, -1 == -1
4712   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4713     ConstantInt *C1 = 0; Value *X = 0;
4714     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4715     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4716         isOnlyUse(Op0)) {
4717       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4718       InsertNewInstBefore(Or, I);
4719       Or->takeName(Op0);
4720       return BinaryOperator::CreateAnd(Or, 
4721                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4722     }
4723
4724     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4725     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4726         isOnlyUse(Op0)) {
4727       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4728       InsertNewInstBefore(Or, I);
4729       Or->takeName(Op0);
4730       return BinaryOperator::CreateXor(Or,
4731                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4732     }
4733
4734     // Try to fold constant and into select arguments.
4735     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4736       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4737         return R;
4738     if (isa<PHINode>(Op0))
4739       if (Instruction *NV = FoldOpIntoPhi(I))
4740         return NV;
4741   }
4742
4743   Value *A = 0, *B = 0;
4744   ConstantInt *C1 = 0, *C2 = 0;
4745
4746   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4747     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4748       return ReplaceInstUsesWith(I, Op1);
4749   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4750     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4751       return ReplaceInstUsesWith(I, Op0);
4752
4753   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4754   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4755   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4756       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4757       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4758        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4759     if (Instruction *BSwap = MatchBSwap(I))
4760       return BSwap;
4761   }
4762   
4763   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4764   if (Op0->hasOneUse() &&
4765       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4766       MaskedValueIsZero(Op1, C1->getValue())) {
4767     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4768     InsertNewInstBefore(NOr, I);
4769     NOr->takeName(Op0);
4770     return BinaryOperator::CreateXor(NOr, C1);
4771   }
4772
4773   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4774   if (Op1->hasOneUse() &&
4775       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4776       MaskedValueIsZero(Op0, C1->getValue())) {
4777     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4778     InsertNewInstBefore(NOr, I);
4779     NOr->takeName(Op0);
4780     return BinaryOperator::CreateXor(NOr, C1);
4781   }
4782
4783   // (A & C)|(B & D)
4784   Value *C = 0, *D = 0;
4785   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4786       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4787     Value *V1 = 0, *V2 = 0, *V3 = 0;
4788     C1 = dyn_cast<ConstantInt>(C);
4789     C2 = dyn_cast<ConstantInt>(D);
4790     if (C1 && C2) {  // (A & C1)|(B & C2)
4791       // If we have: ((V + N) & C1) | (V & C2)
4792       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793       // replace with V+N.
4794       if (C1->getValue() == ~C2->getValue()) {
4795         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4796             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4797           // Add commutes, try both ways.
4798           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799             return ReplaceInstUsesWith(I, A);
4800           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801             return ReplaceInstUsesWith(I, A);
4802         }
4803         // Or commutes, try both ways.
4804         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4805             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4806           // Add commutes, try both ways.
4807           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808             return ReplaceInstUsesWith(I, B);
4809           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810             return ReplaceInstUsesWith(I, B);
4811         }
4812       }
4813       V1 = 0; V2 = 0; V3 = 0;
4814     }
4815     
4816     // Check to see if we have any common things being and'ed.  If so, find the
4817     // terms for V1 & (V2|V3).
4818     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4820         V1 = A, V2 = C, V3 = D;
4821       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822         V1 = A, V2 = B, V3 = C;
4823       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824         V1 = C, V2 = A, V3 = D;
4825       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826         V1 = C, V2 = A, V3 = B;
4827       
4828       if (V1) {
4829         Value *Or =
4830           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4831         return BinaryOperator::CreateAnd(V1, Or);
4832       }
4833     }
4834
4835     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4836     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4837       return Match;
4838     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4839       return Match;
4840     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4841       return Match;
4842     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4843       return Match;
4844
4845     // ((A&~B)|(~A&B)) -> A^B
4846     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4847          match(B, m_Not(m_Specific(A)), *Context)))
4848       return BinaryOperator::CreateXor(A, D);
4849     // ((~B&A)|(~A&B)) -> A^B
4850     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4851          match(B, m_Not(m_Specific(C)), *Context)))
4852       return BinaryOperator::CreateXor(C, D);
4853     // ((A&~B)|(B&~A)) -> A^B
4854     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4855          match(D, m_Not(m_Specific(A)), *Context)))
4856       return BinaryOperator::CreateXor(A, B);
4857     // ((~B&A)|(B&~A)) -> A^B
4858     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4859          match(D, m_Not(m_Specific(C)), *Context)))
4860       return BinaryOperator::CreateXor(C, B);
4861   }
4862   
4863   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4864   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4865     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4866       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4867           SI0->getOperand(1) == SI1->getOperand(1) &&
4868           (SI0->hasOneUse() || SI1->hasOneUse())) {
4869         Instruction *NewOp =
4870         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4871                                                      SI1->getOperand(0),
4872                                                      SI0->getName()), I);
4873         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4874                                       SI1->getOperand(1));
4875       }
4876   }
4877
4878   // ((A|B)&1)|(B&-2) -> (A&1) | B
4879   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4880       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4881     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4882     if (Ret) return Ret;
4883   }
4884   // (B&-2)|((A|B)&1) -> (A&1) | B
4885   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4886       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4887     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4888     if (Ret) return Ret;
4889   }
4890
4891   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4892     if (A == Op1)   // ~A | A == -1
4893       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4894   } else {
4895     A = 0;
4896   }
4897   // Note, A is still live here!
4898   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4899     if (Op0 == B)
4900       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4901
4902     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4903     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4904       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4905                                               I.getName()+".demorgan"), I);
4906       return BinaryOperator::CreateNot(*Context, And);
4907     }
4908   }
4909
4910   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4912     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4913       return R;
4914
4915     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4917         return Res;
4918   }
4919     
4920   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4921   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4922     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4923       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4924         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925             !isa<ICmpInst>(Op1C->getOperand(0))) {
4926           const Type *SrcTy = Op0C->getOperand(0)->getType();
4927           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4928               // Only do this if the casts both really cause code to be
4929               // generated.
4930               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4931                                 I.getType(), TD) &&
4932               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4933                                 I.getType(), TD)) {
4934             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4935                                                           Op1C->getOperand(0),
4936                                                           I.getName());
4937             InsertNewInstBefore(NewOp, I);
4938             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4939           }
4940         }
4941       }
4942   }
4943   
4944     
4945   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4946   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4947     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4948       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4949           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4950           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4951         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4952           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4953             // If either of the constants are nans, then the whole thing returns
4954             // true.
4955             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4956               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4957             
4958             // Otherwise, no need to compare the two constants, compare the
4959             // rest.
4960             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4961                                 LHS->getOperand(0), RHS->getOperand(0));
4962           }
4963       } else {
4964         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4965         FCmpInst::Predicate Op0CC, Op1CC;
4966         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4967                   m_Value(Op0RHS)), *Context) &&
4968             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4969                   m_Value(Op1RHS)), *Context)) {
4970           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4971             // Swap RHS operands to match LHS.
4972             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4973             std::swap(Op1LHS, Op1RHS);
4974           }
4975           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4976             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4977             if (Op0CC == Op1CC)
4978               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4979                                   Op0LHS, Op0RHS);
4980             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4981                      Op1CC == FCmpInst::FCMP_TRUE)
4982               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4983             else if (Op0CC == FCmpInst::FCMP_FALSE)
4984               return ReplaceInstUsesWith(I, Op1);
4985             else if (Op1CC == FCmpInst::FCMP_FALSE)
4986               return ReplaceInstUsesWith(I, Op0);
4987             bool Op0Ordered;
4988             bool Op1Ordered;
4989             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4990             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4991             if (Op0Ordered == Op1Ordered) {
4992               // If both are ordered or unordered, return a new fcmp with
4993               // or'ed predicates.
4994               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4995                                        Op0LHS, Op0RHS, Context);
4996               if (Instruction *I = dyn_cast<Instruction>(RV))
4997                 return I;
4998               // Otherwise, it's a constant boolean value...
4999               return ReplaceInstUsesWith(I, RV);
5000             }
5001           }
5002         }
5003       }
5004     }
5005   }
5006
5007   return Changed ? &I : 0;
5008 }
5009
5010 namespace {
5011
5012 // XorSelf - Implements: X ^ X --> 0
5013 struct XorSelf {
5014   Value *RHS;
5015   XorSelf(Value *rhs) : RHS(rhs) {}
5016   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5017   Instruction *apply(BinaryOperator &Xor) const {
5018     return &Xor;
5019   }
5020 };
5021
5022 }
5023
5024 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5025   bool Changed = SimplifyCommutative(I);
5026   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5027
5028   if (isa<UndefValue>(Op1)) {
5029     if (isa<UndefValue>(Op0))
5030       // Handle undef ^ undef -> 0 special case. This is a common
5031       // idiom (misuse).
5032       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5033     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5034   }
5035
5036   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5037   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5038     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5039     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5040   }
5041   
5042   // See if we can simplify any instructions used by the instruction whose sole 
5043   // purpose is to compute bits we don't care about.
5044   if (SimplifyDemandedInstructionBits(I))
5045     return &I;
5046   if (isa<VectorType>(I.getType()))
5047     if (isa<ConstantAggregateZero>(Op1))
5048       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5049
5050   // Is this a ~ operation?
5051   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5052     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5053     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5054     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5055       if (Op0I->getOpcode() == Instruction::And || 
5056           Op0I->getOpcode() == Instruction::Or) {
5057         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5058         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5059           Instruction *NotY =
5060             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5061                                       Op0I->getOperand(1)->getName()+".not");
5062           InsertNewInstBefore(NotY, I);
5063           if (Op0I->getOpcode() == Instruction::And)
5064             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5065           else
5066             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5067         }
5068       }
5069     }
5070   }
5071   
5072   
5073   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5074     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5075       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5076       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5077         return new ICmpInst(*Context, ICI->getInversePredicate(),
5078                             ICI->getOperand(0), ICI->getOperand(1));
5079
5080       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5081         return new FCmpInst(*Context, FCI->getInversePredicate(),
5082                             FCI->getOperand(0), FCI->getOperand(1));
5083     }
5084
5085     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5086     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5087       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5088         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5089           Instruction::CastOps Opcode = Op0C->getOpcode();
5090           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5091             if (RHS == Context->getConstantExprCast(Opcode, 
5092                                              Context->getConstantIntTrue(),
5093                                              Op0C->getDestTy())) {
5094               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5095                                      *Context,
5096                                      CI->getOpcode(), CI->getInversePredicate(),
5097                                      CI->getOperand(0), CI->getOperand(1)), I);
5098               NewCI->takeName(CI);
5099               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5100             }
5101           }
5102         }
5103       }
5104     }
5105
5106     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5107       // ~(c-X) == X-c-1 == X+(-c-1)
5108       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5109         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5110           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5111           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5112                                       Context->getConstantInt(I.getType(), 1));
5113           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5114         }
5115           
5116       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5117         if (Op0I->getOpcode() == Instruction::Add) {
5118           // ~(X-c) --> (-c-1)-X
5119           if (RHS->isAllOnesValue()) {
5120             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5121             return BinaryOperator::CreateSub(
5122                            Context->getConstantExprSub(NegOp0CI,
5123                                       Context->getConstantInt(I.getType(), 1)),
5124                                       Op0I->getOperand(0));
5125           } else if (RHS->getValue().isSignBit()) {
5126             // (X + C) ^ signbit -> (X + C + signbit)
5127             Constant *C =
5128                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5129             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5130
5131           }
5132         } else if (Op0I->getOpcode() == Instruction::Or) {
5133           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5134           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5135             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5136             // Anything in both C1 and C2 is known to be zero, remove it from
5137             // NewRHS.
5138             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5139             NewRHS = Context->getConstantExprAnd(NewRHS, 
5140                                        Context->getConstantExprNot(CommonBits));
5141             AddToWorkList(Op0I);
5142             I.setOperand(0, Op0I->getOperand(0));
5143             I.setOperand(1, NewRHS);
5144             return &I;
5145           }
5146         }
5147       }
5148     }
5149
5150     // Try to fold constant and into select arguments.
5151     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5152       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5153         return R;
5154     if (isa<PHINode>(Op0))
5155       if (Instruction *NV = FoldOpIntoPhi(I))
5156         return NV;
5157   }
5158
5159   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5160     if (X == Op1)
5161       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5162
5163   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5164     if (X == Op0)
5165       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5166
5167   
5168   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5169   if (Op1I) {
5170     Value *A, *B;
5171     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5172       if (A == Op0) {              // B^(B|A) == (A|B)^B
5173         Op1I->swapOperands();
5174         I.swapOperands();
5175         std::swap(Op0, Op1);
5176       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5177         I.swapOperands();     // Simplified below.
5178         std::swap(Op0, Op1);
5179       }
5180     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5181       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5182     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5183       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5184     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5185                Op1I->hasOneUse()){
5186       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5187         Op1I->swapOperands();
5188         std::swap(A, B);
5189       }
5190       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5191         I.swapOperands();     // Simplified below.
5192         std::swap(Op0, Op1);
5193       }
5194     }
5195   }
5196   
5197   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5198   if (Op0I) {
5199     Value *A, *B;
5200     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5201         Op0I->hasOneUse()) {
5202       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5203         std::swap(A, B);
5204       if (B == Op1) {                                // (A|B)^B == A & ~B
5205         Instruction *NotB =
5206           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5207                                                         Op1, "tmp"), I);
5208         return BinaryOperator::CreateAnd(A, NotB);
5209       }
5210     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5211       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5212     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5213       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5214     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5215                Op0I->hasOneUse()){
5216       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5217         std::swap(A, B);
5218       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5219           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5220         Instruction *N =
5221           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5222         return BinaryOperator::CreateAnd(N, Op1);
5223       }
5224     }
5225   }
5226   
5227   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5228   if (Op0I && Op1I && Op0I->isShift() && 
5229       Op0I->getOpcode() == Op1I->getOpcode() && 
5230       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5231       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5232     Instruction *NewOp =
5233       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5234                                                     Op1I->getOperand(0),
5235                                                     Op0I->getName()), I);
5236     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5237                                   Op1I->getOperand(1));
5238   }
5239     
5240   if (Op0I && Op1I) {
5241     Value *A, *B, *C, *D;
5242     // (A & B)^(A | B) -> A ^ B
5243     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5245       if ((A == C && B == D) || (A == D && B == C)) 
5246         return BinaryOperator::CreateXor(A, B);
5247     }
5248     // (A | B)^(A & B) -> A ^ B
5249     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5250         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5251       if ((A == C && B == D) || (A == D && B == C)) 
5252         return BinaryOperator::CreateXor(A, B);
5253     }
5254     
5255     // (A & B)^(C & D)
5256     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5257         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5258         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5259       // (X & Y)^(X & Y) -> (Y^Z) & X
5260       Value *X = 0, *Y = 0, *Z = 0;
5261       if (A == C)
5262         X = A, Y = B, Z = D;
5263       else if (A == D)
5264         X = A, Y = B, Z = C;
5265       else if (B == C)
5266         X = B, Y = A, Z = D;
5267       else if (B == D)
5268         X = B, Y = A, Z = C;
5269       
5270       if (X) {
5271         Instruction *NewOp =
5272         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5273         return BinaryOperator::CreateAnd(NewOp, X);
5274       }
5275     }
5276   }
5277     
5278   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5280     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5281       return R;
5282
5283   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5284   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5285     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5286       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287         const Type *SrcTy = Op0C->getOperand(0)->getType();
5288         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5289             // Only do this if the casts both really cause code to be generated.
5290             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5291                               I.getType(), TD) &&
5292             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5293                               I.getType(), TD)) {
5294           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5295                                                          Op1C->getOperand(0),
5296                                                          I.getName());
5297           InsertNewInstBefore(NewOp, I);
5298           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5299         }
5300       }
5301   }
5302
5303   return Changed ? &I : 0;
5304 }
5305
5306 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5307                                    LLVMContext *Context) {
5308   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5309 }
5310
5311 static bool HasAddOverflow(ConstantInt *Result,
5312                            ConstantInt *In1, ConstantInt *In2,
5313                            bool IsSigned) {
5314   if (IsSigned)
5315     if (In2->getValue().isNegative())
5316       return Result->getValue().sgt(In1->getValue());
5317     else
5318       return Result->getValue().slt(In1->getValue());
5319   else
5320     return Result->getValue().ult(In1->getValue());
5321 }
5322
5323 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5324 /// overflowed for this type.
5325 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5326                             Constant *In2, LLVMContext *Context,
5327                             bool IsSigned = false) {
5328   Result = Context->getConstantExprAdd(In1, In2);
5329
5330   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5331     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5332       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5333       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5334                          ExtractElement(In1, Idx, Context),
5335                          ExtractElement(In2, Idx, Context),
5336                          IsSigned))
5337         return true;
5338     }
5339     return false;
5340   }
5341
5342   return HasAddOverflow(cast<ConstantInt>(Result),
5343                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5344                         IsSigned);
5345 }
5346
5347 static bool HasSubOverflow(ConstantInt *Result,
5348                            ConstantInt *In1, ConstantInt *In2,
5349                            bool IsSigned) {
5350   if (IsSigned)
5351     if (In2->getValue().isNegative())
5352       return Result->getValue().slt(In1->getValue());
5353     else
5354       return Result->getValue().sgt(In1->getValue());
5355   else
5356     return Result->getValue().ugt(In1->getValue());
5357 }
5358
5359 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5360 /// overflowed for this type.
5361 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5362                             Constant *In2, LLVMContext *Context,
5363                             bool IsSigned = false) {
5364   Result = Context->getConstantExprSub(In1, In2);
5365
5366   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5368       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5369       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5370                          ExtractElement(In1, Idx, Context),
5371                          ExtractElement(In2, Idx, Context),
5372                          IsSigned))
5373         return true;
5374     }
5375     return false;
5376   }
5377
5378   return HasSubOverflow(cast<ConstantInt>(Result),
5379                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380                         IsSigned);
5381 }
5382
5383 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5384 /// code necessary to compute the offset from the base pointer (without adding
5385 /// in the base pointer).  Return the result as a signed integer of intptr size.
5386 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5387   TargetData &TD = IC.getTargetData();
5388   gep_type_iterator GTI = gep_type_begin(GEP);
5389   const Type *IntPtrTy = TD.getIntPtrType();
5390   LLVMContext *Context = IC.getContext();
5391   Value *Result = Context->getNullValue(IntPtrTy);
5392
5393   // Build a mask for high order bits.
5394   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5395   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5396
5397   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5398        ++i, ++GTI) {
5399     Value *Op = *i;
5400     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5401     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5402       if (OpC->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         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5407         
5408         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5409           Result = 
5410              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5411         else
5412           Result = IC.InsertNewInstBefore(
5413                    BinaryOperator::CreateAdd(Result,
5414                                         Context->getConstantInt(IntPtrTy, Size),
5415                                              GEP->getName()+".offs"), I);
5416         continue;
5417       }
5418       
5419       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5420       Constant *OC =
5421               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5422       Scale = Context->getConstantExprMul(OC, Scale);
5423       if (Constant *RC = dyn_cast<Constant>(Result))
5424         Result = Context->getConstantExprAdd(RC, Scale);
5425       else {
5426         // Emit an add instruction.
5427         Result = IC.InsertNewInstBefore(
5428            BinaryOperator::CreateAdd(Result, Scale,
5429                                      GEP->getName()+".offs"), I);
5430       }
5431       continue;
5432     }
5433     // Convert to correct type.
5434     if (Op->getType() != IntPtrTy) {
5435       if (Constant *OpC = dyn_cast<Constant>(Op))
5436         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5437       else
5438         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5439                                                                 true,
5440                                                       Op->getName()+".c"), I);
5441     }
5442     if (Size != 1) {
5443       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5444       if (Constant *OpC = dyn_cast<Constant>(Op))
5445         Op = Context->getConstantExprMul(OpC, Scale);
5446       else    // We'll let instcombine(mul) convert this to a shl if possible.
5447         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5448                                                   GEP->getName()+".idx"), I);
5449     }
5450
5451     // Emit an add instruction.
5452     if (isa<Constant>(Op) && isa<Constant>(Result))
5453       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5454                                     cast<Constant>(Result));
5455     else
5456       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5457                                                   GEP->getName()+".offs"), I);
5458   }
5459   return Result;
5460 }
5461
5462
5463 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5464 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5465 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5466 /// complex, and scales are involved.  The above expression would also be legal
5467 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5468 /// later form is less amenable to optimization though, and we are allowed to
5469 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5470 ///
5471 /// If we can't emit an optimized form for this expression, this returns null.
5472 /// 
5473 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5474                                           InstCombiner &IC) {
5475   TargetData &TD = IC.getTargetData();
5476   gep_type_iterator GTI = gep_type_begin(GEP);
5477
5478   // Check to see if this gep only has a single variable index.  If so, and if
5479   // any constant indices are a multiple of its scale, then we can compute this
5480   // in terms of the scale of the variable index.  For example, if the GEP
5481   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5482   // because the expression will cross zero at the same point.
5483   unsigned i, e = GEP->getNumOperands();
5484   int64_t Offset = 0;
5485   for (i = 1; i != e; ++i, ++GTI) {
5486     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5487       // Compute the aggregate offset of constant indices.
5488       if (CI->isZero()) continue;
5489
5490       // Handle a struct index, which adds its field offset to the pointer.
5491       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5492         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5493       } else {
5494         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5495         Offset += Size*CI->getSExtValue();
5496       }
5497     } else {
5498       // Found our variable index.
5499       break;
5500     }
5501   }
5502   
5503   // If there are no variable indices, we must have a constant offset, just
5504   // evaluate it the general way.
5505   if (i == e) return 0;
5506   
5507   Value *VariableIdx = GEP->getOperand(i);
5508   // Determine the scale factor of the variable element.  For example, this is
5509   // 4 if the variable index is into an array of i32.
5510   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5511   
5512   // Verify that there are no other variable indices.  If so, emit the hard way.
5513   for (++i, ++GTI; i != e; ++i, ++GTI) {
5514     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5515     if (!CI) return 0;
5516    
5517     // Compute the aggregate offset of constant indices.
5518     if (CI->isZero()) continue;
5519     
5520     // Handle a struct index, which adds its field offset to the pointer.
5521     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5522       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5523     } else {
5524       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5525       Offset += Size*CI->getSExtValue();
5526     }
5527   }
5528   
5529   // Okay, we know we have a single variable index, which must be a
5530   // pointer/array/vector index.  If there is no offset, life is simple, return
5531   // the index.
5532   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5533   if (Offset == 0) {
5534     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5535     // we don't need to bother extending: the extension won't affect where the
5536     // computation crosses zero.
5537     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5538       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5539                                   VariableIdx->getNameStart(), &I);
5540     return VariableIdx;
5541   }
5542   
5543   // Otherwise, there is an index.  The computation we will do will be modulo
5544   // the pointer size, so get it.
5545   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5546   
5547   Offset &= PtrSizeMask;
5548   VariableScale &= PtrSizeMask;
5549
5550   // To do this transformation, any constant index must be a multiple of the
5551   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5552   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5553   // multiple of the variable scale.
5554   int64_t NewOffs = Offset / (int64_t)VariableScale;
5555   if (Offset != NewOffs*(int64_t)VariableScale)
5556     return 0;
5557
5558   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5559   const Type *IntPtrTy = TD.getIntPtrType();
5560   if (VariableIdx->getType() != IntPtrTy)
5561     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5562                                               true /*SExt*/, 
5563                                               VariableIdx->getNameStart(), &I);
5564   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5565   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5566 }
5567
5568
5569 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5570 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5571 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5572                                        ICmpInst::Predicate Cond,
5573                                        Instruction &I) {
5574   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5575
5576   // Look through bitcasts.
5577   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5578     RHS = BCI->getOperand(0);
5579
5580   Value *PtrBase = GEPLHS->getOperand(0);
5581   if (PtrBase == RHS) {
5582     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5583     // This transformation (ignoring the base and scales) is valid because we
5584     // know pointers can't overflow.  See if we can output an optimized form.
5585     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5586     
5587     // If not, synthesize the offset the hard way.
5588     if (Offset == 0)
5589       Offset = EmitGEPOffset(GEPLHS, I, *this);
5590     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5591                         Context->getNullValue(Offset->getType()));
5592   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5593     // If the base pointers are different, but the indices are the same, just
5594     // compare the base pointer.
5595     if (PtrBase != GEPRHS->getOperand(0)) {
5596       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5597       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5598                         GEPRHS->getOperand(0)->getType();
5599       if (IndicesTheSame)
5600         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5601           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5602             IndicesTheSame = false;
5603             break;
5604           }
5605
5606       // If all indices are the same, just compare the base pointers.
5607       if (IndicesTheSame)
5608         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5609                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5610
5611       // Otherwise, the base pointers are different and the indices are
5612       // different, bail out.
5613       return 0;
5614     }
5615
5616     // If one of the GEPs has all zero indices, recurse.
5617     bool AllZeros = true;
5618     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5619       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5620           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5621         AllZeros = false;
5622         break;
5623       }
5624     if (AllZeros)
5625       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5626                           ICmpInst::getSwappedPredicate(Cond), I);
5627
5628     // If the other GEP has all zero indices, recurse.
5629     AllZeros = true;
5630     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5631       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5632           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5633         AllZeros = false;
5634         break;
5635       }
5636     if (AllZeros)
5637       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5638
5639     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5640       // If the GEPs only differ by one index, compare it.
5641       unsigned NumDifferences = 0;  // Keep track of # differences.
5642       unsigned DiffOperand = 0;     // The operand that differs.
5643       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5644         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5645           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5646                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5647             // Irreconcilable differences.
5648             NumDifferences = 2;
5649             break;
5650           } else {
5651             if (NumDifferences++) break;
5652             DiffOperand = i;
5653           }
5654         }
5655
5656       if (NumDifferences == 0)   // SAME GEP?
5657         return ReplaceInstUsesWith(I, // No comparison is needed here.
5658                                    Context->getConstantInt(Type::Int1Ty,
5659                                              ICmpInst::isTrueWhenEqual(Cond)));
5660
5661       else if (NumDifferences == 1) {
5662         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5663         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5664         // Make sure we do a signed comparison here.
5665         return new ICmpInst(*Context,
5666                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5667       }
5668     }
5669
5670     // Only lower this if the icmp is the only user of the GEP or if we expect
5671     // the result to fold to a constant!
5672     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5673         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5674       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5675       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5676       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5677       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5678     }
5679   }
5680   return 0;
5681 }
5682
5683 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5684 ///
5685 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5686                                                 Instruction *LHSI,
5687                                                 Constant *RHSC) {
5688   if (!isa<ConstantFP>(RHSC)) return 0;
5689   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5690   
5691   // Get the width of the mantissa.  We don't want to hack on conversions that
5692   // might lose information from the integer, e.g. "i64 -> float"
5693   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5694   if (MantissaWidth == -1) return 0;  // Unknown.
5695   
5696   // Check to see that the input is converted from an integer type that is small
5697   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5698   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5699   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5700   
5701   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5702   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5703   if (LHSUnsigned)
5704     ++InputSize;
5705   
5706   // If the conversion would lose info, don't hack on this.
5707   if ((int)InputSize > MantissaWidth)
5708     return 0;
5709   
5710   // Otherwise, we can potentially simplify the comparison.  We know that it
5711   // will always come through as an integer value and we know the constant is
5712   // not a NAN (it would have been previously simplified).
5713   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5714   
5715   ICmpInst::Predicate Pred;
5716   switch (I.getPredicate()) {
5717   default: LLVM_UNREACHABLE("Unexpected predicate!");
5718   case FCmpInst::FCMP_UEQ:
5719   case FCmpInst::FCMP_OEQ:
5720     Pred = ICmpInst::ICMP_EQ;
5721     break;
5722   case FCmpInst::FCMP_UGT:
5723   case FCmpInst::FCMP_OGT:
5724     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5725     break;
5726   case FCmpInst::FCMP_UGE:
5727   case FCmpInst::FCMP_OGE:
5728     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5729     break;
5730   case FCmpInst::FCMP_ULT:
5731   case FCmpInst::FCMP_OLT:
5732     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5733     break;
5734   case FCmpInst::FCMP_ULE:
5735   case FCmpInst::FCMP_OLE:
5736     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5737     break;
5738   case FCmpInst::FCMP_UNE:
5739   case FCmpInst::FCMP_ONE:
5740     Pred = ICmpInst::ICMP_NE;
5741     break;
5742   case FCmpInst::FCMP_ORD:
5743     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5744   case FCmpInst::FCMP_UNO:
5745     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5746   }
5747   
5748   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5749   
5750   // Now we know that the APFloat is a normal number, zero or inf.
5751   
5752   // See if the FP constant is too large for the integer.  For example,
5753   // comparing an i8 to 300.0.
5754   unsigned IntWidth = IntTy->getScalarSizeInBits();
5755   
5756   if (!LHSUnsigned) {
5757     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5758     // and large values.
5759     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5760     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5761                           APFloat::rmNearestTiesToEven);
5762     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5763       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5764           Pred == ICmpInst::ICMP_SLE)
5765         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5766       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5767     }
5768   } else {
5769     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5770     // +INF and large values.
5771     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5772     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5773                           APFloat::rmNearestTiesToEven);
5774     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5775       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5776           Pred == ICmpInst::ICMP_ULE)
5777         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5778       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5779     }
5780   }
5781   
5782   if (!LHSUnsigned) {
5783     // See if the RHS value is < SignedMin.
5784     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5785     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5786                           APFloat::rmNearestTiesToEven);
5787     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5788       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5789           Pred == ICmpInst::ICMP_SGE)
5790         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5791       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5792     }
5793   }
5794
5795   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5796   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5797   // casting the FP value to the integer value and back, checking for equality.
5798   // Don't do this for zero, because -0.0 is not fractional.
5799   Constant *RHSInt = LHSUnsigned
5800     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5801     : Context->getConstantExprFPToSI(RHSC, IntTy);
5802   if (!RHS.isZero()) {
5803     bool Equal = LHSUnsigned
5804       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5805       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5806     if (!Equal) {
5807       // If we had a comparison against a fractional value, we have to adjust
5808       // the compare predicate and sometimes the value.  RHSC is rounded towards
5809       // zero at this point.
5810       switch (Pred) {
5811       default: LLVM_UNREACHABLE("Unexpected integer comparison!");
5812       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5813         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5814       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5815         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5816       case ICmpInst::ICMP_ULE:
5817         // (float)int <= 4.4   --> int <= 4
5818         // (float)int <= -4.4  --> false
5819         if (RHS.isNegative())
5820           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5821         break;
5822       case ICmpInst::ICMP_SLE:
5823         // (float)int <= 4.4   --> int <= 4
5824         // (float)int <= -4.4  --> int < -4
5825         if (RHS.isNegative())
5826           Pred = ICmpInst::ICMP_SLT;
5827         break;
5828       case ICmpInst::ICMP_ULT:
5829         // (float)int < -4.4   --> false
5830         // (float)int < 4.4    --> int <= 4
5831         if (RHS.isNegative())
5832           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5833         Pred = ICmpInst::ICMP_ULE;
5834         break;
5835       case ICmpInst::ICMP_SLT:
5836         // (float)int < -4.4   --> int < -4
5837         // (float)int < 4.4    --> int <= 4
5838         if (!RHS.isNegative())
5839           Pred = ICmpInst::ICMP_SLE;
5840         break;
5841       case ICmpInst::ICMP_UGT:
5842         // (float)int > 4.4    --> int > 4
5843         // (float)int > -4.4   --> true
5844         if (RHS.isNegative())
5845           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5846         break;
5847       case ICmpInst::ICMP_SGT:
5848         // (float)int > 4.4    --> int > 4
5849         // (float)int > -4.4   --> int >= -4
5850         if (RHS.isNegative())
5851           Pred = ICmpInst::ICMP_SGE;
5852         break;
5853       case ICmpInst::ICMP_UGE:
5854         // (float)int >= -4.4   --> true
5855         // (float)int >= 4.4    --> int > 4
5856         if (!RHS.isNegative())
5857           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5858         Pred = ICmpInst::ICMP_UGT;
5859         break;
5860       case ICmpInst::ICMP_SGE:
5861         // (float)int >= -4.4   --> int >= -4
5862         // (float)int >= 4.4    --> int > 4
5863         if (!RHS.isNegative())
5864           Pred = ICmpInst::ICMP_SGT;
5865         break;
5866       }
5867     }
5868   }
5869
5870   // Lower this FP comparison into an appropriate integer version of the
5871   // comparison.
5872   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5873 }
5874
5875 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5876   bool Changed = SimplifyCompare(I);
5877   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5878
5879   // Fold trivial predicates.
5880   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5881     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5882   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5883     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5884   
5885   // Simplify 'fcmp pred X, X'
5886   if (Op0 == Op1) {
5887     switch (I.getPredicate()) {
5888     default: LLVM_UNREACHABLE("Unknown predicate!");
5889     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5890     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5891     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5892       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5893     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5894     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5895     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5896       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5897       
5898     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5899     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5900     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5901     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5902       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5903       I.setPredicate(FCmpInst::FCMP_UNO);
5904       I.setOperand(1, Context->getNullValue(Op0->getType()));
5905       return &I;
5906       
5907     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5908     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5909     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5910     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5911       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5912       I.setPredicate(FCmpInst::FCMP_ORD);
5913       I.setOperand(1, Context->getNullValue(Op0->getType()));
5914       return &I;
5915     }
5916   }
5917     
5918   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5919     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5920
5921   // Handle fcmp with constant RHS
5922   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5923     // If the constant is a nan, see if we can fold the comparison based on it.
5924     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5925       if (CFP->getValueAPF().isNaN()) {
5926         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5927           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5928         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5929                "Comparison must be either ordered or unordered!");
5930         // True if unordered.
5931         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5932       }
5933     }
5934     
5935     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5936       switch (LHSI->getOpcode()) {
5937       case Instruction::PHI:
5938         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5939         // block.  If in the same block, we're encouraging jump threading.  If
5940         // not, we are just pessimizing the code by making an i1 phi.
5941         if (LHSI->getParent() == I.getParent())
5942           if (Instruction *NV = FoldOpIntoPhi(I))
5943             return NV;
5944         break;
5945       case Instruction::SIToFP:
5946       case Instruction::UIToFP:
5947         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5948           return NV;
5949         break;
5950       case Instruction::Select:
5951         // If either operand of the select is a constant, we can fold the
5952         // comparison into the select arms, which will cause one to be
5953         // constant folded and the select turned into a bitwise or.
5954         Value *Op1 = 0, *Op2 = 0;
5955         if (LHSI->hasOneUse()) {
5956           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5957             // Fold the known value into the constant operand.
5958             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5959             // Insert a new FCmp of the other select operand.
5960             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5961                                                       LHSI->getOperand(2), RHSC,
5962                                                       I.getName()), I);
5963           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5964             // Fold the known value into the constant operand.
5965             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5966             // Insert a new FCmp of the other select operand.
5967             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5968                                                       LHSI->getOperand(1), RHSC,
5969                                                       I.getName()), I);
5970           }
5971         }
5972
5973         if (Op1)
5974           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5975         break;
5976       }
5977   }
5978
5979   return Changed ? &I : 0;
5980 }
5981
5982 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5983   bool Changed = SimplifyCompare(I);
5984   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5985   const Type *Ty = Op0->getType();
5986
5987   // icmp X, X
5988   if (Op0 == Op1)
5989     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5990                                                    I.isTrueWhenEqual()));
5991
5992   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5993     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5994   
5995   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5996   // addresses never equal each other!  We already know that Op0 != Op1.
5997   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5998        isa<ConstantPointerNull>(Op0)) &&
5999       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6000        isa<ConstantPointerNull>(Op1)))
6001     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
6002                                                    !I.isTrueWhenEqual()));
6003
6004   // icmp's with boolean values can always be turned into bitwise operations
6005   if (Ty == Type::Int1Ty) {
6006     switch (I.getPredicate()) {
6007     default: LLVM_UNREACHABLE("Invalid icmp instruction!");
6008     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6009       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6010       InsertNewInstBefore(Xor, I);
6011       return BinaryOperator::CreateNot(*Context, Xor);
6012     }
6013     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6014       return BinaryOperator::CreateXor(Op0, Op1);
6015
6016     case ICmpInst::ICMP_UGT:
6017       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6018       // FALL THROUGH
6019     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6020       Instruction *Not = BinaryOperator::CreateNot(*Context,
6021                                                    Op0, I.getName()+"tmp");
6022       InsertNewInstBefore(Not, I);
6023       return BinaryOperator::CreateAnd(Not, Op1);
6024     }
6025     case ICmpInst::ICMP_SGT:
6026       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6027       // FALL THROUGH
6028     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6029       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6030                                                    Op1, I.getName()+"tmp");
6031       InsertNewInstBefore(Not, I);
6032       return BinaryOperator::CreateAnd(Not, Op0);
6033     }
6034     case ICmpInst::ICMP_UGE:
6035       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6036       // FALL THROUGH
6037     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6038       Instruction *Not = BinaryOperator::CreateNot(*Context,
6039                                                    Op0, I.getName()+"tmp");
6040       InsertNewInstBefore(Not, I);
6041       return BinaryOperator::CreateOr(Not, Op1);
6042     }
6043     case ICmpInst::ICMP_SGE:
6044       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6045       // FALL THROUGH
6046     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6047       Instruction *Not = BinaryOperator::CreateNot(*Context,
6048                                                    Op1, I.getName()+"tmp");
6049       InsertNewInstBefore(Not, I);
6050       return BinaryOperator::CreateOr(Not, Op0);
6051     }
6052     }
6053   }
6054
6055   unsigned BitWidth = 0;
6056   if (TD)
6057     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058   else if (Ty->isIntOrIntVector())
6059     BitWidth = Ty->getScalarSizeInBits();
6060
6061   bool isSignBit = false;
6062
6063   // See if we are doing a comparison with a constant.
6064   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6065     Value *A = 0, *B = 0;
6066     
6067     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068     if (I.isEquality() && CI->isNullValue() &&
6069         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6070       // (icmp cond A B) if cond is equality
6071       return new ICmpInst(*Context, I.getPredicate(), A, B);
6072     }
6073     
6074     // If we have an icmp le or icmp ge instruction, turn it into the
6075     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6076     // them being folded in the code below.
6077     switch (I.getPredicate()) {
6078     default: break;
6079     case ICmpInst::ICMP_ULE:
6080       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6081         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6082       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6083                           AddOne(CI, Context));
6084     case ICmpInst::ICMP_SLE:
6085       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6086         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6087       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6088                           AddOne(CI, Context));
6089     case ICmpInst::ICMP_UGE:
6090       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6091         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6092       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6093                           SubOne(CI, Context));
6094     case ICmpInst::ICMP_SGE:
6095       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6096         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6097       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6098                           SubOne(CI, Context));
6099     }
6100     
6101     // If this comparison is a normal comparison, it demands all
6102     // bits, if it is a sign bit comparison, it only demands the sign bit.
6103     bool UnusedBit;
6104     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105   }
6106
6107   // See if we can fold the comparison based on range information we can get
6108   // by checking whether bits are known to be zero or one in the input.
6109   if (BitWidth != 0) {
6110     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113     if (SimplifyDemandedBits(I.getOperandUse(0),
6114                              isSignBit ? APInt::getSignBit(BitWidth)
6115                                        : APInt::getAllOnesValue(BitWidth),
6116                              Op0KnownZero, Op0KnownOne, 0))
6117       return &I;
6118     if (SimplifyDemandedBits(I.getOperandUse(1),
6119                              APInt::getAllOnesValue(BitWidth),
6120                              Op1KnownZero, Op1KnownOne, 0))
6121       return &I;
6122
6123     // Given the known and unknown bits, compute a range that the LHS could be
6124     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6125     // EQ and NE we use unsigned values.
6126     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6128     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6129       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130                                              Op0Min, Op0Max);
6131       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132                                              Op1Min, Op1Max);
6133     } else {
6134       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135                                                Op0Min, Op0Max);
6136       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137                                                Op1Min, Op1Max);
6138     }
6139
6140     // If Min and Max are known to be the same, then SimplifyDemandedBits
6141     // figured out that the LHS is a constant.  Just constant fold this now so
6142     // that code below can assume that Min != Max.
6143     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6144       return new ICmpInst(*Context, I.getPredicate(),
6145                           Context->getConstantInt(Op0Min), Op1);
6146     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6147       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6148                           Context->getConstantInt(Op1Min));
6149
6150     // Based on the range information we know about the LHS, see if we can
6151     // simplify this comparison.  For example, (x&4) < 8  is always true.
6152     switch (I.getPredicate()) {
6153     default: LLVM_UNREACHABLE("Unknown icmp opcode!");
6154     case ICmpInst::ICMP_EQ:
6155       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6156         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6157       break;
6158     case ICmpInst::ICMP_NE:
6159       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6160         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6161       break;
6162     case ICmpInst::ICMP_ULT:
6163       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6164         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6165       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6166         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6167       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6168         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6169       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6171           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6172                               SubOne(CI, Context));
6173
6174         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6175         if (CI->isMinValue(true))
6176           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6177                            Context->getAllOnesValue(Op0->getType()));
6178       }
6179       break;
6180     case ICmpInst::ICMP_UGT:
6181       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6182         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6183       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6184         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6185
6186       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6187         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6188       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6190           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191                               AddOne(CI, Context));
6192
6193         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6194         if (CI->isMaxValue(true))
6195           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6196                               Context->getNullValue(Op0->getType()));
6197       }
6198       break;
6199     case ICmpInst::ICMP_SLT:
6200       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6201         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6202       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6203         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6204       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6205         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6206       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6208           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209                               SubOne(CI, Context));
6210       }
6211       break;
6212     case ICmpInst::ICMP_SGT:
6213       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6214         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6215       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6216         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6217
6218       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6219         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6220       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6222           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6223                               AddOne(CI, Context));
6224       }
6225       break;
6226     case ICmpInst::ICMP_SGE:
6227       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6229         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6230       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6231         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6232       break;
6233     case ICmpInst::ICMP_SLE:
6234       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6236         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6237       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6238         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6239       break;
6240     case ICmpInst::ICMP_UGE:
6241       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6243         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6244       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6245         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6246       break;
6247     case ICmpInst::ICMP_ULE:
6248       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6250         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6251       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6252         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6253       break;
6254     }
6255
6256     // Turn a signed comparison into an unsigned one if both operands
6257     // are known to have the same sign.
6258     if (I.isSignedPredicate() &&
6259         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6261       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6262   }
6263
6264   // Test if the ICmpInst instruction is used exclusively by a select as
6265   // part of a minimum or maximum operation. If so, refrain from doing
6266   // any other folding. This helps out other analyses which understand
6267   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268   // and CodeGen. And in this case, at least one of the comparison
6269   // operands has at least one user besides the compare (the select),
6270   // which would often largely negate the benefit of folding anyway.
6271   if (I.hasOneUse())
6272     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275         return 0;
6276
6277   // See if we are doing a comparison between a constant and an instruction that
6278   // can be folded into the comparison.
6279   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6280     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6281     // instruction, see if that instruction also has constants so that the 
6282     // instruction can be folded into the icmp 
6283     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6284       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285         return Res;
6286   }
6287
6288   // Handle icmp with constant (but not simple integer constant) RHS
6289   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291       switch (LHSI->getOpcode()) {
6292       case Instruction::GetElementPtr:
6293         if (RHSC->isNullValue()) {
6294           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6295           bool isAllZeros = true;
6296           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297             if (!isa<Constant>(LHSI->getOperand(i)) ||
6298                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299               isAllZeros = false;
6300               break;
6301             }
6302           if (isAllZeros)
6303             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6304                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6305         }
6306         break;
6307
6308       case Instruction::PHI:
6309         // Only fold icmp into the PHI if the phi and fcmp are in the same
6310         // block.  If in the same block, we're encouraging jump threading.  If
6311         // not, we are just pessimizing the code by making an i1 phi.
6312         if (LHSI->getParent() == I.getParent())
6313           if (Instruction *NV = FoldOpIntoPhi(I))
6314             return NV;
6315         break;
6316       case Instruction::Select: {
6317         // If either operand of the select is a constant, we can fold the
6318         // comparison into the select arms, which will cause one to be
6319         // constant folded and the select turned into a bitwise or.
6320         Value *Op1 = 0, *Op2 = 0;
6321         if (LHSI->hasOneUse()) {
6322           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323             // Fold the known value into the constant operand.
6324             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6325             // Insert a new ICmp of the other select operand.
6326             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6327                                                    LHSI->getOperand(2), RHSC,
6328                                                    I.getName()), I);
6329           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6330             // Fold the known value into the constant operand.
6331             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6332             // Insert a new ICmp of the other select operand.
6333             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6334                                                    LHSI->getOperand(1), RHSC,
6335                                                    I.getName()), I);
6336           }
6337         }
6338
6339         if (Op1)
6340           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6341         break;
6342       }
6343       case Instruction::Malloc:
6344         // If we have (malloc != null), and if the malloc has a single use, we
6345         // can assume it is successful and remove the malloc.
6346         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6347           AddToWorkList(LHSI);
6348           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6349                                                          !I.isTrueWhenEqual()));
6350         }
6351         break;
6352       }
6353   }
6354
6355   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6356   if (User *GEP = dyn_castGetElementPtr(Op0))
6357     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6358       return NI;
6359   if (User *GEP = dyn_castGetElementPtr(Op1))
6360     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6361                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6362       return NI;
6363
6364   // Test to see if the operands of the icmp are casted versions of other
6365   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6366   // now.
6367   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6368     if (isa<PointerType>(Op0->getType()) && 
6369         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6370       // We keep moving the cast from the left operand over to the right
6371       // operand, where it can often be eliminated completely.
6372       Op0 = CI->getOperand(0);
6373
6374       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6375       // so eliminate it as well.
6376       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6377         Op1 = CI2->getOperand(0);
6378
6379       // If Op1 is a constant, we can fold the cast into the constant.
6380       if (Op0->getType() != Op1->getType()) {
6381         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6382           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6383         } else {
6384           // Otherwise, cast the RHS right before the icmp
6385           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6386         }
6387       }
6388       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6389     }
6390   }
6391   
6392   if (isa<CastInst>(Op0)) {
6393     // Handle the special case of: icmp (cast bool to X), <cst>
6394     // This comes up when you have code like
6395     //   int X = A < B;
6396     //   if (X) ...
6397     // For generality, we handle any zero-extension of any operand comparison
6398     // with a constant or another cast from the same type.
6399     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6400       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6401         return R;
6402   }
6403   
6404   // See if it's the same type of instruction on the left and right.
6405   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6406     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6407       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6408           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6409         switch (Op0I->getOpcode()) {
6410         default: break;
6411         case Instruction::Add:
6412         case Instruction::Sub:
6413         case Instruction::Xor:
6414           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6415             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6416                                 Op1I->getOperand(0));
6417           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6418           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6419             if (CI->getValue().isSignBit()) {
6420               ICmpInst::Predicate Pred = I.isSignedPredicate()
6421                                              ? I.getUnsignedPredicate()
6422                                              : I.getSignedPredicate();
6423               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6424                                   Op1I->getOperand(0));
6425             }
6426             
6427             if (CI->getValue().isMaxSignedValue()) {
6428               ICmpInst::Predicate Pred = I.isSignedPredicate()
6429                                              ? I.getUnsignedPredicate()
6430                                              : I.getSignedPredicate();
6431               Pred = I.getSwappedPredicate(Pred);
6432               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6433                                   Op1I->getOperand(0));
6434             }
6435           }
6436           break;
6437         case Instruction::Mul:
6438           if (!I.isEquality())
6439             break;
6440
6441           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6442             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6443             // Mask = -1 >> count-trailing-zeros(Cst).
6444             if (!CI->isZero() && !CI->isOne()) {
6445               const APInt &AP = CI->getValue();
6446               ConstantInt *Mask = Context->getConstantInt(
6447                                       APInt::getLowBitsSet(AP.getBitWidth(),
6448                                                            AP.getBitWidth() -
6449                                                       AP.countTrailingZeros()));
6450               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6451                                                             Mask);
6452               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6453                                                             Mask);
6454               InsertNewInstBefore(And1, I);
6455               InsertNewInstBefore(And2, I);
6456               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6457             }
6458           }
6459           break;
6460         }
6461       }
6462     }
6463   }
6464   
6465   // ~x < ~y --> y < x
6466   { Value *A, *B;
6467     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6468         match(Op1, m_Not(m_Value(B)), *Context))
6469       return new ICmpInst(*Context, I.getPredicate(), B, A);
6470   }
6471   
6472   if (I.isEquality()) {
6473     Value *A, *B, *C, *D;
6474     
6475     // -x == -y --> x == y
6476     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6477         match(Op1, m_Neg(m_Value(B)), *Context))
6478       return new ICmpInst(*Context, I.getPredicate(), A, B);
6479     
6480     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6481       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6482         Value *OtherVal = A == Op1 ? B : A;
6483         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6484                             Context->getNullValue(A->getType()));
6485       }
6486
6487       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6488         // A^c1 == C^c2 --> A == C^(c1^c2)
6489         ConstantInt *C1, *C2;
6490         if (match(B, m_ConstantInt(C1), *Context) &&
6491             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6492           Constant *NC = 
6493                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6494           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6495           return new ICmpInst(*Context, I.getPredicate(), A,
6496                               InsertNewInstBefore(Xor, I));
6497         }
6498         
6499         // A^B == A^D -> B == D
6500         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6501         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6502         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6503         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6504       }
6505     }
6506     
6507     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6508         (A == Op0 || B == Op0)) {
6509       // A == (A^B)  ->  B == 0
6510       Value *OtherVal = A == Op0 ? B : A;
6511       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6512                           Context->getNullValue(A->getType()));
6513     }
6514
6515     // (A-B) == A  ->  B == 0
6516     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6517       return new ICmpInst(*Context, I.getPredicate(), B, 
6518                           Context->getNullValue(B->getType()));
6519
6520     // A == (A-B)  ->  B == 0
6521     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6522       return new ICmpInst(*Context, I.getPredicate(), B,
6523                           Context->getNullValue(B->getType()));
6524     
6525     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6526     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6527         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6528         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6529       Value *X = 0, *Y = 0, *Z = 0;
6530       
6531       if (A == C) {
6532         X = B; Y = D; Z = A;
6533       } else if (A == D) {
6534         X = B; Y = C; Z = A;
6535       } else if (B == C) {
6536         X = A; Y = D; Z = B;
6537       } else if (B == D) {
6538         X = A; Y = C; Z = B;
6539       }
6540       
6541       if (X) {   // Build (X^Y) & Z
6542         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6543         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6544         I.setOperand(0, Op1);
6545         I.setOperand(1, Context->getNullValue(Op1->getType()));
6546         return &I;
6547       }
6548     }
6549   }
6550   return Changed ? &I : 0;
6551 }
6552
6553
6554 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6555 /// and CmpRHS are both known to be integer constants.
6556 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6557                                           ConstantInt *DivRHS) {
6558   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6559   const APInt &CmpRHSV = CmpRHS->getValue();
6560   
6561   // FIXME: If the operand types don't match the type of the divide 
6562   // then don't attempt this transform. The code below doesn't have the
6563   // logic to deal with a signed divide and an unsigned compare (and
6564   // vice versa). This is because (x /s C1) <s C2  produces different 
6565   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6566   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6567   // work. :(  The if statement below tests that condition and bails 
6568   // if it finds it. 
6569   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6570   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6571     return 0;
6572   if (DivRHS->isZero())
6573     return 0; // The ProdOV computation fails on divide by zero.
6574   if (DivIsSigned && DivRHS->isAllOnesValue())
6575     return 0; // The overflow computation also screws up here
6576   if (DivRHS->isOne())
6577     return 0; // Not worth bothering, and eliminates some funny cases
6578               // with INT_MIN.
6579
6580   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6581   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6582   // C2 (CI). By solving for X we can turn this into a range check 
6583   // instead of computing a divide. 
6584   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6585
6586   // Determine if the product overflows by seeing if the product is
6587   // not equal to the divide. Make sure we do the same kind of divide
6588   // as in the LHS instruction that we're folding. 
6589   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6590                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6591
6592   // Get the ICmp opcode
6593   ICmpInst::Predicate Pred = ICI.getPredicate();
6594
6595   // Figure out the interval that is being checked.  For example, a comparison
6596   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6597   // Compute this interval based on the constants involved and the signedness of
6598   // the compare/divide.  This computes a half-open interval, keeping track of
6599   // whether either value in the interval overflows.  After analysis each
6600   // overflow variable is set to 0 if it's corresponding bound variable is valid
6601   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6602   int LoOverflow = 0, HiOverflow = 0;
6603   Constant *LoBound = 0, *HiBound = 0;
6604   
6605   if (!DivIsSigned) {  // udiv
6606     // e.g. X/5 op 3  --> [15, 20)
6607     LoBound = Prod;
6608     HiOverflow = LoOverflow = ProdOV;
6609     if (!HiOverflow)
6610       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6611   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6612     if (CmpRHSV == 0) {       // (X / pos) op 0
6613       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6614       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6615                                                                     Context)));
6616       HiBound = DivRHS;
6617     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6618       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6619       HiOverflow = LoOverflow = ProdOV;
6620       if (!HiOverflow)
6621         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6622     } else {                       // (X / pos) op neg
6623       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6624       HiBound = AddOne(Prod, Context);
6625       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6626       if (!LoOverflow) {
6627         ConstantInt* DivNeg =
6628                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6629         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6630                                      true) ? -1 : 0;
6631        }
6632     }
6633   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6634     if (CmpRHSV == 0) {       // (X / neg) op 0
6635       // e.g. X/-5 op 0  --> [-4, 5)
6636       LoBound = AddOne(DivRHS, Context);
6637       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6638       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6639         HiOverflow = 1;            // [INTMIN+1, overflow)
6640         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6641       }
6642     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6643       // e.g. X/-5 op 3  --> [-19, -14)
6644       HiBound = AddOne(Prod, Context);
6645       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6646       if (!LoOverflow)
6647         LoOverflow = AddWithOverflow(LoBound, HiBound,
6648                                      DivRHS, Context, true) ? -1 : 0;
6649     } else {                       // (X / neg) op neg
6650       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6651       LoOverflow = HiOverflow = ProdOV;
6652       if (!HiOverflow)
6653         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6654     }
6655     
6656     // Dividing by a negative swaps the condition.  LT <-> GT
6657     Pred = ICmpInst::getSwappedPredicate(Pred);
6658   }
6659
6660   Value *X = DivI->getOperand(0);
6661   switch (Pred) {
6662   default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
6663   case ICmpInst::ICMP_EQ:
6664     if (LoOverflow && HiOverflow)
6665       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6666     else if (HiOverflow)
6667       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6668                           ICmpInst::ICMP_UGE, X, LoBound);
6669     else if (LoOverflow)
6670       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6671                           ICmpInst::ICMP_ULT, X, HiBound);
6672     else
6673       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6674   case ICmpInst::ICMP_NE:
6675     if (LoOverflow && HiOverflow)
6676       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6677     else if (HiOverflow)
6678       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6679                           ICmpInst::ICMP_ULT, X, LoBound);
6680     else if (LoOverflow)
6681       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6682                           ICmpInst::ICMP_UGE, X, HiBound);
6683     else
6684       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6685   case ICmpInst::ICMP_ULT:
6686   case ICmpInst::ICMP_SLT:
6687     if (LoOverflow == +1)   // Low bound is greater than input range.
6688       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6689     if (LoOverflow == -1)   // Low bound is less than input range.
6690       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6691     return new ICmpInst(*Context, Pred, X, LoBound);
6692   case ICmpInst::ICMP_UGT:
6693   case ICmpInst::ICMP_SGT:
6694     if (HiOverflow == +1)       // High bound greater than input range.
6695       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6696     else if (HiOverflow == -1)  // High bound less than input range.
6697       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6698     if (Pred == ICmpInst::ICMP_UGT)
6699       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6700     else
6701       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6702   }
6703 }
6704
6705
6706 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6707 ///
6708 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6709                                                           Instruction *LHSI,
6710                                                           ConstantInt *RHS) {
6711   const APInt &RHSV = RHS->getValue();
6712   
6713   switch (LHSI->getOpcode()) {
6714   case Instruction::Trunc:
6715     if (ICI.isEquality() && LHSI->hasOneUse()) {
6716       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6717       // of the high bits truncated out of x are known.
6718       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6719              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6720       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6721       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6722       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6723       
6724       // If all the high bits are known, we can do this xform.
6725       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6726         // Pull in the high bits from known-ones set.
6727         APInt NewRHS(RHS->getValue());
6728         NewRHS.zext(SrcBits);
6729         NewRHS |= KnownOne;
6730         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6731                             Context->getConstantInt(NewRHS));
6732       }
6733     }
6734     break;
6735       
6736   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6737     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6738       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6739       // fold the xor.
6740       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6741           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6742         Value *CompareVal = LHSI->getOperand(0);
6743         
6744         // If the sign bit of the XorCST is not set, there is no change to
6745         // the operation, just stop using the Xor.
6746         if (!XorCST->getValue().isNegative()) {
6747           ICI.setOperand(0, CompareVal);
6748           AddToWorkList(LHSI);
6749           return &ICI;
6750         }
6751         
6752         // Was the old condition true if the operand is positive?
6753         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6754         
6755         // If so, the new one isn't.
6756         isTrueIfPositive ^= true;
6757         
6758         if (isTrueIfPositive)
6759           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6760                               SubOne(RHS, Context));
6761         else
6762           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6763                               AddOne(RHS, Context));
6764       }
6765
6766       if (LHSI->hasOneUse()) {
6767         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6768         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6769           const APInt &SignBit = XorCST->getValue();
6770           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6771                                          ? ICI.getUnsignedPredicate()
6772                                          : ICI.getSignedPredicate();
6773           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6774                               Context->getConstantInt(RHSV ^ SignBit));
6775         }
6776
6777         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6778         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6779           const APInt &NotSignBit = XorCST->getValue();
6780           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6781                                          ? ICI.getUnsignedPredicate()
6782                                          : ICI.getSignedPredicate();
6783           Pred = ICI.getSwappedPredicate(Pred);
6784           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6785                               Context->getConstantInt(RHSV ^ NotSignBit));
6786         }
6787       }
6788     }
6789     break;
6790   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6791     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6792         LHSI->getOperand(0)->hasOneUse()) {
6793       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6794       
6795       // If the LHS is an AND of a truncating cast, we can widen the
6796       // and/compare to be the input width without changing the value
6797       // produced, eliminating a cast.
6798       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6799         // We can do this transformation if either the AND constant does not
6800         // have its sign bit set or if it is an equality comparison. 
6801         // Extending a relational comparison when we're checking the sign
6802         // bit would not work.
6803         if (Cast->hasOneUse() &&
6804             (ICI.isEquality() ||
6805              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6806           uint32_t BitWidth = 
6807             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6808           APInt NewCST = AndCST->getValue();
6809           NewCST.zext(BitWidth);
6810           APInt NewCI = RHSV;
6811           NewCI.zext(BitWidth);
6812           Instruction *NewAnd = 
6813             BinaryOperator::CreateAnd(Cast->getOperand(0),
6814                                Context->getConstantInt(NewCST),LHSI->getName());
6815           InsertNewInstBefore(NewAnd, ICI);
6816           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6817                               Context->getConstantInt(NewCI));
6818         }
6819       }
6820       
6821       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6822       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6823       // happens a LOT in code produced by the C front-end, for bitfield
6824       // access.
6825       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6826       if (Shift && !Shift->isShift())
6827         Shift = 0;
6828       
6829       ConstantInt *ShAmt;
6830       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6831       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6832       const Type *AndTy = AndCST->getType();          // Type of the and.
6833       
6834       // We can fold this as long as we can't shift unknown bits
6835       // into the mask.  This can only happen with signed shift
6836       // rights, as they sign-extend.
6837       if (ShAmt) {
6838         bool CanFold = Shift->isLogicalShift();
6839         if (!CanFold) {
6840           // To test for the bad case of the signed shr, see if any
6841           // of the bits shifted in could be tested after the mask.
6842           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6843           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6844           
6845           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6846           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6847                AndCST->getValue()) == 0)
6848             CanFold = true;
6849         }
6850         
6851         if (CanFold) {
6852           Constant *NewCst;
6853           if (Shift->getOpcode() == Instruction::Shl)
6854             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6855           else
6856             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6857           
6858           // Check to see if we are shifting out any of the bits being
6859           // compared.
6860           if (Context->getConstantExpr(Shift->getOpcode(),
6861                                        NewCst, ShAmt) != RHS) {
6862             // If we shifted bits out, the fold is not going to work out.
6863             // As a special case, check to see if this means that the
6864             // result is always true or false now.
6865             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6866               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6867             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6868               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6869           } else {
6870             ICI.setOperand(1, NewCst);
6871             Constant *NewAndCST;
6872             if (Shift->getOpcode() == Instruction::Shl)
6873               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6874             else
6875               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6876             LHSI->setOperand(1, NewAndCST);
6877             LHSI->setOperand(0, Shift->getOperand(0));
6878             AddToWorkList(Shift); // Shift is dead.
6879             AddUsesToWorkList(ICI);
6880             return &ICI;
6881           }
6882         }
6883       }
6884       
6885       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6886       // preferable because it allows the C<<Y expression to be hoisted out
6887       // of a loop if Y is invariant and X is not.
6888       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6889           ICI.isEquality() && !Shift->isArithmeticShift() &&
6890           !isa<Constant>(Shift->getOperand(0))) {
6891         // Compute C << Y.
6892         Value *NS;
6893         if (Shift->getOpcode() == Instruction::LShr) {
6894           NS = BinaryOperator::CreateShl(AndCST, 
6895                                          Shift->getOperand(1), "tmp");
6896         } else {
6897           // Insert a logical shift.
6898           NS = BinaryOperator::CreateLShr(AndCST,
6899                                           Shift->getOperand(1), "tmp");
6900         }
6901         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6902         
6903         // Compute X & (C << Y).
6904         Instruction *NewAnd = 
6905           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6906         InsertNewInstBefore(NewAnd, ICI);
6907         
6908         ICI.setOperand(0, NewAnd);
6909         return &ICI;
6910       }
6911     }
6912     break;
6913     
6914   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6915     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6916     if (!ShAmt) break;
6917     
6918     uint32_t TypeBits = RHSV.getBitWidth();
6919     
6920     // Check that the shift amount is in range.  If not, don't perform
6921     // undefined shifts.  When the shift is visited it will be
6922     // simplified.
6923     if (ShAmt->uge(TypeBits))
6924       break;
6925     
6926     if (ICI.isEquality()) {
6927       // If we are comparing against bits always shifted out, the
6928       // comparison cannot succeed.
6929       Constant *Comp =
6930         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6931                                                                  ShAmt);
6932       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6933         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6934         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6935         return ReplaceInstUsesWith(ICI, Cst);
6936       }
6937       
6938       if (LHSI->hasOneUse()) {
6939         // Otherwise strength reduce the shift into an and.
6940         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6941         Constant *Mask =
6942           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6943                                                        TypeBits-ShAmtVal));
6944         
6945         Instruction *AndI =
6946           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6947                                     Mask, LHSI->getName()+".mask");
6948         Value *And = InsertNewInstBefore(AndI, ICI);
6949         return new ICmpInst(*Context, ICI.getPredicate(), And,
6950                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6951       }
6952     }
6953     
6954     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6955     bool TrueIfSigned = false;
6956     if (LHSI->hasOneUse() &&
6957         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6958       // (X << 31) <s 0  --> (X&1) != 0
6959       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6960                                            (TypeBits-ShAmt->getZExtValue()-1));
6961       Instruction *AndI =
6962         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6963                                   Mask, LHSI->getName()+".mask");
6964       Value *And = InsertNewInstBefore(AndI, ICI);
6965       
6966       return new ICmpInst(*Context,
6967                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6968                           And, Context->getNullValue(And->getType()));
6969     }
6970     break;
6971   }
6972     
6973   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6974   case Instruction::AShr: {
6975     // Only handle equality comparisons of shift-by-constant.
6976     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6977     if (!ShAmt || !ICI.isEquality()) break;
6978
6979     // Check that the shift amount is in range.  If not, don't perform
6980     // undefined shifts.  When the shift is visited it will be
6981     // simplified.
6982     uint32_t TypeBits = RHSV.getBitWidth();
6983     if (ShAmt->uge(TypeBits))
6984       break;
6985     
6986     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6987       
6988     // If we are comparing against bits always shifted out, the
6989     // comparison cannot succeed.
6990     APInt Comp = RHSV << ShAmtVal;
6991     if (LHSI->getOpcode() == Instruction::LShr)
6992       Comp = Comp.lshr(ShAmtVal);
6993     else
6994       Comp = Comp.ashr(ShAmtVal);
6995     
6996     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6998       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6999       return ReplaceInstUsesWith(ICI, Cst);
7000     }
7001     
7002     // Otherwise, check to see if the bits shifted out are known to be zero.
7003     // If so, we can compare against the unshifted value:
7004     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7005     if (LHSI->hasOneUse() &&
7006         MaskedValueIsZero(LHSI->getOperand(0), 
7007                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7008       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7009                           Context->getConstantExprShl(RHS, ShAmt));
7010     }
7011       
7012     if (LHSI->hasOneUse()) {
7013       // Otherwise strength reduce the shift into an and.
7014       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7015       Constant *Mask = Context->getConstantInt(Val);
7016       
7017       Instruction *AndI =
7018         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7019                                   Mask, LHSI->getName()+".mask");
7020       Value *And = InsertNewInstBefore(AndI, ICI);
7021       return new ICmpInst(*Context, ICI.getPredicate(), And,
7022                           Context->getConstantExprShl(RHS, ShAmt));
7023     }
7024     break;
7025   }
7026     
7027   case Instruction::SDiv:
7028   case Instruction::UDiv:
7029     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7030     // Fold this div into the comparison, producing a range check. 
7031     // Determine, based on the divide type, what the range is being 
7032     // checked.  If there is an overflow on the low or high side, remember 
7033     // it, otherwise compute the range [low, hi) bounding the new value.
7034     // See: InsertRangeTest above for the kinds of replacements possible.
7035     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7036       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7037                                           DivRHS))
7038         return R;
7039     break;
7040
7041   case Instruction::Add:
7042     // Fold: icmp pred (add, X, C1), C2
7043
7044     if (!ICI.isEquality()) {
7045       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7046       if (!LHSC) break;
7047       const APInt &LHSV = LHSC->getValue();
7048
7049       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7050                             .subtract(LHSV);
7051
7052       if (ICI.isSignedPredicate()) {
7053         if (CR.getLower().isSignBit()) {
7054           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7055                               Context->getConstantInt(CR.getUpper()));
7056         } else if (CR.getUpper().isSignBit()) {
7057           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7058                               Context->getConstantInt(CR.getLower()));
7059         }
7060       } else {
7061         if (CR.getLower().isMinValue()) {
7062           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7063                               Context->getConstantInt(CR.getUpper()));
7064         } else if (CR.getUpper().isMinValue()) {
7065           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7066                               Context->getConstantInt(CR.getLower()));
7067         }
7068       }
7069     }
7070     break;
7071   }
7072   
7073   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7074   if (ICI.isEquality()) {
7075     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7076     
7077     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7078     // the second operand is a constant, simplify a bit.
7079     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7080       switch (BO->getOpcode()) {
7081       case Instruction::SRem:
7082         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7083         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7084           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7085           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7086             Instruction *NewRem =
7087               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7088                                          BO->getName());
7089             InsertNewInstBefore(NewRem, ICI);
7090             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7091                                 Context->getNullValue(BO->getType()));
7092           }
7093         }
7094         break;
7095       case Instruction::Add:
7096         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7097         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7098           if (BO->hasOneUse())
7099             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7100                                 Context->getConstantExprSub(RHS, BOp1C));
7101         } else if (RHSV == 0) {
7102           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7103           // efficiently invertible, or if the add has just this one use.
7104           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7105           
7106           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7107             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7108           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7109             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7110           else if (BO->hasOneUse()) {
7111             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7112             InsertNewInstBefore(Neg, ICI);
7113             Neg->takeName(BO);
7114             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7115           }
7116         }
7117         break;
7118       case Instruction::Xor:
7119         // For the xor case, we can xor two constants together, eliminating
7120         // the explicit xor.
7121         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7122           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7123                               Context->getConstantExprXor(RHS, BOC));
7124         
7125         // FALLTHROUGH
7126       case Instruction::Sub:
7127         // Replace (([sub|xor] A, B) != 0) with (A != B)
7128         if (RHSV == 0)
7129           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7130                               BO->getOperand(1));
7131         break;
7132         
7133       case Instruction::Or:
7134         // If bits are being or'd in that are not present in the constant we
7135         // are comparing against, then the comparison could never succeed!
7136         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7137           Constant *NotCI = Context->getConstantExprNot(RHS);
7138           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7139             return ReplaceInstUsesWith(ICI,
7140                                        Context->getConstantInt(Type::Int1Ty, 
7141                                        isICMP_NE));
7142         }
7143         break;
7144         
7145       case Instruction::And:
7146         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7147           // If bits are being compared against that are and'd out, then the
7148           // comparison can never succeed!
7149           if ((RHSV & ~BOC->getValue()) != 0)
7150             return ReplaceInstUsesWith(ICI,
7151                                        Context->getConstantInt(Type::Int1Ty,
7152                                        isICMP_NE));
7153           
7154           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7155           if (RHS == BOC && RHSV.isPowerOf2())
7156             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7157                                 ICmpInst::ICMP_NE, LHSI,
7158                                 Context->getNullValue(RHS->getType()));
7159           
7160           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7161           if (BOC->getValue().isSignBit()) {
7162             Value *X = BO->getOperand(0);
7163             Constant *Zero = Context->getNullValue(X->getType());
7164             ICmpInst::Predicate pred = isICMP_NE ? 
7165               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7166             return new ICmpInst(*Context, pred, X, Zero);
7167           }
7168           
7169           // ((X & ~7) == 0) --> X < 8
7170           if (RHSV == 0 && isHighOnes(BOC)) {
7171             Value *X = BO->getOperand(0);
7172             Constant *NegX = Context->getConstantExprNeg(BOC);
7173             ICmpInst::Predicate pred = isICMP_NE ? 
7174               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7175             return new ICmpInst(*Context, pred, X, NegX);
7176           }
7177         }
7178       default: break;
7179       }
7180     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7181       // Handle icmp {eq|ne} <intrinsic>, intcst.
7182       if (II->getIntrinsicID() == Intrinsic::bswap) {
7183         AddToWorkList(II);
7184         ICI.setOperand(0, II->getOperand(1));
7185         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7186         return &ICI;
7187       }
7188     }
7189   }
7190   return 0;
7191 }
7192
7193 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7194 /// We only handle extending casts so far.
7195 ///
7196 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7197   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7198   Value *LHSCIOp        = LHSCI->getOperand(0);
7199   const Type *SrcTy     = LHSCIOp->getType();
7200   const Type *DestTy    = LHSCI->getType();
7201   Value *RHSCIOp;
7202
7203   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7204   // integer type is the same size as the pointer type.
7205   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7206       getTargetData().getPointerSizeInBits() == 
7207          cast<IntegerType>(DestTy)->getBitWidth()) {
7208     Value *RHSOp = 0;
7209     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7210       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7211     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7212       RHSOp = RHSC->getOperand(0);
7213       // If the pointer types don't match, insert a bitcast.
7214       if (LHSCIOp->getType() != RHSOp->getType())
7215         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7216     }
7217
7218     if (RHSOp)
7219       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7220   }
7221   
7222   // The code below only handles extension cast instructions, so far.
7223   // Enforce this.
7224   if (LHSCI->getOpcode() != Instruction::ZExt &&
7225       LHSCI->getOpcode() != Instruction::SExt)
7226     return 0;
7227
7228   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7229   bool isSignedCmp = ICI.isSignedPredicate();
7230
7231   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7232     // Not an extension from the same type?
7233     RHSCIOp = CI->getOperand(0);
7234     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7235       return 0;
7236     
7237     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7238     // and the other is a zext), then we can't handle this.
7239     if (CI->getOpcode() != LHSCI->getOpcode())
7240       return 0;
7241
7242     // Deal with equality cases early.
7243     if (ICI.isEquality())
7244       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7245
7246     // A signed comparison of sign extended values simplifies into a
7247     // signed comparison.
7248     if (isSignedCmp && isSignedExt)
7249       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7250
7251     // The other three cases all fold into an unsigned comparison.
7252     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7253   }
7254
7255   // If we aren't dealing with a constant on the RHS, exit early
7256   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7257   if (!CI)
7258     return 0;
7259
7260   // Compute the constant that would happen if we truncated to SrcTy then
7261   // reextended to DestTy.
7262   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7263   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7264                                                 Res1, DestTy);
7265
7266   // If the re-extended constant didn't change...
7267   if (Res2 == CI) {
7268     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7269     // For example, we might have:
7270     //    %A = sext i16 %X to i32
7271     //    %B = icmp ugt i32 %A, 1330
7272     // It is incorrect to transform this into 
7273     //    %B = icmp ugt i16 %X, 1330
7274     // because %A may have negative value. 
7275     //
7276     // However, we allow this when the compare is EQ/NE, because they are
7277     // signless.
7278     if (isSignedExt == isSignedCmp || ICI.isEquality())
7279       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7280     return 0;
7281   }
7282
7283   // The re-extended constant changed so the constant cannot be represented 
7284   // in the shorter type. Consequently, we cannot emit a simple comparison.
7285
7286   // First, handle some easy cases. We know the result cannot be equal at this
7287   // point so handle the ICI.isEquality() cases
7288   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7289     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7290   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7291     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7292
7293   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7294   // should have been folded away previously and not enter in here.
7295   Value *Result;
7296   if (isSignedCmp) {
7297     // We're performing a signed comparison.
7298     if (cast<ConstantInt>(CI)->getValue().isNegative())
7299       Result = Context->getConstantIntFalse();          // X < (small) --> false
7300     else
7301       Result = Context->getConstantIntTrue();           // X < (large) --> true
7302   } else {
7303     // We're performing an unsigned comparison.
7304     if (isSignedExt) {
7305       // We're performing an unsigned comp with a sign extended value.
7306       // This is true if the input is >= 0. [aka >s -1]
7307       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7308       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7309                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7310     } else {
7311       // Unsigned extend & unsigned compare -> always true.
7312       Result = Context->getConstantIntTrue();
7313     }
7314   }
7315
7316   // Finally, return the value computed.
7317   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7318       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7319     return ReplaceInstUsesWith(ICI, Result);
7320
7321   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7322           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7323          "ICmp should be folded!");
7324   if (Constant *CI = dyn_cast<Constant>(Result))
7325     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7326   return BinaryOperator::CreateNot(*Context, Result);
7327 }
7328
7329 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7330   return commonShiftTransforms(I);
7331 }
7332
7333 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7334   return commonShiftTransforms(I);
7335 }
7336
7337 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7338   if (Instruction *R = commonShiftTransforms(I))
7339     return R;
7340   
7341   Value *Op0 = I.getOperand(0);
7342   
7343   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7344   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7345     if (CSI->isAllOnesValue())
7346       return ReplaceInstUsesWith(I, CSI);
7347
7348   // See if we can turn a signed shr into an unsigned shr.
7349   if (MaskedValueIsZero(Op0,
7350                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7351     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7352
7353   // Arithmetic shifting an all-sign-bit value is a no-op.
7354   unsigned NumSignBits = ComputeNumSignBits(Op0);
7355   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7356     return ReplaceInstUsesWith(I, Op0);
7357
7358   return 0;
7359 }
7360
7361 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7362   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7363   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7364
7365   // shl X, 0 == X and shr X, 0 == X
7366   // shl 0, X == 0 and shr 0, X == 0
7367   if (Op1 == Context->getNullValue(Op1->getType()) ||
7368       Op0 == Context->getNullValue(Op0->getType()))
7369     return ReplaceInstUsesWith(I, Op0);
7370   
7371   if (isa<UndefValue>(Op0)) {            
7372     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7373       return ReplaceInstUsesWith(I, Op0);
7374     else                                    // undef << X -> 0, undef >>u X -> 0
7375       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7376   }
7377   if (isa<UndefValue>(Op1)) {
7378     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7379       return ReplaceInstUsesWith(I, Op0);          
7380     else                                     // X << undef, X >>u undef -> 0
7381       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7382   }
7383
7384   // See if we can fold away this shift.
7385   if (SimplifyDemandedInstructionBits(I))
7386     return &I;
7387
7388   // Try to fold constant and into select arguments.
7389   if (isa<Constant>(Op0))
7390     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7391       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7392         return R;
7393
7394   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7395     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7396       return Res;
7397   return 0;
7398 }
7399
7400 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7401                                                BinaryOperator &I) {
7402   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7403
7404   // See if we can simplify any instructions used by the instruction whose sole 
7405   // purpose is to compute bits we don't care about.
7406   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7407   
7408   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7409   // a signed shift.
7410   //
7411   if (Op1->uge(TypeBits)) {
7412     if (I.getOpcode() != Instruction::AShr)
7413       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7414     else {
7415       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7416       return &I;
7417     }
7418   }
7419   
7420   // ((X*C1) << C2) == (X * (C1 << C2))
7421   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7422     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7423       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7424         return BinaryOperator::CreateMul(BO->getOperand(0),
7425                                         Context->getConstantExprShl(BOOp, Op1));
7426   
7427   // Try to fold constant and into select arguments.
7428   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7429     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7430       return R;
7431   if (isa<PHINode>(Op0))
7432     if (Instruction *NV = FoldOpIntoPhi(I))
7433       return NV;
7434   
7435   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7436   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7437     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7438     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7439     // place.  Don't try to do this transformation in this case.  Also, we
7440     // require that the input operand is a shift-by-constant so that we have
7441     // confidence that the shifts will get folded together.  We could do this
7442     // xform in more cases, but it is unlikely to be profitable.
7443     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7444         isa<ConstantInt>(TrOp->getOperand(1))) {
7445       // Okay, we'll do this xform.  Make the shift of shift.
7446       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7447       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7448                                                 I.getName());
7449       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7450
7451       // For logical shifts, the truncation has the effect of making the high
7452       // part of the register be zeros.  Emulate this by inserting an AND to
7453       // clear the top bits as needed.  This 'and' will usually be zapped by
7454       // other xforms later if dead.
7455       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7456       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7457       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7458       
7459       // The mask we constructed says what the trunc would do if occurring
7460       // between the shifts.  We want to know the effect *after* the second
7461       // shift.  We know that it is a logical shift by a constant, so adjust the
7462       // mask as appropriate.
7463       if (I.getOpcode() == Instruction::Shl)
7464         MaskV <<= Op1->getZExtValue();
7465       else {
7466         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7467         MaskV = MaskV.lshr(Op1->getZExtValue());
7468       }
7469
7470       Instruction *And =
7471         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7472                                   TI->getName());
7473       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7474
7475       // Return the value truncated to the interesting size.
7476       return new TruncInst(And, I.getType());
7477     }
7478   }
7479   
7480   if (Op0->hasOneUse()) {
7481     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7482       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7483       Value *V1, *V2;
7484       ConstantInt *CC;
7485       switch (Op0BO->getOpcode()) {
7486         default: break;
7487         case Instruction::Add:
7488         case Instruction::And:
7489         case Instruction::Or:
7490         case Instruction::Xor: {
7491           // These operators commute.
7492           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7493           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7494               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7495                     m_Specific(Op1)), *Context)){
7496             Instruction *YS = BinaryOperator::CreateShl(
7497                                             Op0BO->getOperand(0), Op1,
7498                                             Op0BO->getName());
7499             InsertNewInstBefore(YS, I); // (Y << C)
7500             Instruction *X = 
7501               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7502                                      Op0BO->getOperand(1)->getName());
7503             InsertNewInstBefore(X, I);  // (X + (Y << C))
7504             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7505             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7506                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7507           }
7508           
7509           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7510           Value *Op0BOOp1 = Op0BO->getOperand(1);
7511           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7512               match(Op0BOOp1, 
7513                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7514                           m_ConstantInt(CC)), *Context) &&
7515               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7516             Instruction *YS = BinaryOperator::CreateShl(
7517                                                      Op0BO->getOperand(0), Op1,
7518                                                      Op0BO->getName());
7519             InsertNewInstBefore(YS, I); // (Y << C)
7520             Instruction *XM =
7521               BinaryOperator::CreateAnd(V1,
7522                                         Context->getConstantExprShl(CC, Op1),
7523                                         V1->getName()+".mask");
7524             InsertNewInstBefore(XM, I); // X & (CC << C)
7525             
7526             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7527           }
7528         }
7529           
7530         // FALL THROUGH.
7531         case Instruction::Sub: {
7532           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7533           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7534               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7535                     m_Specific(Op1)), *Context)){
7536             Instruction *YS = BinaryOperator::CreateShl(
7537                                                      Op0BO->getOperand(1), Op1,
7538                                                      Op0BO->getName());
7539             InsertNewInstBefore(YS, I); // (Y << C)
7540             Instruction *X =
7541               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7542                                      Op0BO->getOperand(0)->getName());
7543             InsertNewInstBefore(X, I);  // (X + (Y << C))
7544             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7545             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7546                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7547           }
7548           
7549           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7550           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7551               match(Op0BO->getOperand(0),
7552                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7553                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7554               cast<BinaryOperator>(Op0BO->getOperand(0))
7555                   ->getOperand(0)->hasOneUse()) {
7556             Instruction *YS = BinaryOperator::CreateShl(
7557                                                      Op0BO->getOperand(1), Op1,
7558                                                      Op0BO->getName());
7559             InsertNewInstBefore(YS, I); // (Y << C)
7560             Instruction *XM =
7561               BinaryOperator::CreateAnd(V1, 
7562                                         Context->getConstantExprShl(CC, Op1),
7563                                         V1->getName()+".mask");
7564             InsertNewInstBefore(XM, I); // X & (CC << C)
7565             
7566             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7567           }
7568           
7569           break;
7570         }
7571       }
7572       
7573       
7574       // If the operand is an bitwise operator with a constant RHS, and the
7575       // shift is the only use, we can pull it out of the shift.
7576       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7577         bool isValid = true;     // Valid only for And, Or, Xor
7578         bool highBitSet = false; // Transform if high bit of constant set?
7579         
7580         switch (Op0BO->getOpcode()) {
7581           default: isValid = false; break;   // Do not perform transform!
7582           case Instruction::Add:
7583             isValid = isLeftShift;
7584             break;
7585           case Instruction::Or:
7586           case Instruction::Xor:
7587             highBitSet = false;
7588             break;
7589           case Instruction::And:
7590             highBitSet = true;
7591             break;
7592         }
7593         
7594         // If this is a signed shift right, and the high bit is modified
7595         // by the logical operation, do not perform the transformation.
7596         // The highBitSet boolean indicates the value of the high bit of
7597         // the constant which would cause it to be modified for this
7598         // operation.
7599         //
7600         if (isValid && I.getOpcode() == Instruction::AShr)
7601           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7602         
7603         if (isValid) {
7604           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7605           
7606           Instruction *NewShift =
7607             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7608           InsertNewInstBefore(NewShift, I);
7609           NewShift->takeName(Op0BO);
7610           
7611           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7612                                         NewRHS);
7613         }
7614       }
7615     }
7616   }
7617   
7618   // Find out if this is a shift of a shift by a constant.
7619   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7620   if (ShiftOp && !ShiftOp->isShift())
7621     ShiftOp = 0;
7622   
7623   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7624     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7625     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7626     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7627     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7628     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7629     Value *X = ShiftOp->getOperand(0);
7630     
7631     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7632     
7633     const IntegerType *Ty = cast<IntegerType>(I.getType());
7634     
7635     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7636     if (I.getOpcode() == ShiftOp->getOpcode()) {
7637       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7638       // saturates.
7639       if (AmtSum >= TypeBits) {
7640         if (I.getOpcode() != Instruction::AShr)
7641           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7642         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7643       }
7644       
7645       return BinaryOperator::Create(I.getOpcode(), X,
7646                                     Context->getConstantInt(Ty, AmtSum));
7647     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7648                I.getOpcode() == Instruction::AShr) {
7649       if (AmtSum >= TypeBits)
7650         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7651       
7652       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7653       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7654     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7655                I.getOpcode() == Instruction::LShr) {
7656       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7657       if (AmtSum >= TypeBits)
7658         AmtSum = TypeBits-1;
7659       
7660       Instruction *Shift =
7661         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7662       InsertNewInstBefore(Shift, I);
7663
7664       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7665       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7666     }
7667     
7668     // Okay, if we get here, one shift must be left, and the other shift must be
7669     // right.  See if the amounts are equal.
7670     if (ShiftAmt1 == ShiftAmt2) {
7671       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7672       if (I.getOpcode() == Instruction::Shl) {
7673         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7674         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7675       }
7676       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7677       if (I.getOpcode() == Instruction::LShr) {
7678         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7679         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7680       }
7681       // We can simplify ((X << C) >>s C) into a trunc + sext.
7682       // NOTE: we could do this for any C, but that would make 'unusual' integer
7683       // types.  For now, just stick to ones well-supported by the code
7684       // generators.
7685       const Type *SExtType = 0;
7686       switch (Ty->getBitWidth() - ShiftAmt1) {
7687       case 1  :
7688       case 8  :
7689       case 16 :
7690       case 32 :
7691       case 64 :
7692       case 128:
7693         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7694         break;
7695       default: break;
7696       }
7697       if (SExtType) {
7698         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7699         InsertNewInstBefore(NewTrunc, I);
7700         return new SExtInst(NewTrunc, Ty);
7701       }
7702       // Otherwise, we can't handle it yet.
7703     } else if (ShiftAmt1 < ShiftAmt2) {
7704       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7705       
7706       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7707       if (I.getOpcode() == Instruction::Shl) {
7708         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7709                ShiftOp->getOpcode() == Instruction::AShr);
7710         Instruction *Shift =
7711           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7712         InsertNewInstBefore(Shift, I);
7713         
7714         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7715         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7716       }
7717       
7718       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7719       if (I.getOpcode() == Instruction::LShr) {
7720         assert(ShiftOp->getOpcode() == Instruction::Shl);
7721         Instruction *Shift =
7722           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7723         InsertNewInstBefore(Shift, I);
7724         
7725         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7726         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7727       }
7728       
7729       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7730     } else {
7731       assert(ShiftAmt2 < ShiftAmt1);
7732       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7733
7734       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7735       if (I.getOpcode() == Instruction::Shl) {
7736         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7737                ShiftOp->getOpcode() == Instruction::AShr);
7738         Instruction *Shift =
7739           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7740                                  Context->getConstantInt(Ty, ShiftDiff));
7741         InsertNewInstBefore(Shift, I);
7742         
7743         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7744         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7745       }
7746       
7747       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7748       if (I.getOpcode() == Instruction::LShr) {
7749         assert(ShiftOp->getOpcode() == Instruction::Shl);
7750         Instruction *Shift =
7751           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7752         InsertNewInstBefore(Shift, I);
7753         
7754         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7755         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7756       }
7757       
7758       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7759     }
7760   }
7761   return 0;
7762 }
7763
7764
7765 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7766 /// expression.  If so, decompose it, returning some value X, such that Val is
7767 /// X*Scale+Offset.
7768 ///
7769 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7770                                         int &Offset, LLVMContext *Context) {
7771   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7772   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7773     Offset = CI->getZExtValue();
7774     Scale  = 0;
7775     return Context->getConstantInt(Type::Int32Ty, 0);
7776   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7777     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7778       if (I->getOpcode() == Instruction::Shl) {
7779         // This is a value scaled by '1 << the shift amt'.
7780         Scale = 1U << RHS->getZExtValue();
7781         Offset = 0;
7782         return I->getOperand(0);
7783       } else if (I->getOpcode() == Instruction::Mul) {
7784         // This value is scaled by 'RHS'.
7785         Scale = RHS->getZExtValue();
7786         Offset = 0;
7787         return I->getOperand(0);
7788       } else if (I->getOpcode() == Instruction::Add) {
7789         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7790         // where C1 is divisible by C2.
7791         unsigned SubScale;
7792         Value *SubVal = 
7793           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7794                                     Offset, Context);
7795         Offset += RHS->getZExtValue();
7796         Scale = SubScale;
7797         return SubVal;
7798       }
7799     }
7800   }
7801
7802   // Otherwise, we can't look past this.
7803   Scale = 1;
7804   Offset = 0;
7805   return Val;
7806 }
7807
7808
7809 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7810 /// try to eliminate the cast by moving the type information into the alloc.
7811 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7812                                                    AllocationInst &AI) {
7813   const PointerType *PTy = cast<PointerType>(CI.getType());
7814   
7815   // Remove any uses of AI that are dead.
7816   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7817   
7818   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7819     Instruction *User = cast<Instruction>(*UI++);
7820     if (isInstructionTriviallyDead(User)) {
7821       while (UI != E && *UI == User)
7822         ++UI; // If this instruction uses AI more than once, don't break UI.
7823       
7824       ++NumDeadInst;
7825       DOUT << "IC: DCE: " << *User;
7826       EraseInstFromFunction(*User);
7827     }
7828   }
7829   
7830   // Get the type really allocated and the type casted to.
7831   const Type *AllocElTy = AI.getAllocatedType();
7832   const Type *CastElTy = PTy->getElementType();
7833   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7834
7835   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7836   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7837   if (CastElTyAlign < AllocElTyAlign) return 0;
7838
7839   // If the allocation has multiple uses, only promote it if we are strictly
7840   // increasing the alignment of the resultant allocation.  If we keep it the
7841   // same, we open the door to infinite loops of various kinds.  (A reference
7842   // from a dbg.declare doesn't count as a use for this purpose.)
7843   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7844       CastElTyAlign == AllocElTyAlign) return 0;
7845
7846   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7847   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7848   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7849
7850   // See if we can satisfy the modulus by pulling a scale out of the array
7851   // size argument.
7852   unsigned ArraySizeScale;
7853   int ArrayOffset;
7854   Value *NumElements = // See if the array size is a decomposable linear expr.
7855     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7856                               ArrayOffset, Context);
7857  
7858   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7859   // do the xform.
7860   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7861       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7862
7863   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7864   Value *Amt = 0;
7865   if (Scale == 1) {
7866     Amt = NumElements;
7867   } else {
7868     // If the allocation size is constant, form a constant mul expression
7869     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7870     if (isa<ConstantInt>(NumElements))
7871       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7872                                  cast<ConstantInt>(Amt));
7873     // otherwise multiply the amount and the number of elements
7874     else {
7875       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7876       Amt = InsertNewInstBefore(Tmp, AI);
7877     }
7878   }
7879   
7880   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7881     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7882     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7883     Amt = InsertNewInstBefore(Tmp, AI);
7884   }
7885   
7886   AllocationInst *New;
7887   if (isa<MallocInst>(AI))
7888     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7889   else
7890     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7891   InsertNewInstBefore(New, AI);
7892   New->takeName(&AI);
7893   
7894   // If the allocation has one real use plus a dbg.declare, just remove the
7895   // declare.
7896   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7897     EraseInstFromFunction(*DI);
7898   }
7899   // If the allocation has multiple real uses, insert a cast and change all
7900   // things that used it to use the new cast.  This will also hack on CI, but it
7901   // will die soon.
7902   else if (!AI.hasOneUse()) {
7903     AddUsesToWorkList(AI);
7904     // New is the allocation instruction, pointer typed. AI is the original
7905     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7906     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7907     InsertNewInstBefore(NewCast, AI);
7908     AI.replaceAllUsesWith(NewCast);
7909   }
7910   return ReplaceInstUsesWith(CI, New);
7911 }
7912
7913 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7914 /// and return it as type Ty without inserting any new casts and without
7915 /// changing the computed value.  This is used by code that tries to decide
7916 /// whether promoting or shrinking integer operations to wider or smaller types
7917 /// will allow us to eliminate a truncate or extend.
7918 ///
7919 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7920 /// extension operation if Ty is larger.
7921 ///
7922 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7923 /// should return true if trunc(V) can be computed by computing V in the smaller
7924 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7925 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7926 /// efficiently truncated.
7927 ///
7928 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7929 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7930 /// the final result.
7931 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7932                                               unsigned CastOpc,
7933                                               int &NumCastsRemoved){
7934   // We can always evaluate constants in another type.
7935   if (isa<Constant>(V))
7936     return true;
7937   
7938   Instruction *I = dyn_cast<Instruction>(V);
7939   if (!I) return false;
7940   
7941   const Type *OrigTy = V->getType();
7942   
7943   // If this is an extension or truncate, we can often eliminate it.
7944   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7945     // If this is a cast from the destination type, we can trivially eliminate
7946     // it, and this will remove a cast overall.
7947     if (I->getOperand(0)->getType() == Ty) {
7948       // If the first operand is itself a cast, and is eliminable, do not count
7949       // this as an eliminable cast.  We would prefer to eliminate those two
7950       // casts first.
7951       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7952         ++NumCastsRemoved;
7953       return true;
7954     }
7955   }
7956
7957   // We can't extend or shrink something that has multiple uses: doing so would
7958   // require duplicating the instruction in general, which isn't profitable.
7959   if (!I->hasOneUse()) return false;
7960
7961   unsigned Opc = I->getOpcode();
7962   switch (Opc) {
7963   case Instruction::Add:
7964   case Instruction::Sub:
7965   case Instruction::Mul:
7966   case Instruction::And:
7967   case Instruction::Or:
7968   case Instruction::Xor:
7969     // These operators can all arbitrarily be extended or truncated.
7970     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7971                                       NumCastsRemoved) &&
7972            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7973                                       NumCastsRemoved);
7974
7975   case Instruction::Shl:
7976     // If we are truncating the result of this SHL, and if it's a shift of a
7977     // constant amount, we can always perform a SHL in a smaller type.
7978     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7979       uint32_t BitWidth = Ty->getScalarSizeInBits();
7980       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7981           CI->getLimitedValue(BitWidth) < BitWidth)
7982         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7983                                           NumCastsRemoved);
7984     }
7985     break;
7986   case Instruction::LShr:
7987     // If this is a truncate of a logical shr, we can truncate it to a smaller
7988     // lshr iff we know that the bits we would otherwise be shifting in are
7989     // already zeros.
7990     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7991       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7992       uint32_t BitWidth = Ty->getScalarSizeInBits();
7993       if (BitWidth < OrigBitWidth &&
7994           MaskedValueIsZero(I->getOperand(0),
7995             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7996           CI->getLimitedValue(BitWidth) < BitWidth) {
7997         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7998                                           NumCastsRemoved);
7999       }
8000     }
8001     break;
8002   case Instruction::ZExt:
8003   case Instruction::SExt:
8004   case Instruction::Trunc:
8005     // If this is the same kind of case as our original (e.g. zext+zext), we
8006     // can safely replace it.  Note that replacing it does not reduce the number
8007     // of casts in the input.
8008     if (Opc == CastOpc)
8009       return true;
8010
8011     // sext (zext ty1), ty2 -> zext ty2
8012     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8013       return true;
8014     break;
8015   case Instruction::Select: {
8016     SelectInst *SI = cast<SelectInst>(I);
8017     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8018                                       NumCastsRemoved) &&
8019            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8020                                       NumCastsRemoved);
8021   }
8022   case Instruction::PHI: {
8023     // We can change a phi if we can change all operands.
8024     PHINode *PN = cast<PHINode>(I);
8025     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8026       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8027                                       NumCastsRemoved))
8028         return false;
8029     return true;
8030   }
8031   default:
8032     // TODO: Can handle more cases here.
8033     break;
8034   }
8035   
8036   return false;
8037 }
8038
8039 /// EvaluateInDifferentType - Given an expression that 
8040 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8041 /// evaluate the expression.
8042 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8043                                              bool isSigned) {
8044   if (Constant *C = dyn_cast<Constant>(V))
8045     return Context->getConstantExprIntegerCast(C, Ty,
8046                                                isSigned /*Sext or ZExt*/);
8047
8048   // Otherwise, it must be an instruction.
8049   Instruction *I = cast<Instruction>(V);
8050   Instruction *Res = 0;
8051   unsigned Opc = I->getOpcode();
8052   switch (Opc) {
8053   case Instruction::Add:
8054   case Instruction::Sub:
8055   case Instruction::Mul:
8056   case Instruction::And:
8057   case Instruction::Or:
8058   case Instruction::Xor:
8059   case Instruction::AShr:
8060   case Instruction::LShr:
8061   case Instruction::Shl: {
8062     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8063     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8064     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8065     break;
8066   }    
8067   case Instruction::Trunc:
8068   case Instruction::ZExt:
8069   case Instruction::SExt:
8070     // If the source type of the cast is the type we're trying for then we can
8071     // just return the source.  There's no need to insert it because it is not
8072     // new.
8073     if (I->getOperand(0)->getType() == Ty)
8074       return I->getOperand(0);
8075     
8076     // Otherwise, must be the same type of cast, so just reinsert a new one.
8077     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8078                            Ty);
8079     break;
8080   case Instruction::Select: {
8081     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8083     Res = SelectInst::Create(I->getOperand(0), True, False);
8084     break;
8085   }
8086   case Instruction::PHI: {
8087     PHINode *OPN = cast<PHINode>(I);
8088     PHINode *NPN = PHINode::Create(Ty);
8089     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8090       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8091       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8092     }
8093     Res = NPN;
8094     break;
8095   }
8096   default: 
8097     // TODO: Can handle more cases here.
8098     LLVM_UNREACHABLE("Unreachable!");
8099     break;
8100   }
8101   
8102   Res->takeName(I);
8103   return InsertNewInstBefore(Res, *I);
8104 }
8105
8106 /// @brief Implement the transforms common to all CastInst visitors.
8107 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8108   Value *Src = CI.getOperand(0);
8109
8110   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8111   // eliminate it now.
8112   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8113     if (Instruction::CastOps opc = 
8114         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8115       // The first cast (CSrc) is eliminable so we need to fix up or replace
8116       // the second cast (CI). CSrc will then have a good chance of being dead.
8117       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8118     }
8119   }
8120
8121   // If we are casting a select then fold the cast into the select
8122   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8123     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8124       return NV;
8125
8126   // If we are casting a PHI then fold the cast into the PHI
8127   if (isa<PHINode>(Src))
8128     if (Instruction *NV = FoldOpIntoPhi(CI))
8129       return NV;
8130   
8131   return 0;
8132 }
8133
8134 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8135 /// or not there is a sequence of GEP indices into the type that will land us at
8136 /// the specified offset.  If so, fill them into NewIndices and return the
8137 /// resultant element type, otherwise return null.
8138 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8139                                        SmallVectorImpl<Value*> &NewIndices,
8140                                        const TargetData *TD,
8141                                        LLVMContext *Context) {
8142   if (!Ty->isSized()) return 0;
8143   
8144   // Start with the index over the outer type.  Note that the type size
8145   // might be zero (even if the offset isn't zero) if the indexed type
8146   // is something like [0 x {int, int}]
8147   const Type *IntPtrTy = TD->getIntPtrType();
8148   int64_t FirstIdx = 0;
8149   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8150     FirstIdx = Offset/TySize;
8151     Offset -= FirstIdx*TySize;
8152     
8153     // Handle hosts where % returns negative instead of values [0..TySize).
8154     if (Offset < 0) {
8155       --FirstIdx;
8156       Offset += TySize;
8157       assert(Offset >= 0);
8158     }
8159     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8160   }
8161   
8162   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8163     
8164   // Index into the types.  If we fail, set OrigBase to null.
8165   while (Offset) {
8166     // Indexing into tail padding between struct/array elements.
8167     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8168       return 0;
8169     
8170     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8171       const StructLayout *SL = TD->getStructLayout(STy);
8172       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8173              "Offset must stay within the indexed type");
8174       
8175       unsigned Elt = SL->getElementContainingOffset(Offset);
8176       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8177       
8178       Offset -= SL->getElementOffset(Elt);
8179       Ty = STy->getElementType(Elt);
8180     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8181       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8182       assert(EltSize && "Cannot index into a zero-sized array");
8183       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8184       Offset %= EltSize;
8185       Ty = AT->getElementType();
8186     } else {
8187       // Otherwise, we can't index into the middle of this atomic type, bail.
8188       return 0;
8189     }
8190   }
8191   
8192   return Ty;
8193 }
8194
8195 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8196 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8197   Value *Src = CI.getOperand(0);
8198   
8199   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8200     // If casting the result of a getelementptr instruction with no offset, turn
8201     // this into a cast of the original pointer!
8202     if (GEP->hasAllZeroIndices()) {
8203       // Changing the cast operand is usually not a good idea but it is safe
8204       // here because the pointer operand is being replaced with another 
8205       // pointer operand so the opcode doesn't need to change.
8206       AddToWorkList(GEP);
8207       CI.setOperand(0, GEP->getOperand(0));
8208       return &CI;
8209     }
8210     
8211     // If the GEP has a single use, and the base pointer is a bitcast, and the
8212     // GEP computes a constant offset, see if we can convert these three
8213     // instructions into fewer.  This typically happens with unions and other
8214     // non-type-safe code.
8215     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8216       if (GEP->hasAllConstantIndices()) {
8217         // We are guaranteed to get a constant from EmitGEPOffset.
8218         ConstantInt *OffsetV =
8219                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8220         int64_t Offset = OffsetV->getSExtValue();
8221         
8222         // Get the base pointer input of the bitcast, and the type it points to.
8223         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8224         const Type *GEPIdxTy =
8225           cast<PointerType>(OrigBase->getType())->getElementType();
8226         SmallVector<Value*, 8> NewIndices;
8227         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8228           // If we were able to index down into an element, create the GEP
8229           // and bitcast the result.  This eliminates one bitcast, potentially
8230           // two.
8231           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8232                                                         NewIndices.begin(),
8233                                                         NewIndices.end(), "");
8234           InsertNewInstBefore(NGEP, CI);
8235           NGEP->takeName(GEP);
8236           
8237           if (isa<BitCastInst>(CI))
8238             return new BitCastInst(NGEP, CI.getType());
8239           assert(isa<PtrToIntInst>(CI));
8240           return new PtrToIntInst(NGEP, CI.getType());
8241         }
8242       }      
8243     }
8244   }
8245     
8246   return commonCastTransforms(CI);
8247 }
8248
8249 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8250 /// type like i42.  We don't want to introduce operations on random non-legal
8251 /// integer types where they don't already exist in the code.  In the future,
8252 /// we should consider making this based off target-data, so that 32-bit targets
8253 /// won't get i64 operations etc.
8254 static bool isSafeIntegerType(const Type *Ty) {
8255   switch (Ty->getPrimitiveSizeInBits()) {
8256   case 8:
8257   case 16:
8258   case 32:
8259   case 64:
8260     return true;
8261   default: 
8262     return false;
8263   }
8264 }
8265
8266 /// commonIntCastTransforms - This function implements the common transforms
8267 /// for trunc, zext, and sext.
8268 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8269   if (Instruction *Result = commonCastTransforms(CI))
8270     return Result;
8271
8272   Value *Src = CI.getOperand(0);
8273   const Type *SrcTy = Src->getType();
8274   const Type *DestTy = CI.getType();
8275   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8276   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8277
8278   // See if we can simplify any instructions used by the LHS whose sole 
8279   // purpose is to compute bits we don't care about.
8280   if (SimplifyDemandedInstructionBits(CI))
8281     return &CI;
8282
8283   // If the source isn't an instruction or has more than one use then we
8284   // can't do anything more. 
8285   Instruction *SrcI = dyn_cast<Instruction>(Src);
8286   if (!SrcI || !Src->hasOneUse())
8287     return 0;
8288
8289   // Attempt to propagate the cast into the instruction for int->int casts.
8290   int NumCastsRemoved = 0;
8291   // Only do this if the dest type is a simple type, don't convert the
8292   // expression tree to something weird like i93 unless the source is also
8293   // strange.
8294   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8295        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8296       CanEvaluateInDifferentType(SrcI, DestTy,
8297                                  CI.getOpcode(), NumCastsRemoved)) {
8298     // If this cast is a truncate, evaluting in a different type always
8299     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8300     // we need to do an AND to maintain the clear top-part of the computation,
8301     // so we require that the input have eliminated at least one cast.  If this
8302     // is a sign extension, we insert two new casts (to do the extension) so we
8303     // require that two casts have been eliminated.
8304     bool DoXForm = false;
8305     bool JustReplace = false;
8306     switch (CI.getOpcode()) {
8307     default:
8308       // All the others use floating point so we shouldn't actually 
8309       // get here because of the check above.
8310       LLVM_UNREACHABLE("Unknown cast type");
8311     case Instruction::Trunc:
8312       DoXForm = true;
8313       break;
8314     case Instruction::ZExt: {
8315       DoXForm = NumCastsRemoved >= 1;
8316       if (!DoXForm && 0) {
8317         // If it's unnecessary to issue an AND to clear the high bits, it's
8318         // always profitable to do this xform.
8319         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8320         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8321         if (MaskedValueIsZero(TryRes, Mask))
8322           return ReplaceInstUsesWith(CI, TryRes);
8323         
8324         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8325           if (TryI->use_empty())
8326             EraseInstFromFunction(*TryI);
8327       }
8328       break;
8329     }
8330     case Instruction::SExt: {
8331       DoXForm = NumCastsRemoved >= 2;
8332       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8333         // If we do not have to emit the truncate + sext pair, then it's always
8334         // profitable to do this xform.
8335         //
8336         // It's not safe to eliminate the trunc + sext pair if one of the
8337         // eliminated cast is a truncate. e.g.
8338         // t2 = trunc i32 t1 to i16
8339         // t3 = sext i16 t2 to i32
8340         // !=
8341         // i32 t1
8342         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8343         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8344         if (NumSignBits > (DestBitSize - SrcBitSize))
8345           return ReplaceInstUsesWith(CI, TryRes);
8346         
8347         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8348           if (TryI->use_empty())
8349             EraseInstFromFunction(*TryI);
8350       }
8351       break;
8352     }
8353     }
8354     
8355     if (DoXForm) {
8356       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8357            << " cast: " << CI;
8358       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8359                                            CI.getOpcode() == Instruction::SExt);
8360       if (JustReplace)
8361         // Just replace this cast with the result.
8362         return ReplaceInstUsesWith(CI, Res);
8363
8364       assert(Res->getType() == DestTy);
8365       switch (CI.getOpcode()) {
8366       default: LLVM_UNREACHABLE("Unknown cast type!");
8367       case Instruction::Trunc:
8368         // Just replace this cast with the result.
8369         return ReplaceInstUsesWith(CI, Res);
8370       case Instruction::ZExt: {
8371         assert(SrcBitSize < DestBitSize && "Not a zext?");
8372
8373         // If the high bits are already zero, just replace this cast with the
8374         // result.
8375         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8376         if (MaskedValueIsZero(Res, Mask))
8377           return ReplaceInstUsesWith(CI, Res);
8378
8379         // We need to emit an AND to clear the high bits.
8380         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8381                                                             SrcBitSize));
8382         return BinaryOperator::CreateAnd(Res, C);
8383       }
8384       case Instruction::SExt: {
8385         // If the high bits are already filled with sign bit, just replace this
8386         // cast with the result.
8387         unsigned NumSignBits = ComputeNumSignBits(Res);
8388         if (NumSignBits > (DestBitSize - SrcBitSize))
8389           return ReplaceInstUsesWith(CI, Res);
8390
8391         // We need to emit a cast to truncate, then a cast to sext.
8392         return CastInst::Create(Instruction::SExt,
8393             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8394                              CI), DestTy);
8395       }
8396       }
8397     }
8398   }
8399   
8400   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8401   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8402
8403   switch (SrcI->getOpcode()) {
8404   case Instruction::Add:
8405   case Instruction::Mul:
8406   case Instruction::And:
8407   case Instruction::Or:
8408   case Instruction::Xor:
8409     // If we are discarding information, rewrite.
8410     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8411       // Don't insert two casts unless at least one can be eliminated.
8412       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8413           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8414         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8415         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8416         return BinaryOperator::Create(
8417             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8418       }
8419     }
8420
8421     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8422     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8423         SrcI->getOpcode() == Instruction::Xor &&
8424         Op1 == Context->getConstantIntTrue() &&
8425         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8426       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8427       return BinaryOperator::CreateXor(New,
8428                                       Context->getConstantInt(CI.getType(), 1));
8429     }
8430     break;
8431
8432   case Instruction::Shl: {
8433     // Canonicalize trunc inside shl, if we can.
8434     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8435     if (CI && DestBitSize < SrcBitSize &&
8436         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8437       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8438       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8439       return BinaryOperator::CreateShl(Op0c, Op1c);
8440     }
8441     break;
8442   }
8443   }
8444   return 0;
8445 }
8446
8447 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8448   if (Instruction *Result = commonIntCastTransforms(CI))
8449     return Result;
8450   
8451   Value *Src = CI.getOperand(0);
8452   const Type *Ty = CI.getType();
8453   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8454   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8455
8456   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8457   if (DestBitWidth == 1 &&
8458       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8459     Constant *One = Context->getConstantInt(Src->getType(), 1);
8460     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8461     Value *Zero = Context->getNullValue(Src->getType());
8462     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8463   }
8464
8465   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8466   ConstantInt *ShAmtV = 0;
8467   Value *ShiftOp = 0;
8468   if (Src->hasOneUse() &&
8469       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8470     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8471     
8472     // Get a mask for the bits shifting in.
8473     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8474     if (MaskedValueIsZero(ShiftOp, Mask)) {
8475       if (ShAmt >= DestBitWidth)        // All zeros.
8476         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8477       
8478       // Okay, we can shrink this.  Truncate the input, then return a new
8479       // shift.
8480       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8481       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8482       return BinaryOperator::CreateLShr(V1, V2);
8483     }
8484   }
8485   
8486   return 0;
8487 }
8488
8489 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8490 /// in order to eliminate the icmp.
8491 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8492                                              bool DoXform) {
8493   // If we are just checking for a icmp eq of a single bit and zext'ing it
8494   // to an integer, then shift the bit to the appropriate place and then
8495   // cast to integer to avoid the comparison.
8496   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8497     const APInt &Op1CV = Op1C->getValue();
8498       
8499     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8500     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8501     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8502         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8503       if (!DoXform) return ICI;
8504
8505       Value *In = ICI->getOperand(0);
8506       Value *Sh = Context->getConstantInt(In->getType(),
8507                                    In->getType()->getScalarSizeInBits()-1);
8508       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8509                                                         In->getName()+".lobit"),
8510                                CI);
8511       if (In->getType() != CI.getType())
8512         In = CastInst::CreateIntegerCast(In, CI.getType(),
8513                                          false/*ZExt*/, "tmp", &CI);
8514
8515       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8516         Constant *One = Context->getConstantInt(In->getType(), 1);
8517         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8518                                                          In->getName()+".not"),
8519                                  CI);
8520       }
8521
8522       return ReplaceInstUsesWith(CI, In);
8523     }
8524       
8525       
8526       
8527     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8528     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8529     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8530     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8531     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8532     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8533     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8534     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8535     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8536         // This only works for EQ and NE
8537         ICI->isEquality()) {
8538       // If Op1C some other power of two, convert:
8539       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8540       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8541       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8542       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8543         
8544       APInt KnownZeroMask(~KnownZero);
8545       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8546         if (!DoXform) return ICI;
8547
8548         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8549         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8550           // (X&4) == 2 --> false
8551           // (X&4) != 2 --> true
8552           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8553           Res = Context->getConstantExprZExt(Res, CI.getType());
8554           return ReplaceInstUsesWith(CI, Res);
8555         }
8556           
8557         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8558         Value *In = ICI->getOperand(0);
8559         if (ShiftAmt) {
8560           // Perform a logical shr by shiftamt.
8561           // Insert the shift to put the result in the low bit.
8562           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8563                               Context->getConstantInt(In->getType(), ShiftAmt),
8564                                                    In->getName()+".lobit"), CI);
8565         }
8566           
8567         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8568           Constant *One = Context->getConstantInt(In->getType(), 1);
8569           In = BinaryOperator::CreateXor(In, One, "tmp");
8570           InsertNewInstBefore(cast<Instruction>(In), CI);
8571         }
8572           
8573         if (CI.getType() == In->getType())
8574           return ReplaceInstUsesWith(CI, In);
8575         else
8576           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8577       }
8578     }
8579   }
8580
8581   return 0;
8582 }
8583
8584 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8585   // If one of the common conversion will work ..
8586   if (Instruction *Result = commonIntCastTransforms(CI))
8587     return Result;
8588
8589   Value *Src = CI.getOperand(0);
8590
8591   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8592   // types and if the sizes are just right we can convert this into a logical
8593   // 'and' which will be much cheaper than the pair of casts.
8594   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8595     // Get the sizes of the types involved.  We know that the intermediate type
8596     // will be smaller than A or C, but don't know the relation between A and C.
8597     Value *A = CSrc->getOperand(0);
8598     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8599     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8600     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8601     // If we're actually extending zero bits, then if
8602     // SrcSize <  DstSize: zext(a & mask)
8603     // SrcSize == DstSize: a & mask
8604     // SrcSize  > DstSize: trunc(a) & mask
8605     if (SrcSize < DstSize) {
8606       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8607       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8608       Instruction *And =
8609         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8610       InsertNewInstBefore(And, CI);
8611       return new ZExtInst(And, CI.getType());
8612     } else if (SrcSize == DstSize) {
8613       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8614       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8615                                                            AndValue));
8616     } else if (SrcSize > DstSize) {
8617       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8618       InsertNewInstBefore(Trunc, CI);
8619       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8620       return BinaryOperator::CreateAnd(Trunc, 
8621                                        Context->getConstantInt(Trunc->getType(),
8622                                                                AndValue));
8623     }
8624   }
8625
8626   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8627     return transformZExtICmp(ICI, CI);
8628
8629   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8630   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8631     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8632     // of the (zext icmp) will be transformed.
8633     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8634     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8635     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8636         (transformZExtICmp(LHS, CI, false) ||
8637          transformZExtICmp(RHS, CI, false))) {
8638       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8639       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8640       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8641     }
8642   }
8643
8644   // zext(trunc(t) & C) -> (t & zext(C)).
8645   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8646     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8647       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8648         Value *TI0 = TI->getOperand(0);
8649         if (TI0->getType() == CI.getType())
8650           return
8651             BinaryOperator::CreateAnd(TI0,
8652                                 Context->getConstantExprZExt(C, CI.getType()));
8653       }
8654
8655   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8656   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8657     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8658       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8659         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8660             And->getOperand(1) == C)
8661           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8662             Value *TI0 = TI->getOperand(0);
8663             if (TI0->getType() == CI.getType()) {
8664               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8665               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8666               InsertNewInstBefore(NewAnd, *And);
8667               return BinaryOperator::CreateXor(NewAnd, ZC);
8668             }
8669           }
8670
8671   return 0;
8672 }
8673
8674 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8675   if (Instruction *I = commonIntCastTransforms(CI))
8676     return I;
8677   
8678   Value *Src = CI.getOperand(0);
8679   
8680   // Canonicalize sign-extend from i1 to a select.
8681   if (Src->getType() == Type::Int1Ty)
8682     return SelectInst::Create(Src,
8683                               Context->getAllOnesValue(CI.getType()),
8684                               Context->getNullValue(CI.getType()));
8685
8686   // See if the value being truncated is already sign extended.  If so, just
8687   // eliminate the trunc/sext pair.
8688   if (getOpcode(Src) == Instruction::Trunc) {
8689     Value *Op = cast<User>(Src)->getOperand(0);
8690     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8691     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8692     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8693     unsigned NumSignBits = ComputeNumSignBits(Op);
8694
8695     if (OpBits == DestBits) {
8696       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8697       // bits, it is already ready.
8698       if (NumSignBits > DestBits-MidBits)
8699         return ReplaceInstUsesWith(CI, Op);
8700     } else if (OpBits < DestBits) {
8701       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8702       // bits, just sext from i32.
8703       if (NumSignBits > OpBits-MidBits)
8704         return new SExtInst(Op, CI.getType(), "tmp");
8705     } else {
8706       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8707       // bits, just truncate to i32.
8708       if (NumSignBits > OpBits-MidBits)
8709         return new TruncInst(Op, CI.getType(), "tmp");
8710     }
8711   }
8712
8713   // If the input is a shl/ashr pair of a same constant, then this is a sign
8714   // extension from a smaller value.  If we could trust arbitrary bitwidth
8715   // integers, we could turn this into a truncate to the smaller bit and then
8716   // use a sext for the whole extension.  Since we don't, look deeper and check
8717   // for a truncate.  If the source and dest are the same type, eliminate the
8718   // trunc and extend and just do shifts.  For example, turn:
8719   //   %a = trunc i32 %i to i8
8720   //   %b = shl i8 %a, 6
8721   //   %c = ashr i8 %b, 6
8722   //   %d = sext i8 %c to i32
8723   // into:
8724   //   %a = shl i32 %i, 30
8725   //   %d = ashr i32 %a, 30
8726   Value *A = 0;
8727   ConstantInt *BA = 0, *CA = 0;
8728   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8729                         m_ConstantInt(CA)), *Context) &&
8730       BA == CA && isa<TruncInst>(A)) {
8731     Value *I = cast<TruncInst>(A)->getOperand(0);
8732     if (I->getType() == CI.getType()) {
8733       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8734       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8735       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8736       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8737       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8738                                                         CI.getName()), CI);
8739       return BinaryOperator::CreateAShr(I, ShAmtV);
8740     }
8741   }
8742   
8743   return 0;
8744 }
8745
8746 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8747 /// in the specified FP type without changing its value.
8748 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8749                               LLVMContext *Context) {
8750   bool losesInfo;
8751   APFloat F = CFP->getValueAPF();
8752   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8753   if (!losesInfo)
8754     return Context->getConstantFP(F);
8755   return 0;
8756 }
8757
8758 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8759 /// through it until we get the source value.
8760 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8761   if (Instruction *I = dyn_cast<Instruction>(V))
8762     if (I->getOpcode() == Instruction::FPExt)
8763       return LookThroughFPExtensions(I->getOperand(0), Context);
8764   
8765   // If this value is a constant, return the constant in the smallest FP type
8766   // that can accurately represent it.  This allows us to turn
8767   // (float)((double)X+2.0) into x+2.0f.
8768   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8769     if (CFP->getType() == Type::PPC_FP128Ty)
8770       return V;  // No constant folding of this.
8771     // See if the value can be truncated to float and then reextended.
8772     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8773       return V;
8774     if (CFP->getType() == Type::DoubleTy)
8775       return V;  // Won't shrink.
8776     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8777       return V;
8778     // Don't try to shrink to various long double types.
8779   }
8780   
8781   return V;
8782 }
8783
8784 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8785   if (Instruction *I = commonCastTransforms(CI))
8786     return I;
8787   
8788   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8789   // smaller than the destination type, we can eliminate the truncate by doing
8790   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8791   // many builtins (sqrt, etc).
8792   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8793   if (OpI && OpI->hasOneUse()) {
8794     switch (OpI->getOpcode()) {
8795     default: break;
8796     case Instruction::FAdd:
8797     case Instruction::FSub:
8798     case Instruction::FMul:
8799     case Instruction::FDiv:
8800     case Instruction::FRem:
8801       const Type *SrcTy = OpI->getType();
8802       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8803       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8804       if (LHSTrunc->getType() != SrcTy && 
8805           RHSTrunc->getType() != SrcTy) {
8806         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8807         // If the source types were both smaller than the destination type of
8808         // the cast, do this xform.
8809         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8810             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8811           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8812                                       CI.getType(), CI);
8813           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8814                                       CI.getType(), CI);
8815           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8816         }
8817       }
8818       break;  
8819     }
8820   }
8821   return 0;
8822 }
8823
8824 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8825   return commonCastTransforms(CI);
8826 }
8827
8828 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8829   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8830   if (OpI == 0)
8831     return commonCastTransforms(FI);
8832
8833   // fptoui(uitofp(X)) --> X
8834   // fptoui(sitofp(X)) --> X
8835   // This is safe if the intermediate type has enough bits in its mantissa to
8836   // accurately represent all values of X.  For example, do not do this with
8837   // i64->float->i64.  This is also safe for sitofp case, because any negative
8838   // 'X' value would cause an undefined result for the fptoui. 
8839   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8840       OpI->getOperand(0)->getType() == FI.getType() &&
8841       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8842                     OpI->getType()->getFPMantissaWidth())
8843     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8844
8845   return commonCastTransforms(FI);
8846 }
8847
8848 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8849   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8850   if (OpI == 0)
8851     return commonCastTransforms(FI);
8852   
8853   // fptosi(sitofp(X)) --> X
8854   // fptosi(uitofp(X)) --> X
8855   // This is safe if the intermediate type has enough bits in its mantissa to
8856   // accurately represent all values of X.  For example, do not do this with
8857   // i64->float->i64.  This is also safe for sitofp case, because any negative
8858   // 'X' value would cause an undefined result for the fptoui. 
8859   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8860       OpI->getOperand(0)->getType() == FI.getType() &&
8861       (int)FI.getType()->getScalarSizeInBits() <=
8862                     OpI->getType()->getFPMantissaWidth())
8863     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8864   
8865   return commonCastTransforms(FI);
8866 }
8867
8868 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8869   return commonCastTransforms(CI);
8870 }
8871
8872 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8873   return commonCastTransforms(CI);
8874 }
8875
8876 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8877   // If the destination integer type is smaller than the intptr_t type for
8878   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8879   // trunc to be exposed to other transforms.  Don't do this for extending
8880   // ptrtoint's, because we don't know if the target sign or zero extends its
8881   // pointers.
8882   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8883     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8884                                                     TD->getIntPtrType(),
8885                                                     "tmp"), CI);
8886     return new TruncInst(P, CI.getType());
8887   }
8888   
8889   return commonPointerCastTransforms(CI);
8890 }
8891
8892 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8893   // If the source integer type is larger than the intptr_t type for
8894   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8895   // allows the trunc to be exposed to other transforms.  Don't do this for
8896   // extending inttoptr's, because we don't know if the target sign or zero
8897   // extends to pointers.
8898   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8899       TD->getPointerSizeInBits()) {
8900     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8901                                                  TD->getIntPtrType(),
8902                                                  "tmp"), CI);
8903     return new IntToPtrInst(P, CI.getType());
8904   }
8905   
8906   if (Instruction *I = commonCastTransforms(CI))
8907     return I;
8908   
8909   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8910   if (!DestPointee->isSized()) return 0;
8911
8912   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8913   ConstantInt *Cst;
8914   Value *X;
8915   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8916                                     m_ConstantInt(Cst)), *Context)) {
8917     // If the source and destination operands have the same type, see if this
8918     // is a single-index GEP.
8919     if (X->getType() == CI.getType()) {
8920       // Get the size of the pointee type.
8921       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8922
8923       // Convert the constant to intptr type.
8924       APInt Offset = Cst->getValue();
8925       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8926
8927       // If Offset is evenly divisible by Size, we can do this xform.
8928       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8929         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8930         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8931       }
8932     }
8933     // TODO: Could handle other cases, e.g. where add is indexing into field of
8934     // struct etc.
8935   } else if (CI.getOperand(0)->hasOneUse() &&
8936              match(CI.getOperand(0), m_Add(m_Value(X),
8937                    m_ConstantInt(Cst)), *Context)) {
8938     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8939     // "inttoptr+GEP" instead of "add+intptr".
8940     
8941     // Get the size of the pointee type.
8942     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8943     
8944     // Convert the constant to intptr type.
8945     APInt Offset = Cst->getValue();
8946     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8947     
8948     // If Offset is evenly divisible by Size, we can do this xform.
8949     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8950       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8951       
8952       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8953                                                             "tmp"), CI);
8954       return GetElementPtrInst::Create(P,
8955                                        Context->getConstantInt(Offset), "tmp");
8956     }
8957   }
8958   return 0;
8959 }
8960
8961 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8962   // If the operands are integer typed then apply the integer transforms,
8963   // otherwise just apply the common ones.
8964   Value *Src = CI.getOperand(0);
8965   const Type *SrcTy = Src->getType();
8966   const Type *DestTy = CI.getType();
8967
8968   if (isa<PointerType>(SrcTy)) {
8969     if (Instruction *I = commonPointerCastTransforms(CI))
8970       return I;
8971   } else {
8972     if (Instruction *Result = commonCastTransforms(CI))
8973       return Result;
8974   }
8975
8976
8977   // Get rid of casts from one type to the same type. These are useless and can
8978   // be replaced by the operand.
8979   if (DestTy == Src->getType())
8980     return ReplaceInstUsesWith(CI, Src);
8981
8982   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8983     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8984     const Type *DstElTy = DstPTy->getElementType();
8985     const Type *SrcElTy = SrcPTy->getElementType();
8986     
8987     // If the address spaces don't match, don't eliminate the bitcast, which is
8988     // required for changing types.
8989     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8990       return 0;
8991     
8992     // If we are casting a malloc or alloca to a pointer to a type of the same
8993     // size, rewrite the allocation instruction to allocate the "right" type.
8994     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8995       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8996         return V;
8997     
8998     // If the source and destination are pointers, and this cast is equivalent
8999     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9000     // This can enhance SROA and other transforms that want type-safe pointers.
9001     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9002     unsigned NumZeros = 0;
9003     while (SrcElTy != DstElTy && 
9004            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9005            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9006       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9007       ++NumZeros;
9008     }
9009
9010     // If we found a path from the src to dest, create the getelementptr now.
9011     if (SrcElTy == DstElTy) {
9012       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9013       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9014                                        ((Instruction*) NULL));
9015     }
9016   }
9017
9018   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9019     if (SVI->hasOneUse()) {
9020       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9021       // a bitconvert to a vector with the same # elts.
9022       if (isa<VectorType>(DestTy) && 
9023           cast<VectorType>(DestTy)->getNumElements() ==
9024                 SVI->getType()->getNumElements() &&
9025           SVI->getType()->getNumElements() ==
9026             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9027         CastInst *Tmp;
9028         // If either of the operands is a cast from CI.getType(), then
9029         // evaluating the shuffle in the casted destination's type will allow
9030         // us to eliminate at least one cast.
9031         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9032              Tmp->getOperand(0)->getType() == DestTy) ||
9033             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9034              Tmp->getOperand(0)->getType() == DestTy)) {
9035           Value *LHS = InsertCastBefore(Instruction::BitCast,
9036                                         SVI->getOperand(0), DestTy, CI);
9037           Value *RHS = InsertCastBefore(Instruction::BitCast,
9038                                         SVI->getOperand(1), DestTy, CI);
9039           // Return a new shuffle vector.  Use the same element ID's, as we
9040           // know the vector types match #elts.
9041           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9042         }
9043       }
9044     }
9045   }
9046   return 0;
9047 }
9048
9049 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9050 ///   %C = or %A, %B
9051 ///   %D = select %cond, %C, %A
9052 /// into:
9053 ///   %C = select %cond, %B, 0
9054 ///   %D = or %A, %C
9055 ///
9056 /// Assuming that the specified instruction is an operand to the select, return
9057 /// a bitmask indicating which operands of this instruction are foldable if they
9058 /// equal the other incoming value of the select.
9059 ///
9060 static unsigned GetSelectFoldableOperands(Instruction *I) {
9061   switch (I->getOpcode()) {
9062   case Instruction::Add:
9063   case Instruction::Mul:
9064   case Instruction::And:
9065   case Instruction::Or:
9066   case Instruction::Xor:
9067     return 3;              // Can fold through either operand.
9068   case Instruction::Sub:   // Can only fold on the amount subtracted.
9069   case Instruction::Shl:   // Can only fold on the shift amount.
9070   case Instruction::LShr:
9071   case Instruction::AShr:
9072     return 1;
9073   default:
9074     return 0;              // Cannot fold
9075   }
9076 }
9077
9078 /// GetSelectFoldableConstant - For the same transformation as the previous
9079 /// function, return the identity constant that goes into the select.
9080 static Constant *GetSelectFoldableConstant(Instruction *I,
9081                                            LLVMContext *Context) {
9082   switch (I->getOpcode()) {
9083   default: LLVM_UNREACHABLE("This cannot happen!");
9084   case Instruction::Add:
9085   case Instruction::Sub:
9086   case Instruction::Or:
9087   case Instruction::Xor:
9088   case Instruction::Shl:
9089   case Instruction::LShr:
9090   case Instruction::AShr:
9091     return Context->getNullValue(I->getType());
9092   case Instruction::And:
9093     return Context->getAllOnesValue(I->getType());
9094   case Instruction::Mul:
9095     return Context->getConstantInt(I->getType(), 1);
9096   }
9097 }
9098
9099 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9100 /// have the same opcode and only one use each.  Try to simplify this.
9101 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9102                                           Instruction *FI) {
9103   if (TI->getNumOperands() == 1) {
9104     // If this is a non-volatile load or a cast from the same type,
9105     // merge.
9106     if (TI->isCast()) {
9107       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9108         return 0;
9109     } else {
9110       return 0;  // unknown unary op.
9111     }
9112
9113     // Fold this by inserting a select from the input values.
9114     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9115                                            FI->getOperand(0), SI.getName()+".v");
9116     InsertNewInstBefore(NewSI, SI);
9117     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9118                             TI->getType());
9119   }
9120
9121   // Only handle binary operators here.
9122   if (!isa<BinaryOperator>(TI))
9123     return 0;
9124
9125   // Figure out if the operations have any operands in common.
9126   Value *MatchOp, *OtherOpT, *OtherOpF;
9127   bool MatchIsOpZero;
9128   if (TI->getOperand(0) == FI->getOperand(0)) {
9129     MatchOp  = TI->getOperand(0);
9130     OtherOpT = TI->getOperand(1);
9131     OtherOpF = FI->getOperand(1);
9132     MatchIsOpZero = true;
9133   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9134     MatchOp  = TI->getOperand(1);
9135     OtherOpT = TI->getOperand(0);
9136     OtherOpF = FI->getOperand(0);
9137     MatchIsOpZero = false;
9138   } else if (!TI->isCommutative()) {
9139     return 0;
9140   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9141     MatchOp  = TI->getOperand(0);
9142     OtherOpT = TI->getOperand(1);
9143     OtherOpF = FI->getOperand(0);
9144     MatchIsOpZero = true;
9145   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9146     MatchOp  = TI->getOperand(1);
9147     OtherOpT = TI->getOperand(0);
9148     OtherOpF = FI->getOperand(1);
9149     MatchIsOpZero = true;
9150   } else {
9151     return 0;
9152   }
9153
9154   // If we reach here, they do have operations in common.
9155   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9156                                          OtherOpF, SI.getName()+".v");
9157   InsertNewInstBefore(NewSI, SI);
9158
9159   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9160     if (MatchIsOpZero)
9161       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9162     else
9163       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9164   }
9165   LLVM_UNREACHABLE("Shouldn't get here");
9166   return 0;
9167 }
9168
9169 static bool isSelect01(Constant *C1, Constant *C2) {
9170   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9171   if (!C1I)
9172     return false;
9173   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9174   if (!C2I)
9175     return false;
9176   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9177 }
9178
9179 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9180 /// facilitate further optimization.
9181 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9182                                             Value *FalseVal) {
9183   // See the comment above GetSelectFoldableOperands for a description of the
9184   // transformation we are doing here.
9185   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9186     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9187         !isa<Constant>(FalseVal)) {
9188       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9189         unsigned OpToFold = 0;
9190         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9191           OpToFold = 1;
9192         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9193           OpToFold = 2;
9194         }
9195
9196         if (OpToFold) {
9197           Constant *C = GetSelectFoldableConstant(TVI, Context);
9198           Value *OOp = TVI->getOperand(2-OpToFold);
9199           // Avoid creating select between 2 constants unless it's selecting
9200           // between 0 and 1.
9201           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9202             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9203             InsertNewInstBefore(NewSel, SI);
9204             NewSel->takeName(TVI);
9205             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9206               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9207             LLVM_UNREACHABLE("Unknown instruction!!");
9208           }
9209         }
9210       }
9211     }
9212   }
9213
9214   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9215     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9216         !isa<Constant>(TrueVal)) {
9217       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9218         unsigned OpToFold = 0;
9219         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9220           OpToFold = 1;
9221         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9222           OpToFold = 2;
9223         }
9224
9225         if (OpToFold) {
9226           Constant *C = GetSelectFoldableConstant(FVI, Context);
9227           Value *OOp = FVI->getOperand(2-OpToFold);
9228           // Avoid creating select between 2 constants unless it's selecting
9229           // between 0 and 1.
9230           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9231             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9232             InsertNewInstBefore(NewSel, SI);
9233             NewSel->takeName(FVI);
9234             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9235               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9236             LLVM_UNREACHABLE("Unknown instruction!!");
9237           }
9238         }
9239       }
9240     }
9241   }
9242
9243   return 0;
9244 }
9245
9246 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9247 /// ICmpInst as its first operand.
9248 ///
9249 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9250                                                    ICmpInst *ICI) {
9251   bool Changed = false;
9252   ICmpInst::Predicate Pred = ICI->getPredicate();
9253   Value *CmpLHS = ICI->getOperand(0);
9254   Value *CmpRHS = ICI->getOperand(1);
9255   Value *TrueVal = SI.getTrueValue();
9256   Value *FalseVal = SI.getFalseValue();
9257
9258   // Check cases where the comparison is with a constant that
9259   // can be adjusted to fit the min/max idiom. We may edit ICI in
9260   // place here, so make sure the select is the only user.
9261   if (ICI->hasOneUse())
9262     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9263       switch (Pred) {
9264       default: break;
9265       case ICmpInst::ICMP_ULT:
9266       case ICmpInst::ICMP_SLT: {
9267         // X < MIN ? T : F  -->  F
9268         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9269           return ReplaceInstUsesWith(SI, FalseVal);
9270         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9271         Constant *AdjustedRHS = SubOne(CI, Context);
9272         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9273             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9274           Pred = ICmpInst::getSwappedPredicate(Pred);
9275           CmpRHS = AdjustedRHS;
9276           std::swap(FalseVal, TrueVal);
9277           ICI->setPredicate(Pred);
9278           ICI->setOperand(1, CmpRHS);
9279           SI.setOperand(1, TrueVal);
9280           SI.setOperand(2, FalseVal);
9281           Changed = true;
9282         }
9283         break;
9284       }
9285       case ICmpInst::ICMP_UGT:
9286       case ICmpInst::ICMP_SGT: {
9287         // X > MAX ? T : F  -->  F
9288         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9289           return ReplaceInstUsesWith(SI, FalseVal);
9290         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9291         Constant *AdjustedRHS = AddOne(CI, Context);
9292         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9293             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9294           Pred = ICmpInst::getSwappedPredicate(Pred);
9295           CmpRHS = AdjustedRHS;
9296           std::swap(FalseVal, TrueVal);
9297           ICI->setPredicate(Pred);
9298           ICI->setOperand(1, CmpRHS);
9299           SI.setOperand(1, TrueVal);
9300           SI.setOperand(2, FalseVal);
9301           Changed = true;
9302         }
9303         break;
9304       }
9305       }
9306
9307       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9308       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9309       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9310       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9311           match(FalseVal, m_ConstantInt<0>(), *Context))
9312         Pred = ICI->getPredicate();
9313       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9314                match(FalseVal, m_ConstantInt<-1>(), *Context))
9315         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9316       
9317       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9318         // If we are just checking for a icmp eq of a single bit and zext'ing it
9319         // to an integer, then shift the bit to the appropriate place and then
9320         // cast to integer to avoid the comparison.
9321         const APInt &Op1CV = CI->getValue();
9322     
9323         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9324         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9325         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9326             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9327           Value *In = ICI->getOperand(0);
9328           Value *Sh = Context->getConstantInt(In->getType(),
9329                                        In->getType()->getScalarSizeInBits()-1);
9330           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9331                                                           In->getName()+".lobit"),
9332                                    *ICI);
9333           if (In->getType() != SI.getType())
9334             In = CastInst::CreateIntegerCast(In, SI.getType(),
9335                                              true/*SExt*/, "tmp", ICI);
9336     
9337           if (Pred == ICmpInst::ICMP_SGT)
9338             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9339                                        In->getName()+".not"), *ICI);
9340     
9341           return ReplaceInstUsesWith(SI, In);
9342         }
9343       }
9344     }
9345
9346   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9347     // Transform (X == Y) ? X : Y  -> Y
9348     if (Pred == ICmpInst::ICMP_EQ)
9349       return ReplaceInstUsesWith(SI, FalseVal);
9350     // Transform (X != Y) ? X : Y  -> X
9351     if (Pred == ICmpInst::ICMP_NE)
9352       return ReplaceInstUsesWith(SI, TrueVal);
9353     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9354
9355   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9356     // Transform (X == Y) ? Y : X  -> X
9357     if (Pred == ICmpInst::ICMP_EQ)
9358       return ReplaceInstUsesWith(SI, FalseVal);
9359     // Transform (X != Y) ? Y : X  -> Y
9360     if (Pred == ICmpInst::ICMP_NE)
9361       return ReplaceInstUsesWith(SI, TrueVal);
9362     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9363   }
9364
9365   /// NOTE: if we wanted to, this is where to detect integer ABS
9366
9367   return Changed ? &SI : 0;
9368 }
9369
9370 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9371   Value *CondVal = SI.getCondition();
9372   Value *TrueVal = SI.getTrueValue();
9373   Value *FalseVal = SI.getFalseValue();
9374
9375   // select true, X, Y  -> X
9376   // select false, X, Y -> Y
9377   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9378     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9379
9380   // select C, X, X -> X
9381   if (TrueVal == FalseVal)
9382     return ReplaceInstUsesWith(SI, TrueVal);
9383
9384   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9385     return ReplaceInstUsesWith(SI, FalseVal);
9386   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9387     return ReplaceInstUsesWith(SI, TrueVal);
9388   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9389     if (isa<Constant>(TrueVal))
9390       return ReplaceInstUsesWith(SI, TrueVal);
9391     else
9392       return ReplaceInstUsesWith(SI, FalseVal);
9393   }
9394
9395   if (SI.getType() == Type::Int1Ty) {
9396     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9397       if (C->getZExtValue()) {
9398         // Change: A = select B, true, C --> A = or B, C
9399         return BinaryOperator::CreateOr(CondVal, FalseVal);
9400       } else {
9401         // Change: A = select B, false, C --> A = and !B, C
9402         Value *NotCond =
9403           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9404                                              "not."+CondVal->getName()), SI);
9405         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9406       }
9407     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9408       if (C->getZExtValue() == false) {
9409         // Change: A = select B, C, false --> A = and B, C
9410         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9411       } else {
9412         // Change: A = select B, C, true --> A = or !B, C
9413         Value *NotCond =
9414           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9415                                              "not."+CondVal->getName()), SI);
9416         return BinaryOperator::CreateOr(NotCond, TrueVal);
9417       }
9418     }
9419     
9420     // select a, b, a  -> a&b
9421     // select a, a, b  -> a|b
9422     if (CondVal == TrueVal)
9423       return BinaryOperator::CreateOr(CondVal, FalseVal);
9424     else if (CondVal == FalseVal)
9425       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9426   }
9427
9428   // Selecting between two integer constants?
9429   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9430     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9431       // select C, 1, 0 -> zext C to int
9432       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9433         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9434       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9435         // select C, 0, 1 -> zext !C to int
9436         Value *NotCond =
9437           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9438                                                "not."+CondVal->getName()), SI);
9439         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9440       }
9441
9442       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9443         // If one of the constants is zero (we know they can't both be) and we
9444         // have an icmp instruction with zero, and we have an 'and' with the
9445         // non-constant value, eliminate this whole mess.  This corresponds to
9446         // cases like this: ((X & 27) ? 27 : 0)
9447         if (TrueValC->isZero() || FalseValC->isZero())
9448           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9449               cast<Constant>(IC->getOperand(1))->isNullValue())
9450             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9451               if (ICA->getOpcode() == Instruction::And &&
9452                   isa<ConstantInt>(ICA->getOperand(1)) &&
9453                   (ICA->getOperand(1) == TrueValC ||
9454                    ICA->getOperand(1) == FalseValC) &&
9455                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9456                 // Okay, now we know that everything is set up, we just don't
9457                 // know whether we have a icmp_ne or icmp_eq and whether the 
9458                 // true or false val is the zero.
9459                 bool ShouldNotVal = !TrueValC->isZero();
9460                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9461                 Value *V = ICA;
9462                 if (ShouldNotVal)
9463                   V = InsertNewInstBefore(BinaryOperator::Create(
9464                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9465                 return ReplaceInstUsesWith(SI, V);
9466               }
9467       }
9468     }
9469
9470   // See if we are selecting two values based on a comparison of the two values.
9471   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9472     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9473       // Transform (X == Y) ? X : Y  -> Y
9474       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9475         // This is not safe in general for floating point:  
9476         // consider X== -0, Y== +0.
9477         // It becomes safe if either operand is a nonzero constant.
9478         ConstantFP *CFPt, *CFPf;
9479         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9480               !CFPt->getValueAPF().isZero()) ||
9481             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9482              !CFPf->getValueAPF().isZero()))
9483         return ReplaceInstUsesWith(SI, FalseVal);
9484       }
9485       // Transform (X != Y) ? X : Y  -> X
9486       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9487         return ReplaceInstUsesWith(SI, TrueVal);
9488       // NOTE: if we wanted to, this is where to detect MIN/MAX
9489
9490     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9491       // Transform (X == Y) ? Y : X  -> X
9492       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9493         // This is not safe in general for floating point:  
9494         // consider X== -0, Y== +0.
9495         // It becomes safe if either operand is a nonzero constant.
9496         ConstantFP *CFPt, *CFPf;
9497         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9498               !CFPt->getValueAPF().isZero()) ||
9499             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9500              !CFPf->getValueAPF().isZero()))
9501           return ReplaceInstUsesWith(SI, FalseVal);
9502       }
9503       // Transform (X != Y) ? Y : X  -> Y
9504       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9505         return ReplaceInstUsesWith(SI, TrueVal);
9506       // NOTE: if we wanted to, this is where to detect MIN/MAX
9507     }
9508     // NOTE: if we wanted to, this is where to detect ABS
9509   }
9510
9511   // See if we are selecting two values based on a comparison of the two values.
9512   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9513     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9514       return Result;
9515
9516   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9517     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9518       if (TI->hasOneUse() && FI->hasOneUse()) {
9519         Instruction *AddOp = 0, *SubOp = 0;
9520
9521         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9522         if (TI->getOpcode() == FI->getOpcode())
9523           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9524             return IV;
9525
9526         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9527         // even legal for FP.
9528         if ((TI->getOpcode() == Instruction::Sub &&
9529              FI->getOpcode() == Instruction::Add) ||
9530             (TI->getOpcode() == Instruction::FSub &&
9531              FI->getOpcode() == Instruction::FAdd)) {
9532           AddOp = FI; SubOp = TI;
9533         } else if ((FI->getOpcode() == Instruction::Sub &&
9534                     TI->getOpcode() == Instruction::Add) ||
9535                    (FI->getOpcode() == Instruction::FSub &&
9536                     TI->getOpcode() == Instruction::FAdd)) {
9537           AddOp = TI; SubOp = FI;
9538         }
9539
9540         if (AddOp) {
9541           Value *OtherAddOp = 0;
9542           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9543             OtherAddOp = AddOp->getOperand(1);
9544           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9545             OtherAddOp = AddOp->getOperand(0);
9546           }
9547
9548           if (OtherAddOp) {
9549             // So at this point we know we have (Y -> OtherAddOp):
9550             //        select C, (add X, Y), (sub X, Z)
9551             Value *NegVal;  // Compute -Z
9552             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9553               NegVal = Context->getConstantExprNeg(C);
9554             } else {
9555               NegVal = InsertNewInstBefore(
9556                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9557                                               "tmp"), SI);
9558             }
9559
9560             Value *NewTrueOp = OtherAddOp;
9561             Value *NewFalseOp = NegVal;
9562             if (AddOp != TI)
9563               std::swap(NewTrueOp, NewFalseOp);
9564             Instruction *NewSel =
9565               SelectInst::Create(CondVal, NewTrueOp,
9566                                  NewFalseOp, SI.getName() + ".p");
9567
9568             NewSel = InsertNewInstBefore(NewSel, SI);
9569             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9570           }
9571         }
9572       }
9573
9574   // See if we can fold the select into one of our operands.
9575   if (SI.getType()->isInteger()) {
9576     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9577     if (FoldI)
9578       return FoldI;
9579   }
9580
9581   if (BinaryOperator::isNot(CondVal)) {
9582     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9583     SI.setOperand(1, FalseVal);
9584     SI.setOperand(2, TrueVal);
9585     return &SI;
9586   }
9587
9588   return 0;
9589 }
9590
9591 /// EnforceKnownAlignment - If the specified pointer points to an object that
9592 /// we control, modify the object's alignment to PrefAlign. This isn't
9593 /// often possible though. If alignment is important, a more reliable approach
9594 /// is to simply align all global variables and allocation instructions to
9595 /// their preferred alignment from the beginning.
9596 ///
9597 static unsigned EnforceKnownAlignment(Value *V,
9598                                       unsigned Align, unsigned PrefAlign) {
9599
9600   User *U = dyn_cast<User>(V);
9601   if (!U) return Align;
9602
9603   switch (getOpcode(U)) {
9604   default: break;
9605   case Instruction::BitCast:
9606     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9607   case Instruction::GetElementPtr: {
9608     // If all indexes are zero, it is just the alignment of the base pointer.
9609     bool AllZeroOperands = true;
9610     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9611       if (!isa<Constant>(*i) ||
9612           !cast<Constant>(*i)->isNullValue()) {
9613         AllZeroOperands = false;
9614         break;
9615       }
9616
9617     if (AllZeroOperands) {
9618       // Treat this like a bitcast.
9619       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9620     }
9621     break;
9622   }
9623   }
9624
9625   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9626     // If there is a large requested alignment and we can, bump up the alignment
9627     // of the global.
9628     if (!GV->isDeclaration()) {
9629       if (GV->getAlignment() >= PrefAlign)
9630         Align = GV->getAlignment();
9631       else {
9632         GV->setAlignment(PrefAlign);
9633         Align = PrefAlign;
9634       }
9635     }
9636   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9637     // If there is a requested alignment and if this is an alloca, round up.  We
9638     // don't do this for malloc, because some systems can't respect the request.
9639     if (isa<AllocaInst>(AI)) {
9640       if (AI->getAlignment() >= PrefAlign)
9641         Align = AI->getAlignment();
9642       else {
9643         AI->setAlignment(PrefAlign);
9644         Align = PrefAlign;
9645       }
9646     }
9647   }
9648
9649   return Align;
9650 }
9651
9652 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9653 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9654 /// and it is more than the alignment of the ultimate object, see if we can
9655 /// increase the alignment of the ultimate object, making this check succeed.
9656 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9657                                                   unsigned PrefAlign) {
9658   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9659                       sizeof(PrefAlign) * CHAR_BIT;
9660   APInt Mask = APInt::getAllOnesValue(BitWidth);
9661   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9662   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9663   unsigned TrailZ = KnownZero.countTrailingOnes();
9664   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9665
9666   if (PrefAlign > Align)
9667     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9668   
9669     // We don't need to make any adjustment.
9670   return Align;
9671 }
9672
9673 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9674   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9675   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9676   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9677   unsigned CopyAlign = MI->getAlignment();
9678
9679   if (CopyAlign < MinAlign) {
9680     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9681                                              MinAlign, false));
9682     return MI;
9683   }
9684   
9685   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9686   // load/store.
9687   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9688   if (MemOpLength == 0) return 0;
9689   
9690   // Source and destination pointer types are always "i8*" for intrinsic.  See
9691   // if the size is something we can handle with a single primitive load/store.
9692   // A single load+store correctly handles overlapping memory in the memmove
9693   // case.
9694   unsigned Size = MemOpLength->getZExtValue();
9695   if (Size == 0) return MI;  // Delete this mem transfer.
9696   
9697   if (Size > 8 || (Size&(Size-1)))
9698     return 0;  // If not 1/2/4/8 bytes, exit.
9699   
9700   // Use an integer load+store unless we can find something better.
9701   Type *NewPtrTy =
9702                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9703   
9704   // Memcpy forces the use of i8* for the source and destination.  That means
9705   // that if you're using memcpy to move one double around, you'll get a cast
9706   // from double* to i8*.  We'd much rather use a double load+store rather than
9707   // an i64 load+store, here because this improves the odds that the source or
9708   // dest address will be promotable.  See if we can find a better type than the
9709   // integer datatype.
9710   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9711     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9712     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9713       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9714       // down through these levels if so.
9715       while (!SrcETy->isSingleValueType()) {
9716         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9717           if (STy->getNumElements() == 1)
9718             SrcETy = STy->getElementType(0);
9719           else
9720             break;
9721         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9722           if (ATy->getNumElements() == 1)
9723             SrcETy = ATy->getElementType();
9724           else
9725             break;
9726         } else
9727           break;
9728       }
9729       
9730       if (SrcETy->isSingleValueType())
9731         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9732     }
9733   }
9734   
9735   
9736   // If the memcpy/memmove provides better alignment info than we can
9737   // infer, use it.
9738   SrcAlign = std::max(SrcAlign, CopyAlign);
9739   DstAlign = std::max(DstAlign, CopyAlign);
9740   
9741   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9742   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9743   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9744   InsertNewInstBefore(L, *MI);
9745   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9746
9747   // Set the size of the copy to 0, it will be deleted on the next iteration.
9748   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9749   return MI;
9750 }
9751
9752 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9753   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9754   if (MI->getAlignment() < Alignment) {
9755     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9756                                              Alignment, false));
9757     return MI;
9758   }
9759   
9760   // Extract the length and alignment and fill if they are constant.
9761   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9762   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9763   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9764     return 0;
9765   uint64_t Len = LenC->getZExtValue();
9766   Alignment = MI->getAlignment();
9767   
9768   // If the length is zero, this is a no-op
9769   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9770   
9771   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9772   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9773     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9774     
9775     Value *Dest = MI->getDest();
9776     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9777
9778     // Alignment 0 is identity for alignment 1 for memset, but not store.
9779     if (Alignment == 0) Alignment = 1;
9780     
9781     // Extract the fill value and store.
9782     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9783     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9784                                       Dest, false, Alignment), *MI);
9785     
9786     // Set the size of the copy to 0, it will be deleted on the next iteration.
9787     MI->setLength(Context->getNullValue(LenC->getType()));
9788     return MI;
9789   }
9790
9791   return 0;
9792 }
9793
9794
9795 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9796 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9797 /// the heavy lifting.
9798 ///
9799 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9800   // If the caller function is nounwind, mark the call as nounwind, even if the
9801   // callee isn't.
9802   if (CI.getParent()->getParent()->doesNotThrow() &&
9803       !CI.doesNotThrow()) {
9804     CI.setDoesNotThrow();
9805     return &CI;
9806   }
9807   
9808   
9809   
9810   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9811   if (!II) return visitCallSite(&CI);
9812   
9813   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9814   // visitCallSite.
9815   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9816     bool Changed = false;
9817
9818     // memmove/cpy/set of zero bytes is a noop.
9819     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9820       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9821
9822       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9823         if (CI->getZExtValue() == 1) {
9824           // Replace the instruction with just byte operations.  We would
9825           // transform other cases to loads/stores, but we don't know if
9826           // alignment is sufficient.
9827         }
9828     }
9829
9830     // If we have a memmove and the source operation is a constant global,
9831     // then the source and dest pointers can't alias, so we can change this
9832     // into a call to memcpy.
9833     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9834       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9835         if (GVSrc->isConstant()) {
9836           Module *M = CI.getParent()->getParent()->getParent();
9837           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9838           const Type *Tys[1];
9839           Tys[0] = CI.getOperand(3)->getType();
9840           CI.setOperand(0, 
9841                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9842           Changed = true;
9843         }
9844
9845       // memmove(x,x,size) -> noop.
9846       if (MMI->getSource() == MMI->getDest())
9847         return EraseInstFromFunction(CI);
9848     }
9849
9850     // If we can determine a pointer alignment that is bigger than currently
9851     // set, update the alignment.
9852     if (isa<MemTransferInst>(MI)) {
9853       if (Instruction *I = SimplifyMemTransfer(MI))
9854         return I;
9855     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9856       if (Instruction *I = SimplifyMemSet(MSI))
9857         return I;
9858     }
9859           
9860     if (Changed) return II;
9861   }
9862   
9863   switch (II->getIntrinsicID()) {
9864   default: break;
9865   case Intrinsic::bswap:
9866     // bswap(bswap(x)) -> x
9867     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9868       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9869         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9870     break;
9871   case Intrinsic::ppc_altivec_lvx:
9872   case Intrinsic::ppc_altivec_lvxl:
9873   case Intrinsic::x86_sse_loadu_ps:
9874   case Intrinsic::x86_sse2_loadu_pd:
9875   case Intrinsic::x86_sse2_loadu_dq:
9876     // Turn PPC lvx     -> load if the pointer is known aligned.
9877     // Turn X86 loadups -> load if the pointer is known aligned.
9878     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9879       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9880                                    Context->getPointerTypeUnqual(II->getType()),
9881                                        CI);
9882       return new LoadInst(Ptr);
9883     }
9884     break;
9885   case Intrinsic::ppc_altivec_stvx:
9886   case Intrinsic::ppc_altivec_stvxl:
9887     // Turn stvx -> store if the pointer is known aligned.
9888     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9889       const Type *OpPtrTy = 
9890         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9891       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9892       return new StoreInst(II->getOperand(1), Ptr);
9893     }
9894     break;
9895   case Intrinsic::x86_sse_storeu_ps:
9896   case Intrinsic::x86_sse2_storeu_pd:
9897   case Intrinsic::x86_sse2_storeu_dq:
9898     // Turn X86 storeu -> store if the pointer is known aligned.
9899     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9900       const Type *OpPtrTy = 
9901         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9902       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9903       return new StoreInst(II->getOperand(2), Ptr);
9904     }
9905     break;
9906     
9907   case Intrinsic::x86_sse_cvttss2si: {
9908     // These intrinsics only demands the 0th element of its input vector.  If
9909     // we can simplify the input based on that, do so now.
9910     unsigned VWidth =
9911       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9912     APInt DemandedElts(VWidth, 1);
9913     APInt UndefElts(VWidth, 0);
9914     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9915                                               UndefElts)) {
9916       II->setOperand(1, V);
9917       return II;
9918     }
9919     break;
9920   }
9921     
9922   case Intrinsic::ppc_altivec_vperm:
9923     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9924     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9925       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9926       
9927       // Check that all of the elements are integer constants or undefs.
9928       bool AllEltsOk = true;
9929       for (unsigned i = 0; i != 16; ++i) {
9930         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9931             !isa<UndefValue>(Mask->getOperand(i))) {
9932           AllEltsOk = false;
9933           break;
9934         }
9935       }
9936       
9937       if (AllEltsOk) {
9938         // Cast the input vectors to byte vectors.
9939         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9940         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9941         Value *Result = Context->getUndef(Op0->getType());
9942         
9943         // Only extract each element once.
9944         Value *ExtractedElts[32];
9945         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9946         
9947         for (unsigned i = 0; i != 16; ++i) {
9948           if (isa<UndefValue>(Mask->getOperand(i)))
9949             continue;
9950           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9951           Idx &= 31;  // Match the hardware behavior.
9952           
9953           if (ExtractedElts[Idx] == 0) {
9954             Instruction *Elt = 
9955               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9956             InsertNewInstBefore(Elt, CI);
9957             ExtractedElts[Idx] = Elt;
9958           }
9959         
9960           // Insert this value into the result vector.
9961           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9962                                              i, "tmp");
9963           InsertNewInstBefore(cast<Instruction>(Result), CI);
9964         }
9965         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9966       }
9967     }
9968     break;
9969
9970   case Intrinsic::stackrestore: {
9971     // If the save is right next to the restore, remove the restore.  This can
9972     // happen when variable allocas are DCE'd.
9973     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9974       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9975         BasicBlock::iterator BI = SS;
9976         if (&*++BI == II)
9977           return EraseInstFromFunction(CI);
9978       }
9979     }
9980     
9981     // Scan down this block to see if there is another stack restore in the
9982     // same block without an intervening call/alloca.
9983     BasicBlock::iterator BI = II;
9984     TerminatorInst *TI = II->getParent()->getTerminator();
9985     bool CannotRemove = false;
9986     for (++BI; &*BI != TI; ++BI) {
9987       if (isa<AllocaInst>(BI)) {
9988         CannotRemove = true;
9989         break;
9990       }
9991       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9992         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9993           // If there is a stackrestore below this one, remove this one.
9994           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9995             return EraseInstFromFunction(CI);
9996           // Otherwise, ignore the intrinsic.
9997         } else {
9998           // If we found a non-intrinsic call, we can't remove the stack
9999           // restore.
10000           CannotRemove = true;
10001           break;
10002         }
10003       }
10004     }
10005     
10006     // If the stack restore is in a return/unwind block and if there are no
10007     // allocas or calls between the restore and the return, nuke the restore.
10008     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10009       return EraseInstFromFunction(CI);
10010     break;
10011   }
10012   }
10013
10014   return visitCallSite(II);
10015 }
10016
10017 // InvokeInst simplification
10018 //
10019 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10020   return visitCallSite(&II);
10021 }
10022
10023 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10024 /// passed through the varargs area, we can eliminate the use of the cast.
10025 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10026                                          const CastInst * const CI,
10027                                          const TargetData * const TD,
10028                                          const int ix) {
10029   if (!CI->isLosslessCast())
10030     return false;
10031
10032   // The size of ByVal arguments is derived from the type, so we
10033   // can't change to a type with a different size.  If the size were
10034   // passed explicitly we could avoid this check.
10035   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10036     return true;
10037
10038   const Type* SrcTy = 
10039             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10040   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10041   if (!SrcTy->isSized() || !DstTy->isSized())
10042     return false;
10043   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10044     return false;
10045   return true;
10046 }
10047
10048 // visitCallSite - Improvements for call and invoke instructions.
10049 //
10050 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10051   bool Changed = false;
10052
10053   // If the callee is a constexpr cast of a function, attempt to move the cast
10054   // to the arguments of the call/invoke.
10055   if (transformConstExprCastCall(CS)) return 0;
10056
10057   Value *Callee = CS.getCalledValue();
10058
10059   if (Function *CalleeF = dyn_cast<Function>(Callee))
10060     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10061       Instruction *OldCall = CS.getInstruction();
10062       // If the call and callee calling conventions don't match, this call must
10063       // be unreachable, as the call is undefined.
10064       new StoreInst(Context->getConstantIntTrue(),
10065                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10066                                   OldCall);
10067       if (!OldCall->use_empty())
10068         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10069       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10070         return EraseInstFromFunction(*OldCall);
10071       return 0;
10072     }
10073
10074   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10075     // This instruction is not reachable, just remove it.  We insert a store to
10076     // undef so that we know that this code is not reachable, despite the fact
10077     // that we can't modify the CFG here.
10078     new StoreInst(Context->getConstantIntTrue(),
10079                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10080                   CS.getInstruction());
10081
10082     if (!CS.getInstruction()->use_empty())
10083       CS.getInstruction()->
10084         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10085
10086     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10087       // Don't break the CFG, insert a dummy cond branch.
10088       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10089                          Context->getConstantIntTrue(), II);
10090     }
10091     return EraseInstFromFunction(*CS.getInstruction());
10092   }
10093
10094   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10095     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10096       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10097         return transformCallThroughTrampoline(CS);
10098
10099   const PointerType *PTy = cast<PointerType>(Callee->getType());
10100   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10101   if (FTy->isVarArg()) {
10102     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10103     // See if we can optimize any arguments passed through the varargs area of
10104     // the call.
10105     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10106            E = CS.arg_end(); I != E; ++I, ++ix) {
10107       CastInst *CI = dyn_cast<CastInst>(*I);
10108       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10109         *I = CI->getOperand(0);
10110         Changed = true;
10111       }
10112     }
10113   }
10114
10115   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10116     // Inline asm calls cannot throw - mark them 'nounwind'.
10117     CS.setDoesNotThrow();
10118     Changed = true;
10119   }
10120
10121   return Changed ? CS.getInstruction() : 0;
10122 }
10123
10124 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10125 // attempt to move the cast to the arguments of the call/invoke.
10126 //
10127 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10128   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10129   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10130   if (CE->getOpcode() != Instruction::BitCast || 
10131       !isa<Function>(CE->getOperand(0)))
10132     return false;
10133   Function *Callee = cast<Function>(CE->getOperand(0));
10134   Instruction *Caller = CS.getInstruction();
10135   const AttrListPtr &CallerPAL = CS.getAttributes();
10136
10137   // Okay, this is a cast from a function to a different type.  Unless doing so
10138   // would cause a type conversion of one of our arguments, change this call to
10139   // be a direct call with arguments casted to the appropriate types.
10140   //
10141   const FunctionType *FT = Callee->getFunctionType();
10142   const Type *OldRetTy = Caller->getType();
10143   const Type *NewRetTy = FT->getReturnType();
10144
10145   if (isa<StructType>(NewRetTy))
10146     return false; // TODO: Handle multiple return values.
10147
10148   // Check to see if we are changing the return type...
10149   if (OldRetTy != NewRetTy) {
10150     if (Callee->isDeclaration() &&
10151         // Conversion is ok if changing from one pointer type to another or from
10152         // a pointer to an integer of the same size.
10153         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10154           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10155       return false;   // Cannot transform this return value.
10156
10157     if (!Caller->use_empty() &&
10158         // void -> non-void is handled specially
10159         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10160       return false;   // Cannot transform this return value.
10161
10162     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10163       Attributes RAttrs = CallerPAL.getRetAttributes();
10164       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10165         return false;   // Attribute not compatible with transformed value.
10166     }
10167
10168     // If the callsite is an invoke instruction, and the return value is used by
10169     // a PHI node in a successor, we cannot change the return type of the call
10170     // because there is no place to put the cast instruction (without breaking
10171     // the critical edge).  Bail out in this case.
10172     if (!Caller->use_empty())
10173       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10174         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10175              UI != E; ++UI)
10176           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10177             if (PN->getParent() == II->getNormalDest() ||
10178                 PN->getParent() == II->getUnwindDest())
10179               return false;
10180   }
10181
10182   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10183   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10184
10185   CallSite::arg_iterator AI = CS.arg_begin();
10186   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10187     const Type *ParamTy = FT->getParamType(i);
10188     const Type *ActTy = (*AI)->getType();
10189
10190     if (!CastInst::isCastable(ActTy, ParamTy))
10191       return false;   // Cannot transform this parameter value.
10192
10193     if (CallerPAL.getParamAttributes(i + 1) 
10194         & Attribute::typeIncompatible(ParamTy))
10195       return false;   // Attribute not compatible with transformed value.
10196
10197     // Converting from one pointer type to another or between a pointer and an
10198     // integer of the same size is safe even if we do not have a body.
10199     bool isConvertible = ActTy == ParamTy ||
10200       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10201        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10202     if (Callee->isDeclaration() && !isConvertible) return false;
10203   }
10204
10205   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10206       Callee->isDeclaration())
10207     return false;   // Do not delete arguments unless we have a function body.
10208
10209   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10210       !CallerPAL.isEmpty())
10211     // In this case we have more arguments than the new function type, but we
10212     // won't be dropping them.  Check that these extra arguments have attributes
10213     // that are compatible with being a vararg call argument.
10214     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10215       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10216         break;
10217       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10218       if (PAttrs & Attribute::VarArgsIncompatible)
10219         return false;
10220     }
10221
10222   // Okay, we decided that this is a safe thing to do: go ahead and start
10223   // inserting cast instructions as necessary...
10224   std::vector<Value*> Args;
10225   Args.reserve(NumActualArgs);
10226   SmallVector<AttributeWithIndex, 8> attrVec;
10227   attrVec.reserve(NumCommonArgs);
10228
10229   // Get any return attributes.
10230   Attributes RAttrs = CallerPAL.getRetAttributes();
10231
10232   // If the return value is not being used, the type may not be compatible
10233   // with the existing attributes.  Wipe out any problematic attributes.
10234   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10235
10236   // Add the new return attributes.
10237   if (RAttrs)
10238     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10239
10240   AI = CS.arg_begin();
10241   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10242     const Type *ParamTy = FT->getParamType(i);
10243     if ((*AI)->getType() == ParamTy) {
10244       Args.push_back(*AI);
10245     } else {
10246       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10247           false, ParamTy, false);
10248       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10249       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10250     }
10251
10252     // Add any parameter attributes.
10253     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10254       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10255   }
10256
10257   // If the function takes more arguments than the call was taking, add them
10258   // now...
10259   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10260     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10261
10262   // If we are removing arguments to the function, emit an obnoxious warning...
10263   if (FT->getNumParams() < NumActualArgs) {
10264     if (!FT->isVarArg()) {
10265       cerr << "WARNING: While resolving call to function '"
10266            << Callee->getName() << "' arguments were dropped!\n";
10267     } else {
10268       // Add all of the arguments in their promoted form to the arg list...
10269       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10270         const Type *PTy = getPromotedType((*AI)->getType());
10271         if (PTy != (*AI)->getType()) {
10272           // Must promote to pass through va_arg area!
10273           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10274                                                                 PTy, false);
10275           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10276           InsertNewInstBefore(Cast, *Caller);
10277           Args.push_back(Cast);
10278         } else {
10279           Args.push_back(*AI);
10280         }
10281
10282         // Add any parameter attributes.
10283         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10284           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10285       }
10286     }
10287   }
10288
10289   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10290     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10291
10292   if (NewRetTy == Type::VoidTy)
10293     Caller->setName("");   // Void type should not have a name.
10294
10295   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10296
10297   Instruction *NC;
10298   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10299     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10300                             Args.begin(), Args.end(),
10301                             Caller->getName(), Caller);
10302     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10303     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10304   } else {
10305     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10306                           Caller->getName(), Caller);
10307     CallInst *CI = cast<CallInst>(Caller);
10308     if (CI->isTailCall())
10309       cast<CallInst>(NC)->setTailCall();
10310     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10311     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10312   }
10313
10314   // Insert a cast of the return type as necessary.
10315   Value *NV = NC;
10316   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10317     if (NV->getType() != Type::VoidTy) {
10318       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10319                                                             OldRetTy, false);
10320       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10321
10322       // If this is an invoke instruction, we should insert it after the first
10323       // non-phi, instruction in the normal successor block.
10324       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10325         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10326         InsertNewInstBefore(NC, *I);
10327       } else {
10328         // Otherwise, it's a call, just insert cast right after the call instr
10329         InsertNewInstBefore(NC, *Caller);
10330       }
10331       AddUsersToWorkList(*Caller);
10332     } else {
10333       NV = Context->getUndef(Caller->getType());
10334     }
10335   }
10336
10337   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10338     Caller->replaceAllUsesWith(NV);
10339   Caller->eraseFromParent();
10340   RemoveFromWorkList(Caller);
10341   return true;
10342 }
10343
10344 // transformCallThroughTrampoline - Turn a call to a function created by the
10345 // init_trampoline intrinsic into a direct call to the underlying function.
10346 //
10347 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10348   Value *Callee = CS.getCalledValue();
10349   const PointerType *PTy = cast<PointerType>(Callee->getType());
10350   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10351   const AttrListPtr &Attrs = CS.getAttributes();
10352
10353   // If the call already has the 'nest' attribute somewhere then give up -
10354   // otherwise 'nest' would occur twice after splicing in the chain.
10355   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10356     return 0;
10357
10358   IntrinsicInst *Tramp =
10359     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10360
10361   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10362   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10363   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10364
10365   const AttrListPtr &NestAttrs = NestF->getAttributes();
10366   if (!NestAttrs.isEmpty()) {
10367     unsigned NestIdx = 1;
10368     const Type *NestTy = 0;
10369     Attributes NestAttr = Attribute::None;
10370
10371     // Look for a parameter marked with the 'nest' attribute.
10372     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10373          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10374       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10375         // Record the parameter type and any other attributes.
10376         NestTy = *I;
10377         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10378         break;
10379       }
10380
10381     if (NestTy) {
10382       Instruction *Caller = CS.getInstruction();
10383       std::vector<Value*> NewArgs;
10384       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10385
10386       SmallVector<AttributeWithIndex, 8> NewAttrs;
10387       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10388
10389       // Insert the nest argument into the call argument list, which may
10390       // mean appending it.  Likewise for attributes.
10391
10392       // Add any result attributes.
10393       if (Attributes Attr = Attrs.getRetAttributes())
10394         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10395
10396       {
10397         unsigned Idx = 1;
10398         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10399         do {
10400           if (Idx == NestIdx) {
10401             // Add the chain argument and attributes.
10402             Value *NestVal = Tramp->getOperand(3);
10403             if (NestVal->getType() != NestTy)
10404               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10405             NewArgs.push_back(NestVal);
10406             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10407           }
10408
10409           if (I == E)
10410             break;
10411
10412           // Add the original argument and attributes.
10413           NewArgs.push_back(*I);
10414           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10415             NewAttrs.push_back
10416               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10417
10418           ++Idx, ++I;
10419         } while (1);
10420       }
10421
10422       // Add any function attributes.
10423       if (Attributes Attr = Attrs.getFnAttributes())
10424         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10425
10426       // The trampoline may have been bitcast to a bogus type (FTy).
10427       // Handle this by synthesizing a new function type, equal to FTy
10428       // with the chain parameter inserted.
10429
10430       std::vector<const Type*> NewTypes;
10431       NewTypes.reserve(FTy->getNumParams()+1);
10432
10433       // Insert the chain's type into the list of parameter types, which may
10434       // mean appending it.
10435       {
10436         unsigned Idx = 1;
10437         FunctionType::param_iterator I = FTy->param_begin(),
10438           E = FTy->param_end();
10439
10440         do {
10441           if (Idx == NestIdx)
10442             // Add the chain's type.
10443             NewTypes.push_back(NestTy);
10444
10445           if (I == E)
10446             break;
10447
10448           // Add the original type.
10449           NewTypes.push_back(*I);
10450
10451           ++Idx, ++I;
10452         } while (1);
10453       }
10454
10455       // Replace the trampoline call with a direct call.  Let the generic
10456       // code sort out any function type mismatches.
10457       FunctionType *NewFTy =
10458                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10459                                                 FTy->isVarArg());
10460       Constant *NewCallee =
10461         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10462         NestF : Context->getConstantExprBitCast(NestF, 
10463                                          Context->getPointerTypeUnqual(NewFTy));
10464       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10465
10466       Instruction *NewCaller;
10467       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10468         NewCaller = InvokeInst::Create(NewCallee,
10469                                        II->getNormalDest(), II->getUnwindDest(),
10470                                        NewArgs.begin(), NewArgs.end(),
10471                                        Caller->getName(), Caller);
10472         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10473         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10474       } else {
10475         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10476                                      Caller->getName(), Caller);
10477         if (cast<CallInst>(Caller)->isTailCall())
10478           cast<CallInst>(NewCaller)->setTailCall();
10479         cast<CallInst>(NewCaller)->
10480           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10481         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10482       }
10483       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10484         Caller->replaceAllUsesWith(NewCaller);
10485       Caller->eraseFromParent();
10486       RemoveFromWorkList(Caller);
10487       return 0;
10488     }
10489   }
10490
10491   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10492   // parameter, there is no need to adjust the argument list.  Let the generic
10493   // code sort out any function type mismatches.
10494   Constant *NewCallee =
10495     NestF->getType() == PTy ? NestF : 
10496                               Context->getConstantExprBitCast(NestF, PTy);
10497   CS.setCalledFunction(NewCallee);
10498   return CS.getInstruction();
10499 }
10500
10501 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10502 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10503 /// and a single binop.
10504 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10505   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10506   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10507   unsigned Opc = FirstInst->getOpcode();
10508   Value *LHSVal = FirstInst->getOperand(0);
10509   Value *RHSVal = FirstInst->getOperand(1);
10510     
10511   const Type *LHSType = LHSVal->getType();
10512   const Type *RHSType = RHSVal->getType();
10513   
10514   // Scan to see if all operands are the same opcode, all have one use, and all
10515   // kill their operands (i.e. the operands have one use).
10516   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10517     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10518     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10519         // Verify type of the LHS matches so we don't fold cmp's of different
10520         // types or GEP's with different index types.
10521         I->getOperand(0)->getType() != LHSType ||
10522         I->getOperand(1)->getType() != RHSType)
10523       return 0;
10524
10525     // If they are CmpInst instructions, check their predicates
10526     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10527       if (cast<CmpInst>(I)->getPredicate() !=
10528           cast<CmpInst>(FirstInst)->getPredicate())
10529         return 0;
10530     
10531     // Keep track of which operand needs a phi node.
10532     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10533     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10534   }
10535   
10536   // Otherwise, this is safe to transform!
10537   
10538   Value *InLHS = FirstInst->getOperand(0);
10539   Value *InRHS = FirstInst->getOperand(1);
10540   PHINode *NewLHS = 0, *NewRHS = 0;
10541   if (LHSVal == 0) {
10542     NewLHS = PHINode::Create(LHSType,
10543                              FirstInst->getOperand(0)->getName() + ".pn");
10544     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10545     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10546     InsertNewInstBefore(NewLHS, PN);
10547     LHSVal = NewLHS;
10548   }
10549   
10550   if (RHSVal == 0) {
10551     NewRHS = PHINode::Create(RHSType,
10552                              FirstInst->getOperand(1)->getName() + ".pn");
10553     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10554     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10555     InsertNewInstBefore(NewRHS, PN);
10556     RHSVal = NewRHS;
10557   }
10558   
10559   // Add all operands to the new PHIs.
10560   if (NewLHS || NewRHS) {
10561     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10562       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10563       if (NewLHS) {
10564         Value *NewInLHS = InInst->getOperand(0);
10565         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10566       }
10567       if (NewRHS) {
10568         Value *NewInRHS = InInst->getOperand(1);
10569         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10570       }
10571     }
10572   }
10573     
10574   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10575     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10576   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10577   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10578                          LHSVal, RHSVal);
10579 }
10580
10581 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10582   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10583   
10584   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10585                                         FirstInst->op_end());
10586   // This is true if all GEP bases are allocas and if all indices into them are
10587   // constants.
10588   bool AllBasePointersAreAllocas = true;
10589   
10590   // Scan to see if all operands are the same opcode, all have one use, and all
10591   // kill their operands (i.e. the operands have one use).
10592   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10593     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10594     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10595       GEP->getNumOperands() != FirstInst->getNumOperands())
10596       return 0;
10597
10598     // Keep track of whether or not all GEPs are of alloca pointers.
10599     if (AllBasePointersAreAllocas &&
10600         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10601          !GEP->hasAllConstantIndices()))
10602       AllBasePointersAreAllocas = false;
10603     
10604     // Compare the operand lists.
10605     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10606       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10607         continue;
10608       
10609       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10610       // if one of the PHIs has a constant for the index.  The index may be
10611       // substantially cheaper to compute for the constants, so making it a
10612       // variable index could pessimize the path.  This also handles the case
10613       // for struct indices, which must always be constant.
10614       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10615           isa<ConstantInt>(GEP->getOperand(op)))
10616         return 0;
10617       
10618       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10619         return 0;
10620       FixedOperands[op] = 0;  // Needs a PHI.
10621     }
10622   }
10623   
10624   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10625   // bother doing this transformation.  At best, this will just save a bit of
10626   // offset calculation, but all the predecessors will have to materialize the
10627   // stack address into a register anyway.  We'd actually rather *clone* the
10628   // load up into the predecessors so that we have a load of a gep of an alloca,
10629   // which can usually all be folded into the load.
10630   if (AllBasePointersAreAllocas)
10631     return 0;
10632   
10633   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10634   // that is variable.
10635   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10636   
10637   bool HasAnyPHIs = false;
10638   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10639     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10640     Value *FirstOp = FirstInst->getOperand(i);
10641     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10642                                      FirstOp->getName()+".pn");
10643     InsertNewInstBefore(NewPN, PN);
10644     
10645     NewPN->reserveOperandSpace(e);
10646     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10647     OperandPhis[i] = NewPN;
10648     FixedOperands[i] = NewPN;
10649     HasAnyPHIs = true;
10650   }
10651
10652   
10653   // Add all operands to the new PHIs.
10654   if (HasAnyPHIs) {
10655     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10656       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10657       BasicBlock *InBB = PN.getIncomingBlock(i);
10658       
10659       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10660         if (PHINode *OpPhi = OperandPhis[op])
10661           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10662     }
10663   }
10664   
10665   Value *Base = FixedOperands[0];
10666   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10667                                    FixedOperands.end());
10668 }
10669
10670
10671 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10672 /// sink the load out of the block that defines it.  This means that it must be
10673 /// obvious the value of the load is not changed from the point of the load to
10674 /// the end of the block it is in.
10675 ///
10676 /// Finally, it is safe, but not profitable, to sink a load targetting a
10677 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10678 /// to a register.
10679 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10680   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10681   
10682   for (++BBI; BBI != E; ++BBI)
10683     if (BBI->mayWriteToMemory())
10684       return false;
10685   
10686   // Check for non-address taken alloca.  If not address-taken already, it isn't
10687   // profitable to do this xform.
10688   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10689     bool isAddressTaken = false;
10690     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10691          UI != E; ++UI) {
10692       if (isa<LoadInst>(UI)) continue;
10693       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10694         // If storing TO the alloca, then the address isn't taken.
10695         if (SI->getOperand(1) == AI) continue;
10696       }
10697       isAddressTaken = true;
10698       break;
10699     }
10700     
10701     if (!isAddressTaken && AI->isStaticAlloca())
10702       return false;
10703   }
10704   
10705   // If this load is a load from a GEP with a constant offset from an alloca,
10706   // then we don't want to sink it.  In its present form, it will be
10707   // load [constant stack offset].  Sinking it will cause us to have to
10708   // materialize the stack addresses in each predecessor in a register only to
10709   // do a shared load from register in the successor.
10710   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10711     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10712       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10713         return false;
10714   
10715   return true;
10716 }
10717
10718
10719 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10720 // operator and they all are only used by the PHI, PHI together their
10721 // inputs, and do the operation once, to the result of the PHI.
10722 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10723   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10724
10725   // Scan the instruction, looking for input operations that can be folded away.
10726   // If all input operands to the phi are the same instruction (e.g. a cast from
10727   // the same type or "+42") we can pull the operation through the PHI, reducing
10728   // code size and simplifying code.
10729   Constant *ConstantOp = 0;
10730   const Type *CastSrcTy = 0;
10731   bool isVolatile = false;
10732   if (isa<CastInst>(FirstInst)) {
10733     CastSrcTy = FirstInst->getOperand(0)->getType();
10734   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10735     // Can fold binop, compare or shift here if the RHS is a constant, 
10736     // otherwise call FoldPHIArgBinOpIntoPHI.
10737     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10738     if (ConstantOp == 0)
10739       return FoldPHIArgBinOpIntoPHI(PN);
10740   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10741     isVolatile = LI->isVolatile();
10742     // We can't sink the load if the loaded value could be modified between the
10743     // load and the PHI.
10744     if (LI->getParent() != PN.getIncomingBlock(0) ||
10745         !isSafeAndProfitableToSinkLoad(LI))
10746       return 0;
10747     
10748     // If the PHI is of volatile loads and the load block has multiple
10749     // successors, sinking it would remove a load of the volatile value from
10750     // the path through the other successor.
10751     if (isVolatile &&
10752         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10753       return 0;
10754     
10755   } else if (isa<GetElementPtrInst>(FirstInst)) {
10756     return FoldPHIArgGEPIntoPHI(PN);
10757   } else {
10758     return 0;  // Cannot fold this operation.
10759   }
10760
10761   // Check to see if all arguments are the same operation.
10762   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10763     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10764     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10765     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10766       return 0;
10767     if (CastSrcTy) {
10768       if (I->getOperand(0)->getType() != CastSrcTy)
10769         return 0;  // Cast operation must match.
10770     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10771       // We can't sink the load if the loaded value could be modified between 
10772       // the load and the PHI.
10773       if (LI->isVolatile() != isVolatile ||
10774           LI->getParent() != PN.getIncomingBlock(i) ||
10775           !isSafeAndProfitableToSinkLoad(LI))
10776         return 0;
10777       
10778       // If the PHI is of volatile loads and the load block has multiple
10779       // successors, sinking it would remove a load of the volatile value from
10780       // the path through the other successor.
10781       if (isVolatile &&
10782           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10783         return 0;
10784       
10785     } else if (I->getOperand(1) != ConstantOp) {
10786       return 0;
10787     }
10788   }
10789
10790   // Okay, they are all the same operation.  Create a new PHI node of the
10791   // correct type, and PHI together all of the LHS's of the instructions.
10792   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10793                                    PN.getName()+".in");
10794   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10795
10796   Value *InVal = FirstInst->getOperand(0);
10797   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10798
10799   // Add all operands to the new PHI.
10800   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10801     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10802     if (NewInVal != InVal)
10803       InVal = 0;
10804     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10805   }
10806
10807   Value *PhiVal;
10808   if (InVal) {
10809     // The new PHI unions all of the same values together.  This is really
10810     // common, so we handle it intelligently here for compile-time speed.
10811     PhiVal = InVal;
10812     delete NewPN;
10813   } else {
10814     InsertNewInstBefore(NewPN, PN);
10815     PhiVal = NewPN;
10816   }
10817
10818   // Insert and return the new operation.
10819   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10820     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10821   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10822     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10823   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10824     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10825                            PhiVal, ConstantOp);
10826   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10827   
10828   // If this was a volatile load that we are merging, make sure to loop through
10829   // and mark all the input loads as non-volatile.  If we don't do this, we will
10830   // insert a new volatile load and the old ones will not be deletable.
10831   if (isVolatile)
10832     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10833       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10834   
10835   return new LoadInst(PhiVal, "", isVolatile);
10836 }
10837
10838 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10839 /// that is dead.
10840 static bool DeadPHICycle(PHINode *PN,
10841                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10842   if (PN->use_empty()) return true;
10843   if (!PN->hasOneUse()) return false;
10844
10845   // Remember this node, and if we find the cycle, return.
10846   if (!PotentiallyDeadPHIs.insert(PN))
10847     return true;
10848   
10849   // Don't scan crazily complex things.
10850   if (PotentiallyDeadPHIs.size() == 16)
10851     return false;
10852
10853   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10854     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10855
10856   return false;
10857 }
10858
10859 /// PHIsEqualValue - Return true if this phi node is always equal to
10860 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10861 ///   z = some value; x = phi (y, z); y = phi (x, z)
10862 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10863                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10864   // See if we already saw this PHI node.
10865   if (!ValueEqualPHIs.insert(PN))
10866     return true;
10867   
10868   // Don't scan crazily complex things.
10869   if (ValueEqualPHIs.size() == 16)
10870     return false;
10871  
10872   // Scan the operands to see if they are either phi nodes or are equal to
10873   // the value.
10874   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10875     Value *Op = PN->getIncomingValue(i);
10876     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10877       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10878         return false;
10879     } else if (Op != NonPhiInVal)
10880       return false;
10881   }
10882   
10883   return true;
10884 }
10885
10886
10887 // PHINode simplification
10888 //
10889 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10890   // If LCSSA is around, don't mess with Phi nodes
10891   if (MustPreserveLCSSA) return 0;
10892   
10893   if (Value *V = PN.hasConstantValue())
10894     return ReplaceInstUsesWith(PN, V);
10895
10896   // If all PHI operands are the same operation, pull them through the PHI,
10897   // reducing code size.
10898   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10899       isa<Instruction>(PN.getIncomingValue(1)) &&
10900       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10901       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10902       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10903       // than themselves more than once.
10904       PN.getIncomingValue(0)->hasOneUse())
10905     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10906       return Result;
10907
10908   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10909   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10910   // PHI)... break the cycle.
10911   if (PN.hasOneUse()) {
10912     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10913     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10914       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10915       PotentiallyDeadPHIs.insert(&PN);
10916       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10917         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10918     }
10919    
10920     // If this phi has a single use, and if that use just computes a value for
10921     // the next iteration of a loop, delete the phi.  This occurs with unused
10922     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10923     // common case here is good because the only other things that catch this
10924     // are induction variable analysis (sometimes) and ADCE, which is only run
10925     // late.
10926     if (PHIUser->hasOneUse() &&
10927         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10928         PHIUser->use_back() == &PN) {
10929       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10930     }
10931   }
10932
10933   // We sometimes end up with phi cycles that non-obviously end up being the
10934   // same value, for example:
10935   //   z = some value; x = phi (y, z); y = phi (x, z)
10936   // where the phi nodes don't necessarily need to be in the same block.  Do a
10937   // quick check to see if the PHI node only contains a single non-phi value, if
10938   // so, scan to see if the phi cycle is actually equal to that value.
10939   {
10940     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10941     // Scan for the first non-phi operand.
10942     while (InValNo != NumOperandVals && 
10943            isa<PHINode>(PN.getIncomingValue(InValNo)))
10944       ++InValNo;
10945
10946     if (InValNo != NumOperandVals) {
10947       Value *NonPhiInVal = PN.getOperand(InValNo);
10948       
10949       // Scan the rest of the operands to see if there are any conflicts, if so
10950       // there is no need to recursively scan other phis.
10951       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10952         Value *OpVal = PN.getIncomingValue(InValNo);
10953         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10954           break;
10955       }
10956       
10957       // If we scanned over all operands, then we have one unique value plus
10958       // phi values.  Scan PHI nodes to see if they all merge in each other or
10959       // the value.
10960       if (InValNo == NumOperandVals) {
10961         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10962         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10963           return ReplaceInstUsesWith(PN, NonPhiInVal);
10964       }
10965     }
10966   }
10967   return 0;
10968 }
10969
10970 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10971                                    Instruction *InsertPoint,
10972                                    InstCombiner *IC) {
10973   unsigned PtrSize = DTy->getScalarSizeInBits();
10974   unsigned VTySize = V->getType()->getScalarSizeInBits();
10975   // We must cast correctly to the pointer type. Ensure that we
10976   // sign extend the integer value if it is smaller as this is
10977   // used for address computation.
10978   Instruction::CastOps opcode = 
10979      (VTySize < PtrSize ? Instruction::SExt :
10980       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10981   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10982 }
10983
10984
10985 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10986   Value *PtrOp = GEP.getOperand(0);
10987   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10988   // If so, eliminate the noop.
10989   if (GEP.getNumOperands() == 1)
10990     return ReplaceInstUsesWith(GEP, PtrOp);
10991
10992   if (isa<UndefValue>(GEP.getOperand(0)))
10993     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
10994
10995   bool HasZeroPointerIndex = false;
10996   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10997     HasZeroPointerIndex = C->isNullValue();
10998
10999   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11000     return ReplaceInstUsesWith(GEP, PtrOp);
11001
11002   // Eliminate unneeded casts for indices.
11003   bool MadeChange = false;
11004   
11005   gep_type_iterator GTI = gep_type_begin(GEP);
11006   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11007        i != e; ++i, ++GTI) {
11008     if (isa<SequentialType>(*GTI)) {
11009       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11010         if (CI->getOpcode() == Instruction::ZExt ||
11011             CI->getOpcode() == Instruction::SExt) {
11012           const Type *SrcTy = CI->getOperand(0)->getType();
11013           // We can eliminate a cast from i32 to i64 iff the target 
11014           // is a 32-bit pointer target.
11015           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11016             MadeChange = true;
11017             *i = CI->getOperand(0);
11018           }
11019         }
11020       }
11021       // If we are using a wider index than needed for this platform, shrink it
11022       // to what we need.  If narrower, sign-extend it to what we need.
11023       // If the incoming value needs a cast instruction,
11024       // insert it.  This explicit cast can make subsequent optimizations more
11025       // obvious.
11026       Value *Op = *i;
11027       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11028         if (Constant *C = dyn_cast<Constant>(Op)) {
11029           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11030           MadeChange = true;
11031         } else {
11032           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11033                                 GEP);
11034           *i = Op;
11035           MadeChange = true;
11036         }
11037       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11038         if (Constant *C = dyn_cast<Constant>(Op)) {
11039           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11040           MadeChange = true;
11041         } else {
11042           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11043                                 GEP);
11044           *i = Op;
11045           MadeChange = true;
11046         }
11047       }
11048     }
11049   }
11050   if (MadeChange) return &GEP;
11051
11052   // Combine Indices - If the source pointer to this getelementptr instruction
11053   // is a getelementptr instruction, combine the indices of the two
11054   // getelementptr instructions into a single instruction.
11055   //
11056   SmallVector<Value*, 8> SrcGEPOperands;
11057   if (User *Src = dyn_castGetElementPtr(PtrOp))
11058     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11059
11060   if (!SrcGEPOperands.empty()) {
11061     // Note that if our source is a gep chain itself that we wait for that
11062     // chain to be resolved before we perform this transformation.  This
11063     // avoids us creating a TON of code in some cases.
11064     //
11065     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11066         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11067       return 0;   // Wait until our source is folded to completion.
11068
11069     SmallVector<Value*, 8> Indices;
11070
11071     // Find out whether the last index in the source GEP is a sequential idx.
11072     bool EndsWithSequential = false;
11073     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11074            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11075       EndsWithSequential = !isa<StructType>(*I);
11076
11077     // Can we combine the two pointer arithmetics offsets?
11078     if (EndsWithSequential) {
11079       // Replace: gep (gep %P, long B), long A, ...
11080       // With:    T = long A+B; gep %P, T, ...
11081       //
11082       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11083       if (SO1 == Context->getNullValue(SO1->getType())) {
11084         Sum = GO1;
11085       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11086         Sum = SO1;
11087       } else {
11088         // If they aren't the same type, convert both to an integer of the
11089         // target's pointer size.
11090         if (SO1->getType() != GO1->getType()) {
11091           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11092             SO1 =
11093                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11094           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11095             GO1 =
11096                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11097           } else {
11098             unsigned PS = TD->getPointerSizeInBits();
11099             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11100               // Convert GO1 to SO1's type.
11101               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11102
11103             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11104               // Convert SO1 to GO1's type.
11105               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11106             } else {
11107               const Type *PT = TD->getIntPtrType();
11108               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11109               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11110             }
11111           }
11112         }
11113         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11114           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11115                                             cast<Constant>(GO1));
11116         else {
11117           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11118           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11119         }
11120       }
11121
11122       // Recycle the GEP we already have if possible.
11123       if (SrcGEPOperands.size() == 2) {
11124         GEP.setOperand(0, SrcGEPOperands[0]);
11125         GEP.setOperand(1, Sum);
11126         return &GEP;
11127       } else {
11128         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11129                        SrcGEPOperands.end()-1);
11130         Indices.push_back(Sum);
11131         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11132       }
11133     } else if (isa<Constant>(*GEP.idx_begin()) &&
11134                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11135                SrcGEPOperands.size() != 1) {
11136       // Otherwise we can do the fold if the first index of the GEP is a zero
11137       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11138                      SrcGEPOperands.end());
11139       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11140     }
11141
11142     if (!Indices.empty())
11143       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11144                                        Indices.end(), GEP.getName());
11145
11146   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11147     // GEP of global variable.  If all of the indices for this GEP are
11148     // constants, we can promote this to a constexpr instead of an instruction.
11149
11150     // Scan for nonconstants...
11151     SmallVector<Constant*, 8> Indices;
11152     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11153     for (; I != E && isa<Constant>(*I); ++I)
11154       Indices.push_back(cast<Constant>(*I));
11155
11156     if (I == E) {  // If they are all constants...
11157       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11158                                                     &Indices[0],Indices.size());
11159
11160       // Replace all uses of the GEP with the new constexpr...
11161       return ReplaceInstUsesWith(GEP, CE);
11162     }
11163   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11164     if (!isa<PointerType>(X->getType())) {
11165       // Not interesting.  Source pointer must be a cast from pointer.
11166     } else if (HasZeroPointerIndex) {
11167       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11168       // into     : GEP [10 x i8]* X, i32 0, ...
11169       //
11170       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11171       //           into     : GEP i8* X, ...
11172       // 
11173       // This occurs when the program declares an array extern like "int X[];"
11174       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11175       const PointerType *XTy = cast<PointerType>(X->getType());
11176       if (const ArrayType *CATy =
11177           dyn_cast<ArrayType>(CPTy->getElementType())) {
11178         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11179         if (CATy->getElementType() == XTy->getElementType()) {
11180           // -> GEP i8* X, ...
11181           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11182           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11183                                            GEP.getName());
11184         } else if (const ArrayType *XATy =
11185                  dyn_cast<ArrayType>(XTy->getElementType())) {
11186           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11187           if (CATy->getElementType() == XATy->getElementType()) {
11188             // -> GEP [10 x i8]* X, i32 0, ...
11189             // At this point, we know that the cast source type is a pointer
11190             // to an array of the same type as the destination pointer
11191             // array.  Because the array type is never stepped over (there
11192             // is a leading zero) we can fold the cast into this GEP.
11193             GEP.setOperand(0, X);
11194             return &GEP;
11195           }
11196         }
11197       }
11198     } else if (GEP.getNumOperands() == 2) {
11199       // Transform things like:
11200       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11201       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11202       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11203       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11204       if (isa<ArrayType>(SrcElTy) &&
11205           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11206           TD->getTypeAllocSize(ResElTy)) {
11207         Value *Idx[2];
11208         Idx[0] = Context->getNullValue(Type::Int32Ty);
11209         Idx[1] = GEP.getOperand(1);
11210         Value *V = InsertNewInstBefore(
11211                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11212         // V and GEP are both pointer types --> BitCast
11213         return new BitCastInst(V, GEP.getType());
11214       }
11215       
11216       // Transform things like:
11217       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11218       //   (where tmp = 8*tmp2) into:
11219       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11220       
11221       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11222         uint64_t ArrayEltSize =
11223             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11224         
11225         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11226         // allow either a mul, shift, or constant here.
11227         Value *NewIdx = 0;
11228         ConstantInt *Scale = 0;
11229         if (ArrayEltSize == 1) {
11230           NewIdx = GEP.getOperand(1);
11231           Scale = 
11232                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11233         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11234           NewIdx = Context->getConstantInt(CI->getType(), 1);
11235           Scale = CI;
11236         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11237           if (Inst->getOpcode() == Instruction::Shl &&
11238               isa<ConstantInt>(Inst->getOperand(1))) {
11239             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11240             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11241             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11242                                      1ULL << ShAmtVal);
11243             NewIdx = Inst->getOperand(0);
11244           } else if (Inst->getOpcode() == Instruction::Mul &&
11245                      isa<ConstantInt>(Inst->getOperand(1))) {
11246             Scale = cast<ConstantInt>(Inst->getOperand(1));
11247             NewIdx = Inst->getOperand(0);
11248           }
11249         }
11250         
11251         // If the index will be to exactly the right offset with the scale taken
11252         // out, perform the transformation. Note, we don't know whether Scale is
11253         // signed or not. We'll use unsigned version of division/modulo
11254         // operation after making sure Scale doesn't have the sign bit set.
11255         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11256             Scale->getZExtValue() % ArrayEltSize == 0) {
11257           Scale = Context->getConstantInt(Scale->getType(),
11258                                    Scale->getZExtValue() / ArrayEltSize);
11259           if (Scale->getZExtValue() != 1) {
11260             Constant *C =
11261                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11262                                                        false /*ZExt*/);
11263             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11264             NewIdx = InsertNewInstBefore(Sc, GEP);
11265           }
11266
11267           // Insert the new GEP instruction.
11268           Value *Idx[2];
11269           Idx[0] = Context->getNullValue(Type::Int32Ty);
11270           Idx[1] = NewIdx;
11271           Instruction *NewGEP =
11272             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11273           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11274           // The NewGEP must be pointer typed, so must the old one -> BitCast
11275           return new BitCastInst(NewGEP, GEP.getType());
11276         }
11277       }
11278     }
11279   }
11280   
11281   /// See if we can simplify:
11282   ///   X = bitcast A to B*
11283   ///   Y = gep X, <...constant indices...>
11284   /// into a gep of the original struct.  This is important for SROA and alias
11285   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11286   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11287     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11288       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11289       // a constant back from EmitGEPOffset.
11290       ConstantInt *OffsetV =
11291                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11292       int64_t Offset = OffsetV->getSExtValue();
11293       
11294       // If this GEP instruction doesn't move the pointer, just replace the GEP
11295       // with a bitcast of the real input to the dest type.
11296       if (Offset == 0) {
11297         // If the bitcast is of an allocation, and the allocation will be
11298         // converted to match the type of the cast, don't touch this.
11299         if (isa<AllocationInst>(BCI->getOperand(0))) {
11300           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11301           if (Instruction *I = visitBitCast(*BCI)) {
11302             if (I != BCI) {
11303               I->takeName(BCI);
11304               BCI->getParent()->getInstList().insert(BCI, I);
11305               ReplaceInstUsesWith(*BCI, I);
11306             }
11307             return &GEP;
11308           }
11309         }
11310         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11311       }
11312       
11313       // Otherwise, if the offset is non-zero, we need to find out if there is a
11314       // field at Offset in 'A's type.  If so, we can pull the cast through the
11315       // GEP.
11316       SmallVector<Value*, 8> NewIndices;
11317       const Type *InTy =
11318         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11319       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11320         Instruction *NGEP =
11321            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11322                                      NewIndices.end());
11323         if (NGEP->getType() == GEP.getType()) return NGEP;
11324         InsertNewInstBefore(NGEP, GEP);
11325         NGEP->takeName(&GEP);
11326         return new BitCastInst(NGEP, GEP.getType());
11327       }
11328     }
11329   }    
11330     
11331   return 0;
11332 }
11333
11334 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11335   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11336   if (AI.isArrayAllocation()) {  // Check C != 1
11337     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11338       const Type *NewTy = 
11339         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11340       AllocationInst *New = 0;
11341
11342       // Create and insert the replacement instruction...
11343       if (isa<MallocInst>(AI))
11344         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11345       else {
11346         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11347         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11348       }
11349
11350       InsertNewInstBefore(New, AI);
11351
11352       // Scan to the end of the allocation instructions, to skip over a block of
11353       // allocas if possible...also skip interleaved debug info
11354       //
11355       BasicBlock::iterator It = New;
11356       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11357
11358       // Now that I is pointing to the first non-allocation-inst in the block,
11359       // insert our getelementptr instruction...
11360       //
11361       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11362       Value *Idx[2];
11363       Idx[0] = NullIdx;
11364       Idx[1] = NullIdx;
11365       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11366                                            New->getName()+".sub", It);
11367
11368       // Now make everything use the getelementptr instead of the original
11369       // allocation.
11370       return ReplaceInstUsesWith(AI, V);
11371     } else if (isa<UndefValue>(AI.getArraySize())) {
11372       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11373     }
11374   }
11375
11376   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11377     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11378     // Note that we only do this for alloca's, because malloc should allocate
11379     // and return a unique pointer, even for a zero byte allocation.
11380     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11381       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11382
11383     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11384     if (AI.getAlignment() == 0)
11385       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11386   }
11387
11388   return 0;
11389 }
11390
11391 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11392   Value *Op = FI.getOperand(0);
11393
11394   // free undef -> unreachable.
11395   if (isa<UndefValue>(Op)) {
11396     // Insert a new store to null because we cannot modify the CFG here.
11397     new StoreInst(Context->getConstantIntTrue(),
11398            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11399     return EraseInstFromFunction(FI);
11400   }
11401   
11402   // If we have 'free null' delete the instruction.  This can happen in stl code
11403   // when lots of inlining happens.
11404   if (isa<ConstantPointerNull>(Op))
11405     return EraseInstFromFunction(FI);
11406   
11407   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11408   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11409     FI.setOperand(0, CI->getOperand(0));
11410     return &FI;
11411   }
11412   
11413   // Change free (gep X, 0,0,0,0) into free(X)
11414   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11415     if (GEPI->hasAllZeroIndices()) {
11416       AddToWorkList(GEPI);
11417       FI.setOperand(0, GEPI->getOperand(0));
11418       return &FI;
11419     }
11420   }
11421   
11422   // Change free(malloc) into nothing, if the malloc has a single use.
11423   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11424     if (MI->hasOneUse()) {
11425       EraseInstFromFunction(FI);
11426       return EraseInstFromFunction(*MI);
11427     }
11428
11429   return 0;
11430 }
11431
11432
11433 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11434 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11435                                         const TargetData *TD) {
11436   User *CI = cast<User>(LI.getOperand(0));
11437   Value *CastOp = CI->getOperand(0);
11438   LLVMContext *Context = IC.getContext();
11439
11440   if (TD) {
11441     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11442       // Instead of loading constant c string, use corresponding integer value
11443       // directly if string length is small enough.
11444       std::string Str;
11445       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11446         unsigned len = Str.length();
11447         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11448         unsigned numBits = Ty->getPrimitiveSizeInBits();
11449         // Replace LI with immediate integer store.
11450         if ((numBits >> 3) == len + 1) {
11451           APInt StrVal(numBits, 0);
11452           APInt SingleChar(numBits, 0);
11453           if (TD->isLittleEndian()) {
11454             for (signed i = len-1; i >= 0; i--) {
11455               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11456               StrVal = (StrVal << 8) | SingleChar;
11457             }
11458           } else {
11459             for (unsigned i = 0; i < len; i++) {
11460               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11461               StrVal = (StrVal << 8) | SingleChar;
11462             }
11463             // Append NULL at the end.
11464             SingleChar = 0;
11465             StrVal = (StrVal << 8) | SingleChar;
11466           }
11467           Value *NL = Context->getConstantInt(StrVal);
11468           return IC.ReplaceInstUsesWith(LI, NL);
11469         }
11470       }
11471     }
11472   }
11473
11474   const PointerType *DestTy = cast<PointerType>(CI->getType());
11475   const Type *DestPTy = DestTy->getElementType();
11476   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11477
11478     // If the address spaces don't match, don't eliminate the cast.
11479     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11480       return 0;
11481
11482     const Type *SrcPTy = SrcTy->getElementType();
11483
11484     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11485          isa<VectorType>(DestPTy)) {
11486       // If the source is an array, the code below will not succeed.  Check to
11487       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11488       // constants.
11489       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11490         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11491           if (ASrcTy->getNumElements() != 0) {
11492             Value *Idxs[2];
11493             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11494             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11495             SrcTy = cast<PointerType>(CastOp->getType());
11496             SrcPTy = SrcTy->getElementType();
11497           }
11498
11499       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11500             isa<VectorType>(SrcPTy)) &&
11501           // Do not allow turning this into a load of an integer, which is then
11502           // casted to a pointer, this pessimizes pointer analysis a lot.
11503           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11504           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11505                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11506
11507         // Okay, we are casting from one integer or pointer type to another of
11508         // the same size.  Instead of casting the pointer before the load, cast
11509         // the result of the loaded value.
11510         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11511                                                              CI->getName(),
11512                                                          LI.isVolatile()),LI);
11513         // Now cast the result of the load.
11514         return new BitCastInst(NewLoad, LI.getType());
11515       }
11516     }
11517   }
11518   return 0;
11519 }
11520
11521 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11522   Value *Op = LI.getOperand(0);
11523
11524   // Attempt to improve the alignment.
11525   unsigned KnownAlign =
11526     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11527   if (KnownAlign >
11528       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11529                                 LI.getAlignment()))
11530     LI.setAlignment(KnownAlign);
11531
11532   // load (cast X) --> cast (load X) iff safe
11533   if (isa<CastInst>(Op))
11534     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11535       return Res;
11536
11537   // None of the following transforms are legal for volatile loads.
11538   if (LI.isVolatile()) return 0;
11539   
11540   // Do really simple store-to-load forwarding and load CSE, to catch cases
11541   // where there are several consequtive memory accesses to the same location,
11542   // separated by a few arithmetic operations.
11543   BasicBlock::iterator BBI = &LI;
11544   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11545     return ReplaceInstUsesWith(LI, AvailableVal);
11546
11547   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11548     const Value *GEPI0 = GEPI->getOperand(0);
11549     // TODO: Consider a target hook for valid address spaces for this xform.
11550     if (isa<ConstantPointerNull>(GEPI0) &&
11551         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11552       // Insert a new store to null instruction before the load to indicate
11553       // that this code is not reachable.  We do this instead of inserting
11554       // an unreachable instruction directly because we cannot modify the
11555       // CFG.
11556       new StoreInst(Context->getUndef(LI.getType()),
11557                     Context->getNullValue(Op->getType()), &LI);
11558       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11559     }
11560   } 
11561
11562   if (Constant *C = dyn_cast<Constant>(Op)) {
11563     // load null/undef -> undef
11564     // TODO: Consider a target hook for valid address spaces for this xform.
11565     if (isa<UndefValue>(C) || (C->isNullValue() && 
11566         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11567       // Insert a new store to null instruction before the load to indicate that
11568       // this code is not reachable.  We do this instead of inserting an
11569       // unreachable instruction directly because we cannot modify the CFG.
11570       new StoreInst(Context->getUndef(LI.getType()),
11571                     Context->getNullValue(Op->getType()), &LI);
11572       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11573     }
11574
11575     // Instcombine load (constant global) into the value loaded.
11576     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11577       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11578         return ReplaceInstUsesWith(LI, GV->getInitializer());
11579
11580     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11581     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11582       if (CE->getOpcode() == Instruction::GetElementPtr) {
11583         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11584           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11585             if (Constant *V = 
11586                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11587                                                       Context))
11588               return ReplaceInstUsesWith(LI, V);
11589         if (CE->getOperand(0)->isNullValue()) {
11590           // Insert a new store to null instruction before the load to indicate
11591           // that this code is not reachable.  We do this instead of inserting
11592           // an unreachable instruction directly because we cannot modify the
11593           // CFG.
11594           new StoreInst(Context->getUndef(LI.getType()),
11595                         Context->getNullValue(Op->getType()), &LI);
11596           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11597         }
11598
11599       } else if (CE->isCast()) {
11600         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11601           return Res;
11602       }
11603     }
11604   }
11605     
11606   // If this load comes from anywhere in a constant global, and if the global
11607   // is all undef or zero, we know what it loads.
11608   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11609     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11610       if (GV->getInitializer()->isNullValue())
11611         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11612       else if (isa<UndefValue>(GV->getInitializer()))
11613         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11614     }
11615   }
11616
11617   if (Op->hasOneUse()) {
11618     // Change select and PHI nodes to select values instead of addresses: this
11619     // helps alias analysis out a lot, allows many others simplifications, and
11620     // exposes redundancy in the code.
11621     //
11622     // Note that we cannot do the transformation unless we know that the
11623     // introduced loads cannot trap!  Something like this is valid as long as
11624     // the condition is always false: load (select bool %C, int* null, int* %G),
11625     // but it would not be valid if we transformed it to load from null
11626     // unconditionally.
11627     //
11628     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11629       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11630       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11631           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11632         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11633                                      SI->getOperand(1)->getName()+".val"), LI);
11634         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11635                                      SI->getOperand(2)->getName()+".val"), LI);
11636         return SelectInst::Create(SI->getCondition(), V1, V2);
11637       }
11638
11639       // load (select (cond, null, P)) -> load P
11640       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11641         if (C->isNullValue()) {
11642           LI.setOperand(0, SI->getOperand(2));
11643           return &LI;
11644         }
11645
11646       // load (select (cond, P, null)) -> load P
11647       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11648         if (C->isNullValue()) {
11649           LI.setOperand(0, SI->getOperand(1));
11650           return &LI;
11651         }
11652     }
11653   }
11654   return 0;
11655 }
11656
11657 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11658 /// when possible.  This makes it generally easy to do alias analysis and/or
11659 /// SROA/mem2reg of the memory object.
11660 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11661   User *CI = cast<User>(SI.getOperand(1));
11662   Value *CastOp = CI->getOperand(0);
11663   LLVMContext *Context = IC.getContext();
11664
11665   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11666   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11667   if (SrcTy == 0) return 0;
11668   
11669   const Type *SrcPTy = SrcTy->getElementType();
11670
11671   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11672     return 0;
11673   
11674   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11675   /// to its first element.  This allows us to handle things like:
11676   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11677   /// on 32-bit hosts.
11678   SmallVector<Value*, 4> NewGEPIndices;
11679   
11680   // If the source is an array, the code below will not succeed.  Check to
11681   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11682   // constants.
11683   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11684     // Index through pointer.
11685     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11686     NewGEPIndices.push_back(Zero);
11687     
11688     while (1) {
11689       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11690         if (!STy->getNumElements()) /* Struct can be empty {} */
11691           break;
11692         NewGEPIndices.push_back(Zero);
11693         SrcPTy = STy->getElementType(0);
11694       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11695         NewGEPIndices.push_back(Zero);
11696         SrcPTy = ATy->getElementType();
11697       } else {
11698         break;
11699       }
11700     }
11701     
11702     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11703   }
11704
11705   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11706     return 0;
11707   
11708   // If the pointers point into different address spaces or if they point to
11709   // values with different sizes, we can't do the transformation.
11710   if (SrcTy->getAddressSpace() != 
11711         cast<PointerType>(CI->getType())->getAddressSpace() ||
11712       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11713       IC.getTargetData().getTypeSizeInBits(DestPTy))
11714     return 0;
11715
11716   // Okay, we are casting from one integer or pointer type to another of
11717   // the same size.  Instead of casting the pointer before 
11718   // the store, cast the value to be stored.
11719   Value *NewCast;
11720   Value *SIOp0 = SI.getOperand(0);
11721   Instruction::CastOps opcode = Instruction::BitCast;
11722   const Type* CastSrcTy = SIOp0->getType();
11723   const Type* CastDstTy = SrcPTy;
11724   if (isa<PointerType>(CastDstTy)) {
11725     if (CastSrcTy->isInteger())
11726       opcode = Instruction::IntToPtr;
11727   } else if (isa<IntegerType>(CastDstTy)) {
11728     if (isa<PointerType>(SIOp0->getType()))
11729       opcode = Instruction::PtrToInt;
11730   }
11731   
11732   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11733   // emit a GEP to index into its first field.
11734   if (!NewGEPIndices.empty()) {
11735     if (Constant *C = dyn_cast<Constant>(CastOp))
11736       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11737                                               NewGEPIndices.size());
11738     else
11739       CastOp = IC.InsertNewInstBefore(
11740               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11741                                         NewGEPIndices.end()), SI);
11742   }
11743   
11744   if (Constant *C = dyn_cast<Constant>(SIOp0))
11745     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11746   else
11747     NewCast = IC.InsertNewInstBefore(
11748       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11749       SI);
11750   return new StoreInst(NewCast, CastOp);
11751 }
11752
11753 /// equivalentAddressValues - Test if A and B will obviously have the same
11754 /// value. This includes recognizing that %t0 and %t1 will have the same
11755 /// value in code like this:
11756 ///   %t0 = getelementptr \@a, 0, 3
11757 ///   store i32 0, i32* %t0
11758 ///   %t1 = getelementptr \@a, 0, 3
11759 ///   %t2 = load i32* %t1
11760 ///
11761 static bool equivalentAddressValues(Value *A, Value *B) {
11762   // Test if the values are trivially equivalent.
11763   if (A == B) return true;
11764   
11765   // Test if the values come form identical arithmetic instructions.
11766   if (isa<BinaryOperator>(A) ||
11767       isa<CastInst>(A) ||
11768       isa<PHINode>(A) ||
11769       isa<GetElementPtrInst>(A))
11770     if (Instruction *BI = dyn_cast<Instruction>(B))
11771       if (cast<Instruction>(A)->isIdenticalTo(BI))
11772         return true;
11773   
11774   // Otherwise they may not be equivalent.
11775   return false;
11776 }
11777
11778 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11779 // return the llvm.dbg.declare.
11780 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11781   if (!V->hasNUses(2))
11782     return 0;
11783   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11784        UI != E; ++UI) {
11785     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11786       return DI;
11787     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11788       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11789         return DI;
11790       }
11791   }
11792   return 0;
11793 }
11794
11795 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11796   Value *Val = SI.getOperand(0);
11797   Value *Ptr = SI.getOperand(1);
11798
11799   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11800     EraseInstFromFunction(SI);
11801     ++NumCombined;
11802     return 0;
11803   }
11804   
11805   // If the RHS is an alloca with a single use, zapify the store, making the
11806   // alloca dead.
11807   // If the RHS is an alloca with a two uses, the other one being a 
11808   // llvm.dbg.declare, zapify the store and the declare, making the
11809   // alloca dead.  We must do this to prevent declare's from affecting
11810   // codegen.
11811   if (!SI.isVolatile()) {
11812     if (Ptr->hasOneUse()) {
11813       if (isa<AllocaInst>(Ptr)) {
11814         EraseInstFromFunction(SI);
11815         ++NumCombined;
11816         return 0;
11817       }
11818       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11819         if (isa<AllocaInst>(GEP->getOperand(0))) {
11820           if (GEP->getOperand(0)->hasOneUse()) {
11821             EraseInstFromFunction(SI);
11822             ++NumCombined;
11823             return 0;
11824           }
11825           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11826             EraseInstFromFunction(*DI);
11827             EraseInstFromFunction(SI);
11828             ++NumCombined;
11829             return 0;
11830           }
11831         }
11832       }
11833     }
11834     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11835       EraseInstFromFunction(*DI);
11836       EraseInstFromFunction(SI);
11837       ++NumCombined;
11838       return 0;
11839     }
11840   }
11841
11842   // Attempt to improve the alignment.
11843   unsigned KnownAlign =
11844     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11845   if (KnownAlign >
11846       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11847                                 SI.getAlignment()))
11848     SI.setAlignment(KnownAlign);
11849
11850   // Do really simple DSE, to catch cases where there are several consecutive
11851   // stores to the same location, separated by a few arithmetic operations. This
11852   // situation often occurs with bitfield accesses.
11853   BasicBlock::iterator BBI = &SI;
11854   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11855        --ScanInsts) {
11856     --BBI;
11857     // Don't count debug info directives, lest they affect codegen,
11858     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11859     // It is necessary for correctness to skip those that feed into a
11860     // llvm.dbg.declare, as these are not present when debugging is off.
11861     if (isa<DbgInfoIntrinsic>(BBI) ||
11862         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11863       ScanInsts++;
11864       continue;
11865     }    
11866     
11867     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11868       // Prev store isn't volatile, and stores to the same location?
11869       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11870                                                           SI.getOperand(1))) {
11871         ++NumDeadStore;
11872         ++BBI;
11873         EraseInstFromFunction(*PrevSI);
11874         continue;
11875       }
11876       break;
11877     }
11878     
11879     // If this is a load, we have to stop.  However, if the loaded value is from
11880     // the pointer we're loading and is producing the pointer we're storing,
11881     // then *this* store is dead (X = load P; store X -> P).
11882     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11883       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11884           !SI.isVolatile()) {
11885         EraseInstFromFunction(SI);
11886         ++NumCombined;
11887         return 0;
11888       }
11889       // Otherwise, this is a load from some other location.  Stores before it
11890       // may not be dead.
11891       break;
11892     }
11893     
11894     // Don't skip over loads or things that can modify memory.
11895     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11896       break;
11897   }
11898   
11899   
11900   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11901
11902   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11903   if (isa<ConstantPointerNull>(Ptr) &&
11904       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11905     if (!isa<UndefValue>(Val)) {
11906       SI.setOperand(0, Context->getUndef(Val->getType()));
11907       if (Instruction *U = dyn_cast<Instruction>(Val))
11908         AddToWorkList(U);  // Dropped a use.
11909       ++NumCombined;
11910     }
11911     return 0;  // Do not modify these!
11912   }
11913
11914   // store undef, Ptr -> noop
11915   if (isa<UndefValue>(Val)) {
11916     EraseInstFromFunction(SI);
11917     ++NumCombined;
11918     return 0;
11919   }
11920
11921   // If the pointer destination is a cast, see if we can fold the cast into the
11922   // source instead.
11923   if (isa<CastInst>(Ptr))
11924     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11925       return Res;
11926   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11927     if (CE->isCast())
11928       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11929         return Res;
11930
11931   
11932   // If this store is the last instruction in the basic block (possibly
11933   // excepting debug info instructions and the pointer bitcasts that feed
11934   // into them), and if the block ends with an unconditional branch, try
11935   // to move it to the successor block.
11936   BBI = &SI; 
11937   do {
11938     ++BBI;
11939   } while (isa<DbgInfoIntrinsic>(BBI) ||
11940            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11941   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11942     if (BI->isUnconditional())
11943       if (SimplifyStoreAtEndOfBlock(SI))
11944         return 0;  // xform done!
11945   
11946   return 0;
11947 }
11948
11949 /// SimplifyStoreAtEndOfBlock - Turn things like:
11950 ///   if () { *P = v1; } else { *P = v2 }
11951 /// into a phi node with a store in the successor.
11952 ///
11953 /// Simplify things like:
11954 ///   *P = v1; if () { *P = v2; }
11955 /// into a phi node with a store in the successor.
11956 ///
11957 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11958   BasicBlock *StoreBB = SI.getParent();
11959   
11960   // Check to see if the successor block has exactly two incoming edges.  If
11961   // so, see if the other predecessor contains a store to the same location.
11962   // if so, insert a PHI node (if needed) and move the stores down.
11963   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11964   
11965   // Determine whether Dest has exactly two predecessors and, if so, compute
11966   // the other predecessor.
11967   pred_iterator PI = pred_begin(DestBB);
11968   BasicBlock *OtherBB = 0;
11969   if (*PI != StoreBB)
11970     OtherBB = *PI;
11971   ++PI;
11972   if (PI == pred_end(DestBB))
11973     return false;
11974   
11975   if (*PI != StoreBB) {
11976     if (OtherBB)
11977       return false;
11978     OtherBB = *PI;
11979   }
11980   if (++PI != pred_end(DestBB))
11981     return false;
11982
11983   // Bail out if all the relevant blocks aren't distinct (this can happen,
11984   // for example, if SI is in an infinite loop)
11985   if (StoreBB == DestBB || OtherBB == DestBB)
11986     return false;
11987
11988   // Verify that the other block ends in a branch and is not otherwise empty.
11989   BasicBlock::iterator BBI = OtherBB->getTerminator();
11990   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11991   if (!OtherBr || BBI == OtherBB->begin())
11992     return false;
11993   
11994   // If the other block ends in an unconditional branch, check for the 'if then
11995   // else' case.  there is an instruction before the branch.
11996   StoreInst *OtherStore = 0;
11997   if (OtherBr->isUnconditional()) {
11998     --BBI;
11999     // Skip over debugging info.
12000     while (isa<DbgInfoIntrinsic>(BBI) ||
12001            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12002       if (BBI==OtherBB->begin())
12003         return false;
12004       --BBI;
12005     }
12006     // If this isn't a store, or isn't a store to the same location, bail out.
12007     OtherStore = dyn_cast<StoreInst>(BBI);
12008     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12009       return false;
12010   } else {
12011     // Otherwise, the other block ended with a conditional branch. If one of the
12012     // destinations is StoreBB, then we have the if/then case.
12013     if (OtherBr->getSuccessor(0) != StoreBB && 
12014         OtherBr->getSuccessor(1) != StoreBB)
12015       return false;
12016     
12017     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12018     // if/then triangle.  See if there is a store to the same ptr as SI that
12019     // lives in OtherBB.
12020     for (;; --BBI) {
12021       // Check to see if we find the matching store.
12022       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12023         if (OtherStore->getOperand(1) != SI.getOperand(1))
12024           return false;
12025         break;
12026       }
12027       // If we find something that may be using or overwriting the stored
12028       // value, or if we run out of instructions, we can't do the xform.
12029       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12030           BBI == OtherBB->begin())
12031         return false;
12032     }
12033     
12034     // In order to eliminate the store in OtherBr, we have to
12035     // make sure nothing reads or overwrites the stored value in
12036     // StoreBB.
12037     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12038       // FIXME: This should really be AA driven.
12039       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12040         return false;
12041     }
12042   }
12043   
12044   // Insert a PHI node now if we need it.
12045   Value *MergedVal = OtherStore->getOperand(0);
12046   if (MergedVal != SI.getOperand(0)) {
12047     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12048     PN->reserveOperandSpace(2);
12049     PN->addIncoming(SI.getOperand(0), SI.getParent());
12050     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12051     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12052   }
12053   
12054   // Advance to a place where it is safe to insert the new store and
12055   // insert it.
12056   BBI = DestBB->getFirstNonPHI();
12057   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12058                                     OtherStore->isVolatile()), *BBI);
12059   
12060   // Nuke the old stores.
12061   EraseInstFromFunction(SI);
12062   EraseInstFromFunction(*OtherStore);
12063   ++NumCombined;
12064   return true;
12065 }
12066
12067
12068 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12069   // Change br (not X), label True, label False to: br X, label False, True
12070   Value *X = 0;
12071   BasicBlock *TrueDest;
12072   BasicBlock *FalseDest;
12073   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12074       !isa<Constant>(X)) {
12075     // Swap Destinations and condition...
12076     BI.setCondition(X);
12077     BI.setSuccessor(0, FalseDest);
12078     BI.setSuccessor(1, TrueDest);
12079     return &BI;
12080   }
12081
12082   // Cannonicalize fcmp_one -> fcmp_oeq
12083   FCmpInst::Predicate FPred; Value *Y;
12084   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12085                              TrueDest, FalseDest), *Context))
12086     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12087          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12088       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12089       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12090       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12091       NewSCC->takeName(I);
12092       // Swap Destinations and condition...
12093       BI.setCondition(NewSCC);
12094       BI.setSuccessor(0, FalseDest);
12095       BI.setSuccessor(1, TrueDest);
12096       RemoveFromWorkList(I);
12097       I->eraseFromParent();
12098       AddToWorkList(NewSCC);
12099       return &BI;
12100     }
12101
12102   // Cannonicalize icmp_ne -> icmp_eq
12103   ICmpInst::Predicate IPred;
12104   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12105                       TrueDest, FalseDest), *Context))
12106     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12107          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12108          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12109       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12110       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12111       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12112       NewSCC->takeName(I);
12113       // Swap Destinations and condition...
12114       BI.setCondition(NewSCC);
12115       BI.setSuccessor(0, FalseDest);
12116       BI.setSuccessor(1, TrueDest);
12117       RemoveFromWorkList(I);
12118       I->eraseFromParent();;
12119       AddToWorkList(NewSCC);
12120       return &BI;
12121     }
12122
12123   return 0;
12124 }
12125
12126 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12127   Value *Cond = SI.getCondition();
12128   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12129     if (I->getOpcode() == Instruction::Add)
12130       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12131         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12132         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12133           SI.setOperand(i,
12134                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12135                                                 AddRHS));
12136         SI.setOperand(0, I->getOperand(0));
12137         AddToWorkList(I);
12138         return &SI;
12139       }
12140   }
12141   return 0;
12142 }
12143
12144 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12145   Value *Agg = EV.getAggregateOperand();
12146
12147   if (!EV.hasIndices())
12148     return ReplaceInstUsesWith(EV, Agg);
12149
12150   if (Constant *C = dyn_cast<Constant>(Agg)) {
12151     if (isa<UndefValue>(C))
12152       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12153       
12154     if (isa<ConstantAggregateZero>(C))
12155       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12156
12157     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12158       // Extract the element indexed by the first index out of the constant
12159       Value *V = C->getOperand(*EV.idx_begin());
12160       if (EV.getNumIndices() > 1)
12161         // Extract the remaining indices out of the constant indexed by the
12162         // first index
12163         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12164       else
12165         return ReplaceInstUsesWith(EV, V);
12166     }
12167     return 0; // Can't handle other constants
12168   } 
12169   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12170     // We're extracting from an insertvalue instruction, compare the indices
12171     const unsigned *exti, *exte, *insi, *inse;
12172     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12173          exte = EV.idx_end(), inse = IV->idx_end();
12174          exti != exte && insi != inse;
12175          ++exti, ++insi) {
12176       if (*insi != *exti)
12177         // The insert and extract both reference distinctly different elements.
12178         // This means the extract is not influenced by the insert, and we can
12179         // replace the aggregate operand of the extract with the aggregate
12180         // operand of the insert. i.e., replace
12181         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12182         // %E = extractvalue { i32, { i32 } } %I, 0
12183         // with
12184         // %E = extractvalue { i32, { i32 } } %A, 0
12185         return ExtractValueInst::Create(IV->getAggregateOperand(),
12186                                         EV.idx_begin(), EV.idx_end());
12187     }
12188     if (exti == exte && insi == inse)
12189       // Both iterators are at the end: Index lists are identical. Replace
12190       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12191       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12192       // with "i32 42"
12193       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12194     if (exti == exte) {
12195       // The extract list is a prefix of the insert list. i.e. replace
12196       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12197       // %E = extractvalue { i32, { i32 } } %I, 1
12198       // with
12199       // %X = extractvalue { i32, { i32 } } %A, 1
12200       // %E = insertvalue { i32 } %X, i32 42, 0
12201       // by switching the order of the insert and extract (though the
12202       // insertvalue should be left in, since it may have other uses).
12203       Value *NewEV = InsertNewInstBefore(
12204         ExtractValueInst::Create(IV->getAggregateOperand(),
12205                                  EV.idx_begin(), EV.idx_end()),
12206         EV);
12207       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12208                                      insi, inse);
12209     }
12210     if (insi == inse)
12211       // The insert list is a prefix of the extract list
12212       // We can simply remove the common indices from the extract and make it
12213       // operate on the inserted value instead of the insertvalue result.
12214       // i.e., replace
12215       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12216       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12217       // with
12218       // %E extractvalue { i32 } { i32 42 }, 0
12219       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12220                                       exti, exte);
12221   }
12222   // Can't simplify extracts from other values. Note that nested extracts are
12223   // already simplified implicitely by the above (extract ( extract (insert) )
12224   // will be translated into extract ( insert ( extract ) ) first and then just
12225   // the value inserted, if appropriate).
12226   return 0;
12227 }
12228
12229 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12230 /// is to leave as a vector operation.
12231 static bool CheapToScalarize(Value *V, bool isConstant) {
12232   if (isa<ConstantAggregateZero>(V)) 
12233     return true;
12234   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12235     if (isConstant) return true;
12236     // If all elts are the same, we can extract.
12237     Constant *Op0 = C->getOperand(0);
12238     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12239       if (C->getOperand(i) != Op0)
12240         return false;
12241     return true;
12242   }
12243   Instruction *I = dyn_cast<Instruction>(V);
12244   if (!I) return false;
12245   
12246   // Insert element gets simplified to the inserted element or is deleted if
12247   // this is constant idx extract element and its a constant idx insertelt.
12248   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12249       isa<ConstantInt>(I->getOperand(2)))
12250     return true;
12251   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12252     return true;
12253   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12254     if (BO->hasOneUse() &&
12255         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12256          CheapToScalarize(BO->getOperand(1), isConstant)))
12257       return true;
12258   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12259     if (CI->hasOneUse() &&
12260         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12261          CheapToScalarize(CI->getOperand(1), isConstant)))
12262       return true;
12263   
12264   return false;
12265 }
12266
12267 /// Read and decode a shufflevector mask.
12268 ///
12269 /// It turns undef elements into values that are larger than the number of
12270 /// elements in the input.
12271 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12272   unsigned NElts = SVI->getType()->getNumElements();
12273   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12274     return std::vector<unsigned>(NElts, 0);
12275   if (isa<UndefValue>(SVI->getOperand(2)))
12276     return std::vector<unsigned>(NElts, 2*NElts);
12277
12278   std::vector<unsigned> Result;
12279   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12280   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12281     if (isa<UndefValue>(*i))
12282       Result.push_back(NElts*2);  // undef -> 8
12283     else
12284       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12285   return Result;
12286 }
12287
12288 /// FindScalarElement - Given a vector and an element number, see if the scalar
12289 /// value is already around as a register, for example if it were inserted then
12290 /// extracted from the vector.
12291 static Value *FindScalarElement(Value *V, unsigned EltNo,
12292                                 LLVMContext *Context) {
12293   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12294   const VectorType *PTy = cast<VectorType>(V->getType());
12295   unsigned Width = PTy->getNumElements();
12296   if (EltNo >= Width)  // Out of range access.
12297     return Context->getUndef(PTy->getElementType());
12298   
12299   if (isa<UndefValue>(V))
12300     return Context->getUndef(PTy->getElementType());
12301   else if (isa<ConstantAggregateZero>(V))
12302     return Context->getNullValue(PTy->getElementType());
12303   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12304     return CP->getOperand(EltNo);
12305   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12306     // If this is an insert to a variable element, we don't know what it is.
12307     if (!isa<ConstantInt>(III->getOperand(2))) 
12308       return 0;
12309     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12310     
12311     // If this is an insert to the element we are looking for, return the
12312     // inserted value.
12313     if (EltNo == IIElt) 
12314       return III->getOperand(1);
12315     
12316     // Otherwise, the insertelement doesn't modify the value, recurse on its
12317     // vector input.
12318     return FindScalarElement(III->getOperand(0), EltNo, Context);
12319   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12320     unsigned LHSWidth =
12321       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12322     unsigned InEl = getShuffleMask(SVI)[EltNo];
12323     if (InEl < LHSWidth)
12324       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12325     else if (InEl < LHSWidth*2)
12326       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12327     else
12328       return Context->getUndef(PTy->getElementType());
12329   }
12330   
12331   // Otherwise, we don't know.
12332   return 0;
12333 }
12334
12335 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12336   // If vector val is undef, replace extract with scalar undef.
12337   if (isa<UndefValue>(EI.getOperand(0)))
12338     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12339
12340   // If vector val is constant 0, replace extract with scalar 0.
12341   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12342     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12343   
12344   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12345     // If vector val is constant with all elements the same, replace EI with
12346     // that element. When the elements are not identical, we cannot replace yet
12347     // (we do that below, but only when the index is constant).
12348     Constant *op0 = C->getOperand(0);
12349     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12350       if (C->getOperand(i) != op0) {
12351         op0 = 0; 
12352         break;
12353       }
12354     if (op0)
12355       return ReplaceInstUsesWith(EI, op0);
12356   }
12357   
12358   // If extracting a specified index from the vector, see if we can recursively
12359   // find a previously computed scalar that was inserted into the vector.
12360   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12361     unsigned IndexVal = IdxC->getZExtValue();
12362     unsigned VectorWidth = 
12363       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12364       
12365     // If this is extracting an invalid index, turn this into undef, to avoid
12366     // crashing the code below.
12367     if (IndexVal >= VectorWidth)
12368       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12369     
12370     // This instruction only demands the single element from the input vector.
12371     // If the input vector has a single use, simplify it based on this use
12372     // property.
12373     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12374       APInt UndefElts(VectorWidth, 0);
12375       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12376       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12377                                                 DemandedMask, UndefElts)) {
12378         EI.setOperand(0, V);
12379         return &EI;
12380       }
12381     }
12382     
12383     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12384       return ReplaceInstUsesWith(EI, Elt);
12385     
12386     // If the this extractelement is directly using a bitcast from a vector of
12387     // the same number of elements, see if we can find the source element from
12388     // it.  In this case, we will end up needing to bitcast the scalars.
12389     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12390       if (const VectorType *VT = 
12391               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12392         if (VT->getNumElements() == VectorWidth)
12393           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12394                                              IndexVal, Context))
12395             return new BitCastInst(Elt, EI.getType());
12396     }
12397   }
12398   
12399   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12400     if (I->hasOneUse()) {
12401       // Push extractelement into predecessor operation if legal and
12402       // profitable to do so
12403       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12404         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12405         if (CheapToScalarize(BO, isConstantElt)) {
12406           ExtractElementInst *newEI0 = 
12407             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12408                                    EI.getName()+".lhs");
12409           ExtractElementInst *newEI1 =
12410             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12411                                    EI.getName()+".rhs");
12412           InsertNewInstBefore(newEI0, EI);
12413           InsertNewInstBefore(newEI1, EI);
12414           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12415         }
12416       } else if (isa<LoadInst>(I)) {
12417         unsigned AS = 
12418           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12419         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12420                                   Context->getPointerType(EI.getType(), AS),EI);
12421         GetElementPtrInst *GEP =
12422           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12423         InsertNewInstBefore(GEP, EI);
12424         return new LoadInst(GEP);
12425       }
12426     }
12427     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12428       // Extracting the inserted element?
12429       if (IE->getOperand(2) == EI.getOperand(1))
12430         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12431       // If the inserted and extracted elements are constants, they must not
12432       // be the same value, extract from the pre-inserted value instead.
12433       if (isa<Constant>(IE->getOperand(2)) &&
12434           isa<Constant>(EI.getOperand(1))) {
12435         AddUsesToWorkList(EI);
12436         EI.setOperand(0, IE->getOperand(0));
12437         return &EI;
12438       }
12439     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12440       // If this is extracting an element from a shufflevector, figure out where
12441       // it came from and extract from the appropriate input element instead.
12442       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12443         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12444         Value *Src;
12445         unsigned LHSWidth =
12446           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12447
12448         if (SrcIdx < LHSWidth)
12449           Src = SVI->getOperand(0);
12450         else if (SrcIdx < LHSWidth*2) {
12451           SrcIdx -= LHSWidth;
12452           Src = SVI->getOperand(1);
12453         } else {
12454           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12455         }
12456         return new ExtractElementInst(Src, SrcIdx);
12457       }
12458     }
12459   }
12460   return 0;
12461 }
12462
12463 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12464 /// elements from either LHS or RHS, return the shuffle mask and true. 
12465 /// Otherwise, return false.
12466 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12467                                          std::vector<Constant*> &Mask,
12468                                          LLVMContext *Context) {
12469   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12470          "Invalid CollectSingleShuffleElements");
12471   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12472
12473   if (isa<UndefValue>(V)) {
12474     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12475     return true;
12476   } else if (V == LHS) {
12477     for (unsigned i = 0; i != NumElts; ++i)
12478       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12479     return true;
12480   } else if (V == RHS) {
12481     for (unsigned i = 0; i != NumElts; ++i)
12482       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12483     return true;
12484   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12485     // If this is an insert of an extract from some other vector, include it.
12486     Value *VecOp    = IEI->getOperand(0);
12487     Value *ScalarOp = IEI->getOperand(1);
12488     Value *IdxOp    = IEI->getOperand(2);
12489     
12490     if (!isa<ConstantInt>(IdxOp))
12491       return false;
12492     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12493     
12494     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12495       // Okay, we can handle this if the vector we are insertinting into is
12496       // transitively ok.
12497       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12498         // If so, update the mask to reflect the inserted undef.
12499         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12500         return true;
12501       }      
12502     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12503       if (isa<ConstantInt>(EI->getOperand(1)) &&
12504           EI->getOperand(0)->getType() == V->getType()) {
12505         unsigned ExtractedIdx =
12506           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12507         
12508         // This must be extracting from either LHS or RHS.
12509         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12510           // Okay, we can handle this if the vector we are insertinting into is
12511           // transitively ok.
12512           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12513             // If so, update the mask to reflect the inserted value.
12514             if (EI->getOperand(0) == LHS) {
12515               Mask[InsertedIdx % NumElts] = 
12516                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12517             } else {
12518               assert(EI->getOperand(0) == RHS);
12519               Mask[InsertedIdx % NumElts] = 
12520                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12521               
12522             }
12523             return true;
12524           }
12525         }
12526       }
12527     }
12528   }
12529   // TODO: Handle shufflevector here!
12530   
12531   return false;
12532 }
12533
12534 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12535 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12536 /// that computes V and the LHS value of the shuffle.
12537 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12538                                      Value *&RHS, LLVMContext *Context) {
12539   assert(isa<VectorType>(V->getType()) && 
12540          (RHS == 0 || V->getType() == RHS->getType()) &&
12541          "Invalid shuffle!");
12542   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12543
12544   if (isa<UndefValue>(V)) {
12545     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12546     return V;
12547   } else if (isa<ConstantAggregateZero>(V)) {
12548     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12549     return V;
12550   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12551     // If this is an insert of an extract from some other vector, include it.
12552     Value *VecOp    = IEI->getOperand(0);
12553     Value *ScalarOp = IEI->getOperand(1);
12554     Value *IdxOp    = IEI->getOperand(2);
12555     
12556     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12557       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12558           EI->getOperand(0)->getType() == V->getType()) {
12559         unsigned ExtractedIdx =
12560           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12561         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12562         
12563         // Either the extracted from or inserted into vector must be RHSVec,
12564         // otherwise we'd end up with a shuffle of three inputs.
12565         if (EI->getOperand(0) == RHS || RHS == 0) {
12566           RHS = EI->getOperand(0);
12567           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12568           Mask[InsertedIdx % NumElts] = 
12569             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12570           return V;
12571         }
12572         
12573         if (VecOp == RHS) {
12574           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12575                                             RHS, Context);
12576           // Everything but the extracted element is replaced with the RHS.
12577           for (unsigned i = 0; i != NumElts; ++i) {
12578             if (i != InsertedIdx)
12579               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12580           }
12581           return V;
12582         }
12583         
12584         // If this insertelement is a chain that comes from exactly these two
12585         // vectors, return the vector and the effective shuffle.
12586         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12587                                          Context))
12588           return EI->getOperand(0);
12589         
12590       }
12591     }
12592   }
12593   // TODO: Handle shufflevector here!
12594   
12595   // Otherwise, can't do anything fancy.  Return an identity vector.
12596   for (unsigned i = 0; i != NumElts; ++i)
12597     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12598   return V;
12599 }
12600
12601 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12602   Value *VecOp    = IE.getOperand(0);
12603   Value *ScalarOp = IE.getOperand(1);
12604   Value *IdxOp    = IE.getOperand(2);
12605   
12606   // Inserting an undef or into an undefined place, remove this.
12607   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12608     ReplaceInstUsesWith(IE, VecOp);
12609   
12610   // If the inserted element was extracted from some other vector, and if the 
12611   // indexes are constant, try to turn this into a shufflevector operation.
12612   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12613     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12614         EI->getOperand(0)->getType() == IE.getType()) {
12615       unsigned NumVectorElts = IE.getType()->getNumElements();
12616       unsigned ExtractedIdx =
12617         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12618       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12619       
12620       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12621         return ReplaceInstUsesWith(IE, VecOp);
12622       
12623       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12624         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12625       
12626       // If we are extracting a value from a vector, then inserting it right
12627       // back into the same place, just use the input vector.
12628       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12629         return ReplaceInstUsesWith(IE, VecOp);      
12630       
12631       // We could theoretically do this for ANY input.  However, doing so could
12632       // turn chains of insertelement instructions into a chain of shufflevector
12633       // instructions, and right now we do not merge shufflevectors.  As such,
12634       // only do this in a situation where it is clear that there is benefit.
12635       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12636         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12637         // the values of VecOp, except then one read from EIOp0.
12638         // Build a new shuffle mask.
12639         std::vector<Constant*> Mask;
12640         if (isa<UndefValue>(VecOp))
12641           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12642         else {
12643           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12644           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12645                                                        NumVectorElts));
12646         } 
12647         Mask[InsertedIdx] = 
12648                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12649         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12650                                      Context->getConstantVector(Mask));
12651       }
12652       
12653       // If this insertelement isn't used by some other insertelement, turn it
12654       // (and any insertelements it points to), into one big shuffle.
12655       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12656         std::vector<Constant*> Mask;
12657         Value *RHS = 0;
12658         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12659         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12660         // We now have a shuffle of LHS, RHS, Mask.
12661         return new ShuffleVectorInst(LHS, RHS,
12662                                      Context->getConstantVector(Mask));
12663       }
12664     }
12665   }
12666
12667   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12668   APInt UndefElts(VWidth, 0);
12669   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12670   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12671     return &IE;
12672
12673   return 0;
12674 }
12675
12676
12677 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12678   Value *LHS = SVI.getOperand(0);
12679   Value *RHS = SVI.getOperand(1);
12680   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12681
12682   bool MadeChange = false;
12683
12684   // Undefined shuffle mask -> undefined value.
12685   if (isa<UndefValue>(SVI.getOperand(2)))
12686     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12687
12688   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12689
12690   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12691     return 0;
12692
12693   APInt UndefElts(VWidth, 0);
12694   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12695   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12696     LHS = SVI.getOperand(0);
12697     RHS = SVI.getOperand(1);
12698     MadeChange = true;
12699   }
12700   
12701   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12702   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12703   if (LHS == RHS || isa<UndefValue>(LHS)) {
12704     if (isa<UndefValue>(LHS) && LHS == RHS) {
12705       // shuffle(undef,undef,mask) -> undef.
12706       return ReplaceInstUsesWith(SVI, LHS);
12707     }
12708     
12709     // Remap any references to RHS to use LHS.
12710     std::vector<Constant*> Elts;
12711     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12712       if (Mask[i] >= 2*e)
12713         Elts.push_back(Context->getUndef(Type::Int32Ty));
12714       else {
12715         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12716             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12717           Mask[i] = 2*e;     // Turn into undef.
12718           Elts.push_back(Context->getUndef(Type::Int32Ty));
12719         } else {
12720           Mask[i] = Mask[i] % e;  // Force to LHS.
12721           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12722         }
12723       }
12724     }
12725     SVI.setOperand(0, SVI.getOperand(1));
12726     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12727     SVI.setOperand(2, Context->getConstantVector(Elts));
12728     LHS = SVI.getOperand(0);
12729     RHS = SVI.getOperand(1);
12730     MadeChange = true;
12731   }
12732   
12733   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12734   bool isLHSID = true, isRHSID = true;
12735     
12736   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12737     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12738     // Is this an identity shuffle of the LHS value?
12739     isLHSID &= (Mask[i] == i);
12740       
12741     // Is this an identity shuffle of the RHS value?
12742     isRHSID &= (Mask[i]-e == i);
12743   }
12744
12745   // Eliminate identity shuffles.
12746   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12747   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12748   
12749   // If the LHS is a shufflevector itself, see if we can combine it with this
12750   // one without producing an unusual shuffle.  Here we are really conservative:
12751   // we are absolutely afraid of producing a shuffle mask not in the input
12752   // program, because the code gen may not be smart enough to turn a merged
12753   // shuffle into two specific shuffles: it may produce worse code.  As such,
12754   // we only merge two shuffles if the result is one of the two input shuffle
12755   // masks.  In this case, merging the shuffles just removes one instruction,
12756   // which we know is safe.  This is good for things like turning:
12757   // (splat(splat)) -> splat.
12758   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12759     if (isa<UndefValue>(RHS)) {
12760       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12761
12762       std::vector<unsigned> NewMask;
12763       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12764         if (Mask[i] >= 2*e)
12765           NewMask.push_back(2*e);
12766         else
12767           NewMask.push_back(LHSMask[Mask[i]]);
12768       
12769       // If the result mask is equal to the src shuffle or this shuffle mask, do
12770       // the replacement.
12771       if (NewMask == LHSMask || NewMask == Mask) {
12772         unsigned LHSInNElts =
12773           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12774         std::vector<Constant*> Elts;
12775         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12776           if (NewMask[i] >= LHSInNElts*2) {
12777             Elts.push_back(Context->getUndef(Type::Int32Ty));
12778           } else {
12779             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12780           }
12781         }
12782         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12783                                      LHSSVI->getOperand(1),
12784                                      Context->getConstantVector(Elts));
12785       }
12786     }
12787   }
12788
12789   return MadeChange ? &SVI : 0;
12790 }
12791
12792
12793
12794
12795 /// TryToSinkInstruction - Try to move the specified instruction from its
12796 /// current block into the beginning of DestBlock, which can only happen if it's
12797 /// safe to move the instruction past all of the instructions between it and the
12798 /// end of its block.
12799 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12800   assert(I->hasOneUse() && "Invariants didn't hold!");
12801
12802   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12803   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12804     return false;
12805
12806   // Do not sink alloca instructions out of the entry block.
12807   if (isa<AllocaInst>(I) && I->getParent() ==
12808         &DestBlock->getParent()->getEntryBlock())
12809     return false;
12810
12811   // We can only sink load instructions if there is nothing between the load and
12812   // the end of block that could change the value.
12813   if (I->mayReadFromMemory()) {
12814     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12815          Scan != E; ++Scan)
12816       if (Scan->mayWriteToMemory())
12817         return false;
12818   }
12819
12820   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12821
12822   CopyPrecedingStopPoint(I, InsertPos);
12823   I->moveBefore(InsertPos);
12824   ++NumSunkInst;
12825   return true;
12826 }
12827
12828
12829 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12830 /// all reachable code to the worklist.
12831 ///
12832 /// This has a couple of tricks to make the code faster and more powerful.  In
12833 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12834 /// them to the worklist (this significantly speeds up instcombine on code where
12835 /// many instructions are dead or constant).  Additionally, if we find a branch
12836 /// whose condition is a known constant, we only visit the reachable successors.
12837 ///
12838 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12839                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12840                                        InstCombiner &IC,
12841                                        const TargetData *TD) {
12842   SmallVector<BasicBlock*, 256> Worklist;
12843   Worklist.push_back(BB);
12844
12845   while (!Worklist.empty()) {
12846     BB = Worklist.back();
12847     Worklist.pop_back();
12848     
12849     // We have now visited this block!  If we've already been here, ignore it.
12850     if (!Visited.insert(BB)) continue;
12851
12852     DbgInfoIntrinsic *DBI_Prev = NULL;
12853     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12854       Instruction *Inst = BBI++;
12855       
12856       // DCE instruction if trivially dead.
12857       if (isInstructionTriviallyDead(Inst)) {
12858         ++NumDeadInst;
12859         DOUT << "IC: DCE: " << *Inst;
12860         Inst->eraseFromParent();
12861         continue;
12862       }
12863       
12864       // ConstantProp instruction if trivially constant.
12865       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12866         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12867         Inst->replaceAllUsesWith(C);
12868         ++NumConstProp;
12869         Inst->eraseFromParent();
12870         continue;
12871       }
12872      
12873       // If there are two consecutive llvm.dbg.stoppoint calls then
12874       // it is likely that the optimizer deleted code in between these
12875       // two intrinsics. 
12876       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12877       if (DBI_Next) {
12878         if (DBI_Prev
12879             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12880             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12881           IC.RemoveFromWorkList(DBI_Prev);
12882           DBI_Prev->eraseFromParent();
12883         }
12884         DBI_Prev = DBI_Next;
12885       } else {
12886         DBI_Prev = 0;
12887       }
12888
12889       IC.AddToWorkList(Inst);
12890     }
12891
12892     // Recursively visit successors.  If this is a branch or switch on a
12893     // constant, only visit the reachable successor.
12894     TerminatorInst *TI = BB->getTerminator();
12895     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12896       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12897         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12898         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12899         Worklist.push_back(ReachableBB);
12900         continue;
12901       }
12902     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12903       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12904         // See if this is an explicit destination.
12905         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12906           if (SI->getCaseValue(i) == Cond) {
12907             BasicBlock *ReachableBB = SI->getSuccessor(i);
12908             Worklist.push_back(ReachableBB);
12909             continue;
12910           }
12911         
12912         // Otherwise it is the default destination.
12913         Worklist.push_back(SI->getSuccessor(0));
12914         continue;
12915       }
12916     }
12917     
12918     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12919       Worklist.push_back(TI->getSuccessor(i));
12920   }
12921 }
12922
12923 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12924   bool Changed = false;
12925   TD = &getAnalysis<TargetData>();
12926   
12927   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12928              << F.getNameStr() << "\n");
12929
12930   {
12931     // Do a depth-first traversal of the function, populate the worklist with
12932     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12933     // track of which blocks we visit.
12934     SmallPtrSet<BasicBlock*, 64> Visited;
12935     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12936
12937     // Do a quick scan over the function.  If we find any blocks that are
12938     // unreachable, remove any instructions inside of them.  This prevents
12939     // the instcombine code from having to deal with some bad special cases.
12940     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12941       if (!Visited.count(BB)) {
12942         Instruction *Term = BB->getTerminator();
12943         while (Term != BB->begin()) {   // Remove instrs bottom-up
12944           BasicBlock::iterator I = Term; --I;
12945
12946           DOUT << "IC: DCE: " << *I;
12947           // A debug intrinsic shouldn't force another iteration if we weren't
12948           // going to do one without it.
12949           if (!isa<DbgInfoIntrinsic>(I)) {
12950             ++NumDeadInst;
12951             Changed = true;
12952           }
12953           if (!I->use_empty())
12954             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12955           I->eraseFromParent();
12956         }
12957       }
12958   }
12959
12960   while (!Worklist.empty()) {
12961     Instruction *I = RemoveOneFromWorkList();
12962     if (I == 0) continue;  // skip null values.
12963
12964     // Check to see if we can DCE the instruction.
12965     if (isInstructionTriviallyDead(I)) {
12966       // Add operands to the worklist.
12967       if (I->getNumOperands() < 4)
12968         AddUsesToWorkList(*I);
12969       ++NumDeadInst;
12970
12971       DOUT << "IC: DCE: " << *I;
12972
12973       I->eraseFromParent();
12974       RemoveFromWorkList(I);
12975       Changed = true;
12976       continue;
12977     }
12978
12979     // Instruction isn't dead, see if we can constant propagate it.
12980     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12981       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12982
12983       // Add operands to the worklist.
12984       AddUsesToWorkList(*I);
12985       ReplaceInstUsesWith(*I, C);
12986
12987       ++NumConstProp;
12988       I->eraseFromParent();
12989       RemoveFromWorkList(I);
12990       Changed = true;
12991       continue;
12992     }
12993
12994     if (TD &&
12995         (I->getType()->getTypeID() == Type::VoidTyID ||
12996          I->isTrapping())) {
12997       // See if we can constant fold its operands.
12998       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12999         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13000           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13001                                   F.getContext(), TD))
13002             if (NewC != CE) {
13003               i->set(NewC);
13004               Changed = true;
13005             }
13006     }
13007
13008     // See if we can trivially sink this instruction to a successor basic block.
13009     if (I->hasOneUse()) {
13010       BasicBlock *BB = I->getParent();
13011       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13012       if (UserParent != BB) {
13013         bool UserIsSuccessor = false;
13014         // See if the user is one of our successors.
13015         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13016           if (*SI == UserParent) {
13017             UserIsSuccessor = true;
13018             break;
13019           }
13020
13021         // If the user is one of our immediate successors, and if that successor
13022         // only has us as a predecessors (we'd have to split the critical edge
13023         // otherwise), we can keep going.
13024         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13025             next(pred_begin(UserParent)) == pred_end(UserParent))
13026           // Okay, the CFG is simple enough, try to sink this instruction.
13027           Changed |= TryToSinkInstruction(I, UserParent);
13028       }
13029     }
13030
13031     // Now that we have an instruction, try combining it to simplify it...
13032 #ifndef NDEBUG
13033     std::string OrigI;
13034 #endif
13035     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13036     if (Instruction *Result = visit(*I)) {
13037       ++NumCombined;
13038       // Should we replace the old instruction with a new one?
13039       if (Result != I) {
13040         DOUT << "IC: Old = " << *I
13041              << "    New = " << *Result;
13042
13043         // Everything uses the new instruction now.
13044         I->replaceAllUsesWith(Result);
13045
13046         // Push the new instruction and any users onto the worklist.
13047         AddToWorkList(Result);
13048         AddUsersToWorkList(*Result);
13049
13050         // Move the name to the new instruction first.
13051         Result->takeName(I);
13052
13053         // Insert the new instruction into the basic block...
13054         BasicBlock *InstParent = I->getParent();
13055         BasicBlock::iterator InsertPos = I;
13056
13057         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13058           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13059             ++InsertPos;
13060
13061         InstParent->getInstList().insert(InsertPos, Result);
13062
13063         // Make sure that we reprocess all operands now that we reduced their
13064         // use counts.
13065         AddUsesToWorkList(*I);
13066
13067         // Instructions can end up on the worklist more than once.  Make sure
13068         // we do not process an instruction that has been deleted.
13069         RemoveFromWorkList(I);
13070
13071         // Erase the old instruction.
13072         InstParent->getInstList().erase(I);
13073       } else {
13074 #ifndef NDEBUG
13075         DOUT << "IC: Mod = " << OrigI
13076              << "    New = " << *I;
13077 #endif
13078
13079         // If the instruction was modified, it's possible that it is now dead.
13080         // if so, remove it.
13081         if (isInstructionTriviallyDead(I)) {
13082           // Make sure we process all operands now that we are reducing their
13083           // use counts.
13084           AddUsesToWorkList(*I);
13085
13086           // Instructions may end up in the worklist more than once.  Erase all
13087           // occurrences of this instruction.
13088           RemoveFromWorkList(I);
13089           I->eraseFromParent();
13090         } else {
13091           AddToWorkList(I);
13092           AddUsersToWorkList(*I);
13093         }
13094       }
13095       Changed = true;
13096     }
13097   }
13098
13099   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13100     
13101   // Do an explicit clear, this shrinks the map if needed.
13102   WorklistMap.clear();
13103   return Changed;
13104 }
13105
13106
13107 bool InstCombiner::runOnFunction(Function &F) {
13108   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13109   
13110   bool EverMadeChange = false;
13111
13112   // Iterate while there is work to do.
13113   unsigned Iteration = 0;
13114   while (DoOneIteration(F, Iteration++))
13115     EverMadeChange = true;
13116   return EverMadeChange;
13117 }
13118
13119 FunctionPass *llvm::createInstructionCombiningPass() {
13120   return new InstCombiner();
13121 }