864b2fa5ee050f79871514d68afec0a15094cf35
[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(V) ||
414         BinaryOperator::isFNeg(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(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(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(bool) + C -> bool ? C + 1 : C
2105       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106         if (ZI->getSrcTy() == Type::Int1Ty)
2107           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2108     }
2109
2110     if (isa<PHINode>(LHS))
2111       if (Instruction *NV = FoldOpIntoPhi(I))
2112         return NV;
2113     
2114     ConstantInt *XorRHS = 0;
2115     Value *XorLHS = 0;
2116     if (isa<ConstantInt>(RHSC) &&
2117         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2118       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2119       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2120       
2121       uint32_t Size = TySizeBits / 2;
2122       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123       APInt CFF80Val(-C0080Val);
2124       do {
2125         if (TySizeBits > Size) {
2126           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130             // This is a sign extend if the top bits are known zero.
2131             if (!MaskedValueIsZero(XorLHS, 
2132                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133               Size = 0;  // Not a sign ext, but can't be any others either.
2134             break;
2135           }
2136         }
2137         Size >>= 1;
2138         C0080Val = APIntOps::lshr(C0080Val, Size);
2139         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140       } while (Size >= 1);
2141       
2142       // FIXME: This shouldn't be necessary. When the backends can handle types
2143       // with funny bit widths then this switch statement should be removed. It
2144       // is just here to get the size of the "middle" type back up to something
2145       // that the back ends can handle.
2146       const Type *MiddleType = 0;
2147       switch (Size) {
2148         default: break;
2149         case 32: MiddleType = Type::Int32Ty; break;
2150         case 16: MiddleType = Type::Int16Ty; break;
2151         case  8: MiddleType = Type::Int8Ty; break;
2152       }
2153       if (MiddleType) {
2154         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155         InsertNewInstBefore(NewTrunc, I);
2156         return new SExtInst(NewTrunc, I.getType(), I.getName());
2157       }
2158     }
2159   }
2160
2161   if (I.getType() == Type::Int1Ty)
2162     return BinaryOperator::CreateXor(LHS, RHS);
2163
2164   // X + X --> X << 1
2165   if (I.getType()->isInteger()) {
2166     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2167       return Result;
2168
2169     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170       if (RHSI->getOpcode() == Instruction::Sub)
2171         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2172           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2173     }
2174     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175       if (LHSI->getOpcode() == Instruction::Sub)
2176         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2177           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2178     }
2179   }
2180
2181   // -A + B  -->  B - A
2182   // -A + -B  -->  -(A + B)
2183   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2184     if (LHS->getType()->isIntOrIntVector()) {
2185       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2186         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2187         InsertNewInstBefore(NewAdd, I);
2188         return BinaryOperator::CreateNeg(*Context, NewAdd);
2189       }
2190     }
2191     
2192     return BinaryOperator::CreateSub(RHS, LHSV);
2193   }
2194
2195   // A + -B  -->  A - B
2196   if (!isa<Constant>(RHS))
2197     if (Value *V = dyn_castNegVal(RHS, Context))
2198       return BinaryOperator::CreateSub(LHS, V);
2199
2200
2201   ConstantInt *C2;
2202   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2203     if (X == RHS)   // X*C + X --> X * (C+1)
2204       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2205
2206     // X*C1 + X*C2 --> X * (C1+C2)
2207     ConstantInt *C1;
2208     if (X == dyn_castFoldableMul(RHS, C1, Context))
2209       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2210   }
2211
2212   // X + X*C --> X * (C+1)
2213   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2215
2216   // X + ~X --> -1   since   ~X = -X-1
2217   if (dyn_castNotVal(LHS, Context) == RHS ||
2218       dyn_castNotVal(RHS, Context) == LHS)
2219     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2220   
2221
2222   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2223   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2224     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2225       return R;
2226   
2227   // A+B --> A|B iff A and B have no bits set in common.
2228   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230     APInt LHSKnownOne(IT->getBitWidth(), 0);
2231     APInt LHSKnownZero(IT->getBitWidth(), 0);
2232     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233     if (LHSKnownZero != 0) {
2234       APInt RHSKnownOne(IT->getBitWidth(), 0);
2235       APInt RHSKnownZero(IT->getBitWidth(), 0);
2236       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237       
2238       // No bits in common -> bitwise or.
2239       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2240         return BinaryOperator::CreateOr(LHS, RHS);
2241     }
2242   }
2243
2244   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2245   if (I.getType()->isIntOrIntVector()) {
2246     Value *W, *X, *Y, *Z;
2247     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2248         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2249       if (W != Y) {
2250         if (W == Z) {
2251           std::swap(Y, Z);
2252         } else if (Y == X) {
2253           std::swap(W, X);
2254         } else if (X == Z) {
2255           std::swap(Y, Z);
2256           std::swap(W, X);
2257         }
2258       }
2259
2260       if (W == Y) {
2261         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2262                                                             LHS->getName()), I);
2263         return BinaryOperator::CreateMul(W, NewAdd);
2264       }
2265     }
2266   }
2267
2268   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2269     Value *X = 0;
2270     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2271       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2272
2273     // (X & FF00) + xx00  -> (X+xx00) & FF00
2274     if (LHS->hasOneUse() &&
2275         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2276       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2277       if (Anded == CRHS) {
2278         // See if all bits from the first bit set in the Add RHS up are included
2279         // in the mask.  First, get the rightmost bit.
2280         const APInt& AddRHSV = CRHS->getValue();
2281
2282         // Form a mask of all bits from the lowest bit added through the top.
2283         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2284
2285         // See if the and mask includes all of these bits.
2286         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2287
2288         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289           // Okay, the xform is safe.  Insert the new add pronto.
2290           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2291                                                             LHS->getName()), I);
2292           return BinaryOperator::CreateAnd(NewAdd, C2);
2293         }
2294       }
2295     }
2296
2297     // Try to fold constant add into select arguments.
2298     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2299       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2300         return R;
2301   }
2302
2303   // add (cast *A to intptrtype) B -> 
2304   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2305   {
2306     CastInst *CI = dyn_cast<CastInst>(LHS);
2307     Value *Other = RHS;
2308     if (!CI) {
2309       CI = dyn_cast<CastInst>(RHS);
2310       Other = LHS;
2311     }
2312     if (CI && CI->getType()->isSized() && 
2313         (CI->getType()->getScalarSizeInBits() ==
2314          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2315         && isa<PointerType>(CI->getOperand(0)->getType())) {
2316       unsigned AS =
2317         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2318       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2319                                   Context->getPointerType(Type::Int8Ty, AS), I);
2320       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2321       return new PtrToIntInst(I2, CI->getType());
2322     }
2323   }
2324   
2325   // add (select X 0 (sub n A)) A  -->  select X A n
2326   {
2327     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2328     Value *A = RHS;
2329     if (!SI) {
2330       SI = dyn_cast<SelectInst>(RHS);
2331       A = LHS;
2332     }
2333     if (SI && SI->hasOneUse()) {
2334       Value *TV = SI->getTrueValue();
2335       Value *FV = SI->getFalseValue();
2336       Value *N;
2337
2338       // Can we fold the add into the argument of the select?
2339       // We check both true and false select arguments for a matching subtract.
2340       if (match(FV, m_Zero(), *Context) &&
2341           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2342         // Fold the add into the true select value.
2343         return SelectInst::Create(SI->getCondition(), N, A);
2344       if (match(TV, m_Zero(), *Context) &&
2345           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2346         // Fold the add into the false select value.
2347         return SelectInst::Create(SI->getCondition(), A, N);
2348     }
2349   }
2350
2351   // Check for (add (sext x), y), see if we can merge this into an
2352   // integer add followed by a sext.
2353   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354     // (add (sext x), cst) --> (sext (add x, cst'))
2355     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2356       Constant *CI = 
2357         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2358       if (LHSConv->hasOneUse() &&
2359           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2360           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361         // Insert the new, smaller add.
2362         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2363                                                         CI, "addconv");
2364         InsertNewInstBefore(NewAdd, I);
2365         return new SExtInst(NewAdd, I.getType());
2366       }
2367     }
2368     
2369     // (add (sext x), (sext y)) --> (sext (add int x, y))
2370     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371       // Only do this if x/y have the same type, if at last one of them has a
2372       // single use (so we don't increase the number of sexts), and if the
2373       // integer add will not overflow.
2374       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377                                    RHSConv->getOperand(0))) {
2378         // Insert the new integer add.
2379         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2380                                                         RHSConv->getOperand(0),
2381                                                         "addconv");
2382         InsertNewInstBefore(NewAdd, I);
2383         return new SExtInst(NewAdd, I.getType());
2384       }
2385     }
2386   }
2387
2388   return Changed ? &I : 0;
2389 }
2390
2391 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392   bool Changed = SimplifyCommutative(I);
2393   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2394
2395   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2396     // X + 0 --> X
2397     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2398       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2399                               (I.getType())->getValueAPF()))
2400         return ReplaceInstUsesWith(I, LHS);
2401     }
2402
2403     if (isa<PHINode>(LHS))
2404       if (Instruction *NV = FoldOpIntoPhi(I))
2405         return NV;
2406   }
2407
2408   // -A + B  -->  B - A
2409   // -A + -B  -->  -(A + B)
2410   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2411     return BinaryOperator::CreateFSub(RHS, LHSV);
2412
2413   // A + -B  -->  A - B
2414   if (!isa<Constant>(RHS))
2415     if (Value *V = dyn_castFNegVal(RHS, Context))
2416       return BinaryOperator::CreateFSub(LHS, V);
2417
2418   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2419   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421       return ReplaceInstUsesWith(I, LHS);
2422
2423   // Check for (add double (sitofp x), y), see if we can merge this into an
2424   // integer add followed by a promotion.
2425   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427     // ... if the constant fits in the integer value.  This is useful for things
2428     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429     // requires a constant pool load, and generally allows the add to be better
2430     // instcombined.
2431     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2432       Constant *CI = 
2433       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2434       if (LHSConv->hasOneUse() &&
2435           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2436           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437         // Insert the new integer add.
2438         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2439                                                         CI, "addconv");
2440         InsertNewInstBefore(NewAdd, I);
2441         return new SIToFPInst(NewAdd, I.getType());
2442       }
2443     }
2444     
2445     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447       // Only do this if x/y have the same type, if at last one of them has a
2448       // single use (so we don't increase the number of int->fp conversions),
2449       // and if the integer add will not overflow.
2450       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453                                    RHSConv->getOperand(0))) {
2454         // Insert the new integer add.
2455         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2456                                                         RHSConv->getOperand(0),
2457                                                         "addconv");
2458         InsertNewInstBefore(NewAdd, I);
2459         return new SIToFPInst(NewAdd, I.getType());
2460       }
2461     }
2462   }
2463   
2464   return Changed ? &I : 0;
2465 }
2466
2467 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2468   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469
2470   if (Op0 == Op1)                        // sub X, X  -> 0
2471     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2472
2473   // If this is a 'B = x-(-A)', change to B = x+A...
2474   if (Value *V = dyn_castNegVal(Op1, Context))
2475     return BinaryOperator::CreateAdd(Op0, V);
2476
2477   if (isa<UndefValue>(Op0))
2478     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2479   if (isa<UndefValue>(Op1))
2480     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2481
2482   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483     // Replace (-1 - A) with (~A)...
2484     if (C->isAllOnesValue())
2485       return BinaryOperator::CreateNot(*Context, Op1);
2486
2487     // C - ~X == X + (1+C)
2488     Value *X = 0;
2489     if (match(Op1, m_Not(m_Value(X)), *Context))
2490       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2491
2492     // -(X >>u 31) -> (X >>s 31)
2493     // -(X >>s 31) -> (X >>u 31)
2494     if (C->isZero()) {
2495       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2496         if (SI->getOpcode() == Instruction::LShr) {
2497           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2498             // Check to see if we are shifting out everything but the sign bit.
2499             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2500                 SI->getType()->getPrimitiveSizeInBits()-1) {
2501               // Ok, the transformation is safe.  Insert AShr.
2502               return BinaryOperator::Create(Instruction::AShr, 
2503                                           SI->getOperand(0), CU, SI->getName());
2504             }
2505           }
2506         }
2507         else if (SI->getOpcode() == Instruction::AShr) {
2508           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509             // Check to see if we are shifting out everything but the sign bit.
2510             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2511                 SI->getType()->getPrimitiveSizeInBits()-1) {
2512               // Ok, the transformation is safe.  Insert LShr. 
2513               return BinaryOperator::CreateLShr(
2514                                           SI->getOperand(0), CU, SI->getName());
2515             }
2516           }
2517         }
2518       }
2519     }
2520
2521     // Try to fold constant sub into select arguments.
2522     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2523       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524         return R;
2525
2526     // C - zext(bool) -> bool ? C - 1 : C
2527     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2528       if (ZI->getSrcTy() == Type::Int1Ty)
2529         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2530   }
2531
2532   if (I.getType() == Type::Int1Ty)
2533     return BinaryOperator::CreateXor(Op0, Op1);
2534
2535   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2536     if (Op1I->getOpcode() == Instruction::Add) {
2537       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2538         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2539                                          I.getName());
2540       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2541         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2542                                          I.getName());
2543       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2544         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2545           // C1-(X+C2) --> (C1-C2)-X
2546           return BinaryOperator::CreateSub(
2547             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2548       }
2549     }
2550
2551     if (Op1I->hasOneUse()) {
2552       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2553       // is not used by anyone else...
2554       //
2555       if (Op1I->getOpcode() == Instruction::Sub) {
2556         // Swap the two operands of the subexpr...
2557         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2558         Op1I->setOperand(0, IIOp1);
2559         Op1I->setOperand(1, IIOp0);
2560
2561         // Create the new top level add instruction...
2562         return BinaryOperator::CreateAdd(Op0, Op1);
2563       }
2564
2565       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2566       //
2567       if (Op1I->getOpcode() == Instruction::And &&
2568           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2569         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2570
2571         Value *NewNot =
2572           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2573                                                         OtherOp, "B.not"), I);
2574         return BinaryOperator::CreateAnd(Op0, NewNot);
2575       }
2576
2577       // 0 - (X sdiv C)  -> (X sdiv -C)
2578       if (Op1I->getOpcode() == Instruction::SDiv)
2579         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2580           if (CSI->isZero())
2581             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2582               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2583                                           Context->getConstantExprNeg(DivRHS));
2584
2585       // X - X*C --> X * (1-C)
2586       ConstantInt *C2 = 0;
2587       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2588         Constant *CP1 = 
2589           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2590                                              C2);
2591         return BinaryOperator::CreateMul(Op0, CP1);
2592       }
2593     }
2594   }
2595
2596   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2597     if (Op0I->getOpcode() == Instruction::Add) {
2598       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2599         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2600       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2601         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2602     } else if (Op0I->getOpcode() == Instruction::Sub) {
2603       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2604         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2605                                          I.getName());
2606     }
2607   }
2608
2609   ConstantInt *C1;
2610   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2611     if (X == Op1)  // X*C - X --> X * (C-1)
2612       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2613
2614     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2615     if (X == dyn_castFoldableMul(Op1, C2, Context))
2616       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2617   }
2618   return 0;
2619 }
2620
2621 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2622   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2623
2624   // If this is a 'B = x-(-A)', change to B = x+A...
2625   if (Value *V = dyn_castFNegVal(Op1, Context))
2626     return BinaryOperator::CreateFAdd(Op0, V);
2627
2628   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2629     if (Op1I->getOpcode() == Instruction::FAdd) {
2630       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2631         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2632                                           I.getName());
2633       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2634         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2635                                           I.getName());
2636     }
2637   }
2638
2639   return 0;
2640 }
2641
2642 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2643 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2644 /// TrueIfSigned if the result of the comparison is true when the input value is
2645 /// signed.
2646 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2647                            bool &TrueIfSigned) {
2648   switch (pred) {
2649   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2650     TrueIfSigned = true;
2651     return RHS->isZero();
2652   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2653     TrueIfSigned = true;
2654     return RHS->isAllOnesValue();
2655   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2656     TrueIfSigned = false;
2657     return RHS->isAllOnesValue();
2658   case ICmpInst::ICMP_UGT:
2659     // True if LHS u> RHS and RHS == high-bit-mask - 1
2660     TrueIfSigned = true;
2661     return RHS->getValue() ==
2662       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2663   case ICmpInst::ICMP_UGE: 
2664     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2665     TrueIfSigned = true;
2666     return RHS->getValue().isSignBit();
2667   default:
2668     return false;
2669   }
2670 }
2671
2672 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2673   bool Changed = SimplifyCommutative(I);
2674   Value *Op0 = I.getOperand(0);
2675
2676   // TODO: If Op1 is undef and Op0 is finite, return zero.
2677   if (!I.getType()->isFPOrFPVector() &&
2678       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2679     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2680
2681   // Simplify mul instructions with a constant RHS...
2682   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2683     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2684
2685       // ((X << C1)*C2) == (X * (C2 << C1))
2686       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2687         if (SI->getOpcode() == Instruction::Shl)
2688           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2689             return BinaryOperator::CreateMul(SI->getOperand(0),
2690                                         Context->getConstantExprShl(CI, ShOp));
2691
2692       if (CI->isZero())
2693         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2694       if (CI->equalsInt(1))                  // X * 1  == X
2695         return ReplaceInstUsesWith(I, Op0);
2696       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2697         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2698
2699       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2700       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2701         return BinaryOperator::CreateShl(Op0,
2702                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2703       }
2704     } else if (isa<VectorType>(Op1->getType())) {
2705       if (Op1->isNullValue())
2706         return ReplaceInstUsesWith(I, Op1);
2707
2708       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2709         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2710           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2711
2712         // As above, vector X*splat(1.0) -> X in all defined cases.
2713         if (Constant *Splat = Op1V->getSplatValue()) {
2714           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2715             if (CI->equalsInt(1))
2716               return ReplaceInstUsesWith(I, Op0);
2717         }
2718       }
2719     }
2720     
2721     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2722       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2723           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2724         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2725         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2726                                                      Op1, "tmp");
2727         InsertNewInstBefore(Add, I);
2728         Value *C1C2 = Context->getConstantExprMul(Op1, 
2729                                            cast<Constant>(Op0I->getOperand(1)));
2730         return BinaryOperator::CreateAdd(Add, C1C2);
2731         
2732       }
2733
2734     // Try to fold constant mul into select arguments.
2735     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2736       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2737         return R;
2738
2739     if (isa<PHINode>(Op0))
2740       if (Instruction *NV = FoldOpIntoPhi(I))
2741         return NV;
2742   }
2743
2744   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2745     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2746       return BinaryOperator::CreateMul(Op0v, Op1v);
2747
2748   // (X / Y) *  Y = X - (X % Y)
2749   // (X / Y) * -Y = (X % Y) - X
2750   {
2751     Value *Op1 = I.getOperand(1);
2752     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2753     if (!BO ||
2754         (BO->getOpcode() != Instruction::UDiv && 
2755          BO->getOpcode() != Instruction::SDiv)) {
2756       Op1 = Op0;
2757       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2758     }
2759     Value *Neg = dyn_castNegVal(Op1, Context);
2760     if (BO && BO->hasOneUse() &&
2761         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2762         (BO->getOpcode() == Instruction::UDiv ||
2763          BO->getOpcode() == Instruction::SDiv)) {
2764       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2765
2766       Instruction *Rem;
2767       if (BO->getOpcode() == Instruction::UDiv)
2768         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2769       else
2770         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2771
2772       InsertNewInstBefore(Rem, I);
2773       Rem->takeName(BO);
2774
2775       if (Op1BO == Op1)
2776         return BinaryOperator::CreateSub(Op0BO, Rem);
2777       else
2778         return BinaryOperator::CreateSub(Rem, Op0BO);
2779     }
2780   }
2781
2782   if (I.getType() == Type::Int1Ty)
2783     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2784
2785   // If one of the operands of the multiply is a cast from a boolean value, then
2786   // we know the bool is either zero or one, so this is a 'masking' multiply.
2787   // See if we can simplify things based on how the boolean was originally
2788   // formed.
2789   CastInst *BoolCast = 0;
2790   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2791     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2792       BoolCast = CI;
2793   if (!BoolCast)
2794     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2795       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2796         BoolCast = CI;
2797   if (BoolCast) {
2798     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2799       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2800       const Type *SCOpTy = SCIOp0->getType();
2801       bool TIS = false;
2802       
2803       // If the icmp is true iff the sign bit of X is set, then convert this
2804       // multiply into a shift/and combination.
2805       if (isa<ConstantInt>(SCIOp1) &&
2806           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2807           TIS) {
2808         // Shift the X value right to turn it into "all signbits".
2809         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2810                                           SCOpTy->getPrimitiveSizeInBits()-1);
2811         Value *V =
2812           InsertNewInstBefore(
2813             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2814                                             BoolCast->getOperand(0)->getName()+
2815                                             ".mask"), I);
2816
2817         // If the multiply type is not the same as the source type, sign extend
2818         // or truncate to the multiply type.
2819         if (I.getType() != V->getType()) {
2820           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2821           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2822           Instruction::CastOps opcode = 
2823             (SrcBits == DstBits ? Instruction::BitCast : 
2824              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2825           V = InsertCastBefore(opcode, V, I.getType(), I);
2826         }
2827
2828         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2829         return BinaryOperator::CreateAnd(V, OtherOp);
2830       }
2831     }
2832   }
2833
2834   return Changed ? &I : 0;
2835 }
2836
2837 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2838   bool Changed = SimplifyCommutative(I);
2839   Value *Op0 = I.getOperand(0);
2840
2841   // Simplify mul instructions with a constant RHS...
2842   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2843     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2844       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2845       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2846       if (Op1F->isExactlyValue(1.0))
2847         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2848     } else if (isa<VectorType>(Op1->getType())) {
2849       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2850         // As above, vector X*splat(1.0) -> X in all defined cases.
2851         if (Constant *Splat = Op1V->getSplatValue()) {
2852           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2853             if (F->isExactlyValue(1.0))
2854               return ReplaceInstUsesWith(I, Op0);
2855         }
2856       }
2857     }
2858
2859     // Try to fold constant mul into select arguments.
2860     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2861       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2862         return R;
2863
2864     if (isa<PHINode>(Op0))
2865       if (Instruction *NV = FoldOpIntoPhi(I))
2866         return NV;
2867   }
2868
2869   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2870     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2871       return BinaryOperator::CreateFMul(Op0v, Op1v);
2872
2873   return Changed ? &I : 0;
2874 }
2875
2876 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2877 /// instruction.
2878 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2879   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2880   
2881   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2882   int NonNullOperand = -1;
2883   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2884     if (ST->isNullValue())
2885       NonNullOperand = 2;
2886   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2887   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2888     if (ST->isNullValue())
2889       NonNullOperand = 1;
2890   
2891   if (NonNullOperand == -1)
2892     return false;
2893   
2894   Value *SelectCond = SI->getOperand(0);
2895   
2896   // Change the div/rem to use 'Y' instead of the select.
2897   I.setOperand(1, SI->getOperand(NonNullOperand));
2898   
2899   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2900   // problem.  However, the select, or the condition of the select may have
2901   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2902   // propagate the known value for the select into other uses of it, and
2903   // propagate a known value of the condition into its other users.
2904   
2905   // If the select and condition only have a single use, don't bother with this,
2906   // early exit.
2907   if (SI->use_empty() && SelectCond->hasOneUse())
2908     return true;
2909   
2910   // Scan the current block backward, looking for other uses of SI.
2911   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2912   
2913   while (BBI != BBFront) {
2914     --BBI;
2915     // If we found a call to a function, we can't assume it will return, so
2916     // information from below it cannot be propagated above it.
2917     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2918       break;
2919     
2920     // Replace uses of the select or its condition with the known values.
2921     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2922          I != E; ++I) {
2923       if (*I == SI) {
2924         *I = SI->getOperand(NonNullOperand);
2925         AddToWorkList(BBI);
2926       } else if (*I == SelectCond) {
2927         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2928                                    Context->getConstantIntFalse();
2929         AddToWorkList(BBI);
2930       }
2931     }
2932     
2933     // If we past the instruction, quit looking for it.
2934     if (&*BBI == SI)
2935       SI = 0;
2936     if (&*BBI == SelectCond)
2937       SelectCond = 0;
2938     
2939     // If we ran out of things to eliminate, break out of the loop.
2940     if (SelectCond == 0 && SI == 0)
2941       break;
2942     
2943   }
2944   return true;
2945 }
2946
2947
2948 /// This function implements the transforms on div instructions that work
2949 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2950 /// used by the visitors to those instructions.
2951 /// @brief Transforms common to all three div instructions
2952 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2953   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2954
2955   // undef / X -> 0        for integer.
2956   // undef / X -> undef    for FP (the undef could be a snan).
2957   if (isa<UndefValue>(Op0)) {
2958     if (Op0->getType()->isFPOrFPVector())
2959       return ReplaceInstUsesWith(I, Op0);
2960     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2961   }
2962
2963   // X / undef -> undef
2964   if (isa<UndefValue>(Op1))
2965     return ReplaceInstUsesWith(I, Op1);
2966
2967   return 0;
2968 }
2969
2970 /// This function implements the transforms common to both integer division
2971 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2972 /// division instructions.
2973 /// @brief Common integer divide transforms
2974 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2975   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2976
2977   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2978   if (Op0 == Op1) {
2979     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2980       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2981       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2982       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2983     }
2984
2985     Constant *CI = Context->getConstantInt(I.getType(), 1);
2986     return ReplaceInstUsesWith(I, CI);
2987   }
2988   
2989   if (Instruction *Common = commonDivTransforms(I))
2990     return Common;
2991   
2992   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2993   // This does not apply for fdiv.
2994   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2995     return &I;
2996
2997   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2998     // div X, 1 == X
2999     if (RHS->equalsInt(1))
3000       return ReplaceInstUsesWith(I, Op0);
3001
3002     // (X / C1) / C2  -> X / (C1*C2)
3003     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3004       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3005         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3006           if (MultiplyOverflows(RHS, LHSRHS,
3007                                 I.getOpcode()==Instruction::SDiv, Context))
3008             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3009           else 
3010             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3011                                       Context->getConstantExprMul(RHS, LHSRHS));
3012         }
3013
3014     if (!RHS->isZero()) { // avoid X udiv 0
3015       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3016         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3017           return R;
3018       if (isa<PHINode>(Op0))
3019         if (Instruction *NV = FoldOpIntoPhi(I))
3020           return NV;
3021     }
3022   }
3023
3024   // 0 / X == 0, we don't need to preserve faults!
3025   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3026     if (LHS->equalsInt(0))
3027       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3028
3029   // It can't be division by zero, hence it must be division by one.
3030   if (I.getType() == Type::Int1Ty)
3031     return ReplaceInstUsesWith(I, Op0);
3032
3033   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3034     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3035       // div X, 1 == X
3036       if (X->isOne())
3037         return ReplaceInstUsesWith(I, Op0);
3038   }
3039
3040   return 0;
3041 }
3042
3043 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3044   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3045
3046   // Handle the integer div common cases
3047   if (Instruction *Common = commonIDivTransforms(I))
3048     return Common;
3049
3050   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3051     // X udiv C^2 -> X >> C
3052     // Check to see if this is an unsigned division with an exact power of 2,
3053     // if so, convert to a right shift.
3054     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3055       return BinaryOperator::CreateLShr(Op0, 
3056             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3057
3058     // X udiv C, where C >= signbit
3059     if (C->getValue().isNegative()) {
3060       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3061                                                     ICmpInst::ICMP_ULT, Op0, C),
3062                                       I);
3063       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3064                                 Context->getConstantInt(I.getType(), 1));
3065     }
3066   }
3067
3068   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3069   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3070     if (RHSI->getOpcode() == Instruction::Shl &&
3071         isa<ConstantInt>(RHSI->getOperand(0))) {
3072       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3073       if (C1.isPowerOf2()) {
3074         Value *N = RHSI->getOperand(1);
3075         const Type *NTy = N->getType();
3076         if (uint32_t C2 = C1.logBase2()) {
3077           Constant *C2V = Context->getConstantInt(NTy, C2);
3078           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3079         }
3080         return BinaryOperator::CreateLShr(Op0, N);
3081       }
3082     }
3083   }
3084   
3085   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3086   // where C1&C2 are powers of two.
3087   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3088     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3089       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3090         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3091         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3092           // Compute the shift amounts
3093           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3094           // Construct the "on true" case of the select
3095           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3096           Instruction *TSI = BinaryOperator::CreateLShr(
3097                                                  Op0, TC, SI->getName()+".t");
3098           TSI = InsertNewInstBefore(TSI, I);
3099   
3100           // Construct the "on false" case of the select
3101           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3102           Instruction *FSI = BinaryOperator::CreateLShr(
3103                                                  Op0, FC, SI->getName()+".f");
3104           FSI = InsertNewInstBefore(FSI, I);
3105
3106           // construct the select instruction and return it.
3107           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3108         }
3109       }
3110   return 0;
3111 }
3112
3113 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3114   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115
3116   // Handle the integer div common cases
3117   if (Instruction *Common = commonIDivTransforms(I))
3118     return Common;
3119
3120   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3121     // sdiv X, -1 == -X
3122     if (RHS->isAllOnesValue())
3123       return BinaryOperator::CreateNeg(*Context, Op0);
3124   }
3125
3126   // If the sign bits of both operands are zero (i.e. we can prove they are
3127   // unsigned inputs), turn this into a udiv.
3128   if (I.getType()->isInteger()) {
3129     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3130     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3131       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3132       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3133     }
3134   }      
3135   
3136   return 0;
3137 }
3138
3139 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3140   return commonDivTransforms(I);
3141 }
3142
3143 /// This function implements the transforms on rem instructions that work
3144 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3145 /// is used by the visitors to those instructions.
3146 /// @brief Transforms common to all three rem instructions
3147 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3148   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3149
3150   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3151     if (I.getType()->isFPOrFPVector())
3152       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3153     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3154   }
3155   if (isa<UndefValue>(Op1))
3156     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3157
3158   // Handle cases involving: rem X, (select Cond, Y, Z)
3159   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3160     return &I;
3161
3162   return 0;
3163 }
3164
3165 /// This function implements the transforms common to both integer remainder
3166 /// instructions (urem and srem). It is called by the visitors to those integer
3167 /// remainder instructions.
3168 /// @brief Common integer remainder transforms
3169 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3170   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172   if (Instruction *common = commonRemTransforms(I))
3173     return common;
3174
3175   // 0 % X == 0 for integer, we don't need to preserve faults!
3176   if (Constant *LHS = dyn_cast<Constant>(Op0))
3177     if (LHS->isNullValue())
3178       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3179
3180   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181     // X % 0 == undef, we don't need to preserve faults!
3182     if (RHS->equalsInt(0))
3183       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3184     
3185     if (RHS->equalsInt(1))  // X % 1 == 0
3186       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3187
3188     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3189       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3190         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3191           return R;
3192       } else if (isa<PHINode>(Op0I)) {
3193         if (Instruction *NV = FoldOpIntoPhi(I))
3194           return NV;
3195       }
3196
3197       // See if we can fold away this rem instruction.
3198       if (SimplifyDemandedInstructionBits(I))
3199         return &I;
3200     }
3201   }
3202
3203   return 0;
3204 }
3205
3206 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3207   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3208
3209   if (Instruction *common = commonIRemTransforms(I))
3210     return common;
3211   
3212   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3213     // X urem C^2 -> X and C
3214     // Check to see if this is an unsigned remainder with an exact power of 2,
3215     // if so, convert to a bitwise and.
3216     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3217       if (C->getValue().isPowerOf2())
3218         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3219   }
3220
3221   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3222     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3223     if (RHSI->getOpcode() == Instruction::Shl &&
3224         isa<ConstantInt>(RHSI->getOperand(0))) {
3225       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3226         Constant *N1 = Context->getAllOnesValue(I.getType());
3227         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3228                                                                    "tmp"), I);
3229         return BinaryOperator::CreateAnd(Op0, Add);
3230       }
3231     }
3232   }
3233
3234   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3235   // where C1&C2 are powers of two.
3236   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3237     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3238       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3239         // STO == 0 and SFO == 0 handled above.
3240         if ((STO->getValue().isPowerOf2()) && 
3241             (SFO->getValue().isPowerOf2())) {
3242           Value *TrueAnd = InsertNewInstBefore(
3243             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3244                                       SI->getName()+".t"), I);
3245           Value *FalseAnd = InsertNewInstBefore(
3246             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3247                                       SI->getName()+".f"), I);
3248           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3249         }
3250       }
3251   }
3252   
3253   return 0;
3254 }
3255
3256 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3257   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3258
3259   // Handle the integer rem common cases
3260   if (Instruction *common = commonIRemTransforms(I))
3261     return common;
3262   
3263   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3264     if (!isa<Constant>(RHSNeg) ||
3265         (isa<ConstantInt>(RHSNeg) &&
3266          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3267       // X % -Y -> X % Y
3268       AddUsesToWorkList(I);
3269       I.setOperand(1, RHSNeg);
3270       return &I;
3271     }
3272
3273   // If the sign bits of both operands are zero (i.e. we can prove they are
3274   // unsigned inputs), turn this into a urem.
3275   if (I.getType()->isInteger()) {
3276     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3277     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3278       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3279       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3280     }
3281   }
3282
3283   // If it's a constant vector, flip any negative values positive.
3284   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3285     unsigned VWidth = RHSV->getNumOperands();
3286
3287     bool hasNegative = false;
3288     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3289       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3290         if (RHS->getValue().isNegative())
3291           hasNegative = true;
3292
3293     if (hasNegative) {
3294       std::vector<Constant *> Elts(VWidth);
3295       for (unsigned i = 0; i != VWidth; ++i) {
3296         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3297           if (RHS->getValue().isNegative())
3298             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3299           else
3300             Elts[i] = RHS;
3301         }
3302       }
3303
3304       Constant *NewRHSV = Context->getConstantVector(Elts);
3305       if (NewRHSV != RHSV) {
3306         AddUsesToWorkList(I);
3307         I.setOperand(1, NewRHSV);
3308         return &I;
3309       }
3310     }
3311   }
3312
3313   return 0;
3314 }
3315
3316 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3317   return commonRemTransforms(I);
3318 }
3319
3320 // isOneBitSet - Return true if there is exactly one bit set in the specified
3321 // constant.
3322 static bool isOneBitSet(const ConstantInt *CI) {
3323   return CI->getValue().isPowerOf2();
3324 }
3325
3326 // isHighOnes - Return true if the constant is of the form 1+0+.
3327 // This is the same as lowones(~X).
3328 static bool isHighOnes(const ConstantInt *CI) {
3329   return (~CI->getValue() + 1).isPowerOf2();
3330 }
3331
3332 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3333 /// are carefully arranged to allow folding of expressions such as:
3334 ///
3335 ///      (A < B) | (A > B) --> (A != B)
3336 ///
3337 /// Note that this is only valid if the first and second predicates have the
3338 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3339 ///
3340 /// Three bits are used to represent the condition, as follows:
3341 ///   0  A > B
3342 ///   1  A == B
3343 ///   2  A < B
3344 ///
3345 /// <=>  Value  Definition
3346 /// 000     0   Always false
3347 /// 001     1   A >  B
3348 /// 010     2   A == B
3349 /// 011     3   A >= B
3350 /// 100     4   A <  B
3351 /// 101     5   A != B
3352 /// 110     6   A <= B
3353 /// 111     7   Always true
3354 ///  
3355 static unsigned getICmpCode(const ICmpInst *ICI) {
3356   switch (ICI->getPredicate()) {
3357     // False -> 0
3358   case ICmpInst::ICMP_UGT: return 1;  // 001
3359   case ICmpInst::ICMP_SGT: return 1;  // 001
3360   case ICmpInst::ICMP_EQ:  return 2;  // 010
3361   case ICmpInst::ICMP_UGE: return 3;  // 011
3362   case ICmpInst::ICMP_SGE: return 3;  // 011
3363   case ICmpInst::ICMP_ULT: return 4;  // 100
3364   case ICmpInst::ICMP_SLT: return 4;  // 100
3365   case ICmpInst::ICMP_NE:  return 5;  // 101
3366   case ICmpInst::ICMP_ULE: return 6;  // 110
3367   case ICmpInst::ICMP_SLE: return 6;  // 110
3368     // True -> 7
3369   default:
3370     LLVM_UNREACHABLE("Invalid ICmp predicate!");
3371     return 0;
3372   }
3373 }
3374
3375 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3376 /// predicate into a three bit mask. It also returns whether it is an ordered
3377 /// predicate by reference.
3378 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3379   isOrdered = false;
3380   switch (CC) {
3381   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3382   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3383   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3384   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3385   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3386   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3387   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3388   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3389   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3390   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3391   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3392   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3393   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3394   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3395     // True -> 7
3396   default:
3397     // Not expecting FCMP_FALSE and FCMP_TRUE;
3398     LLVM_UNREACHABLE("Unexpected FCmp predicate!");
3399     return 0;
3400   }
3401 }
3402
3403 /// getICmpValue - This is the complement of getICmpCode, which turns an
3404 /// opcode and two operands into either a constant true or false, or a brand 
3405 /// new ICmp instruction. The sign is passed in to determine which kind
3406 /// of predicate to use in the new icmp instruction.
3407 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3408                            LLVMContext *Context) {
3409   switch (code) {
3410   default: LLVM_UNREACHABLE("Illegal ICmp code!");
3411   case  0: return Context->getConstantIntFalse();
3412   case  1: 
3413     if (sign)
3414       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3415     else
3416       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3417   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3418   case  3: 
3419     if (sign)
3420       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3421     else
3422       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3423   case  4: 
3424     if (sign)
3425       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3426     else
3427       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3428   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3429   case  6: 
3430     if (sign)
3431       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3432     else
3433       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3434   case  7: return Context->getConstantIntTrue();
3435   }
3436 }
3437
3438 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3439 /// opcode and two operands into either a FCmp instruction. isordered is passed
3440 /// in to determine which kind of predicate to use in the new fcmp instruction.
3441 static Value *getFCmpValue(bool isordered, unsigned code,
3442                            Value *LHS, Value *RHS, LLVMContext *Context) {
3443   switch (code) {
3444   default: LLVM_UNREACHABLE("Illegal FCmp code!");
3445   case  0:
3446     if (isordered)
3447       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3448     else
3449       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3450   case  1: 
3451     if (isordered)
3452       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3453     else
3454       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3455   case  2: 
3456     if (isordered)
3457       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3458     else
3459       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3460   case  3: 
3461     if (isordered)
3462       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3463     else
3464       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3465   case  4: 
3466     if (isordered)
3467       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3468     else
3469       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3470   case  5: 
3471     if (isordered)
3472       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3473     else
3474       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3475   case  6: 
3476     if (isordered)
3477       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3478     else
3479       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3480   case  7: return Context->getConstantIntTrue();
3481   }
3482 }
3483
3484 /// PredicatesFoldable - Return true if both predicates match sign or if at
3485 /// least one of them is an equality comparison (which is signless).
3486 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3487   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3488          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3489          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3490 }
3491
3492 namespace { 
3493 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3494 struct FoldICmpLogical {
3495   InstCombiner &IC;
3496   Value *LHS, *RHS;
3497   ICmpInst::Predicate pred;
3498   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3499     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3500       pred(ICI->getPredicate()) {}
3501   bool shouldApply(Value *V) const {
3502     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3503       if (PredicatesFoldable(pred, ICI->getPredicate()))
3504         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3505                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3506     return false;
3507   }
3508   Instruction *apply(Instruction &Log) const {
3509     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3510     if (ICI->getOperand(0) != LHS) {
3511       assert(ICI->getOperand(1) == LHS);
3512       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3513     }
3514
3515     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3516     unsigned LHSCode = getICmpCode(ICI);
3517     unsigned RHSCode = getICmpCode(RHSICI);
3518     unsigned Code;
3519     switch (Log.getOpcode()) {
3520     case Instruction::And: Code = LHSCode & RHSCode; break;
3521     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3522     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3523     default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
3524     }
3525
3526     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3527                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3528       
3529     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3530     if (Instruction *I = dyn_cast<Instruction>(RV))
3531       return I;
3532     // Otherwise, it's a constant boolean value...
3533     return IC.ReplaceInstUsesWith(Log, RV);
3534   }
3535 };
3536 } // end anonymous namespace
3537
3538 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3539 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3540 // guaranteed to be a binary operator.
3541 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3542                                     ConstantInt *OpRHS,
3543                                     ConstantInt *AndRHS,
3544                                     BinaryOperator &TheAnd) {
3545   Value *X = Op->getOperand(0);
3546   Constant *Together = 0;
3547   if (!Op->isShift())
3548     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3549
3550   switch (Op->getOpcode()) {
3551   case Instruction::Xor:
3552     if (Op->hasOneUse()) {
3553       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3554       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3555       InsertNewInstBefore(And, TheAnd);
3556       And->takeName(Op);
3557       return BinaryOperator::CreateXor(And, Together);
3558     }
3559     break;
3560   case Instruction::Or:
3561     if (Together == AndRHS) // (X | C) & C --> C
3562       return ReplaceInstUsesWith(TheAnd, AndRHS);
3563
3564     if (Op->hasOneUse() && Together != OpRHS) {
3565       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3566       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3567       InsertNewInstBefore(Or, TheAnd);
3568       Or->takeName(Op);
3569       return BinaryOperator::CreateAnd(Or, AndRHS);
3570     }
3571     break;
3572   case Instruction::Add:
3573     if (Op->hasOneUse()) {
3574       // Adding a one to a single bit bit-field should be turned into an XOR
3575       // of the bit.  First thing to check is to see if this AND is with a
3576       // single bit constant.
3577       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3578
3579       // If there is only one bit set...
3580       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3581         // Ok, at this point, we know that we are masking the result of the
3582         // ADD down to exactly one bit.  If the constant we are adding has
3583         // no bits set below this bit, then we can eliminate the ADD.
3584         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3585
3586         // Check to see if any bits below the one bit set in AndRHSV are set.
3587         if ((AddRHS & (AndRHSV-1)) == 0) {
3588           // If not, the only thing that can effect the output of the AND is
3589           // the bit specified by AndRHSV.  If that bit is set, the effect of
3590           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3591           // no effect.
3592           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3593             TheAnd.setOperand(0, X);
3594             return &TheAnd;
3595           } else {
3596             // Pull the XOR out of the AND.
3597             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3598             InsertNewInstBefore(NewAnd, TheAnd);
3599             NewAnd->takeName(Op);
3600             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3601           }
3602         }
3603       }
3604     }
3605     break;
3606
3607   case Instruction::Shl: {
3608     // We know that the AND will not produce any of the bits shifted in, so if
3609     // the anded constant includes them, clear them now!
3610     //
3611     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3612     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3613     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3614     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3615
3616     if (CI->getValue() == ShlMask) { 
3617     // Masking out bits that the shift already masks
3618       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3619     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3620       TheAnd.setOperand(1, CI);
3621       return &TheAnd;
3622     }
3623     break;
3624   }
3625   case Instruction::LShr:
3626   {
3627     // We know that the AND will not produce any of the bits shifted in, so if
3628     // the anded constant includes them, clear them now!  This only applies to
3629     // unsigned shifts, because a signed shr may bring in set bits!
3630     //
3631     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3632     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3633     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3634     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3635
3636     if (CI->getValue() == ShrMask) {   
3637     // Masking out bits that the shift already masks.
3638       return ReplaceInstUsesWith(TheAnd, Op);
3639     } else if (CI != AndRHS) {
3640       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3641       return &TheAnd;
3642     }
3643     break;
3644   }
3645   case Instruction::AShr:
3646     // Signed shr.
3647     // See if this is shifting in some sign extension, then masking it out
3648     // with an and.
3649     if (Op->hasOneUse()) {
3650       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3651       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3652       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3653       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3654       if (C == AndRHS) {          // Masking out bits shifted in.
3655         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3656         // Make the argument unsigned.
3657         Value *ShVal = Op->getOperand(0);
3658         ShVal = InsertNewInstBefore(
3659             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3660                                    Op->getName()), TheAnd);
3661         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3662       }
3663     }
3664     break;
3665   }
3666   return 0;
3667 }
3668
3669
3670 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3671 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3672 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3673 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3674 /// insert new instructions.
3675 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3676                                            bool isSigned, bool Inside, 
3677                                            Instruction &IB) {
3678   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3679             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3680          "Lo is not <= Hi in range emission code!");
3681     
3682   if (Inside) {
3683     if (Lo == Hi)  // Trivially false.
3684       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3685
3686     // V >= Min && V < Hi --> V < Hi
3687     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3688       ICmpInst::Predicate pred = (isSigned ? 
3689         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3690       return new ICmpInst(*Context, pred, V, Hi);
3691     }
3692
3693     // Emit V-Lo <u Hi-Lo
3694     Constant *NegLo = Context->getConstantExprNeg(Lo);
3695     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3696     InsertNewInstBefore(Add, IB);
3697     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3698     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3699   }
3700
3701   if (Lo == Hi)  // Trivially true.
3702     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3703
3704   // V < Min || V >= Hi -> V > Hi-1
3705   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3706   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3707     ICmpInst::Predicate pred = (isSigned ? 
3708         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3709     return new ICmpInst(*Context, pred, V, Hi);
3710   }
3711
3712   // Emit V-Lo >u Hi-1-Lo
3713   // Note that Hi has already had one subtracted from it, above.
3714   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3715   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3716   InsertNewInstBefore(Add, IB);
3717   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3718   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3719 }
3720
3721 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3722 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3723 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3724 // not, since all 1s are not contiguous.
3725 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3726   const APInt& V = Val->getValue();
3727   uint32_t BitWidth = Val->getType()->getBitWidth();
3728   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3729
3730   // look for the first zero bit after the run of ones
3731   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3732   // look for the first non-zero bit
3733   ME = V.getActiveBits(); 
3734   return true;
3735 }
3736
3737 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3738 /// where isSub determines whether the operator is a sub.  If we can fold one of
3739 /// the following xforms:
3740 /// 
3741 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3742 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3743 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3744 ///
3745 /// return (A +/- B).
3746 ///
3747 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3748                                         ConstantInt *Mask, bool isSub,
3749                                         Instruction &I) {
3750   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3751   if (!LHSI || LHSI->getNumOperands() != 2 ||
3752       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3753
3754   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3755
3756   switch (LHSI->getOpcode()) {
3757   default: return 0;
3758   case Instruction::And:
3759     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3760       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3761       if ((Mask->getValue().countLeadingZeros() + 
3762            Mask->getValue().countPopulation()) == 
3763           Mask->getValue().getBitWidth())
3764         break;
3765
3766       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3767       // part, we don't need any explicit masks to take them out of A.  If that
3768       // is all N is, ignore it.
3769       uint32_t MB = 0, ME = 0;
3770       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3771         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3772         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3773         if (MaskedValueIsZero(RHS, Mask))
3774           break;
3775       }
3776     }
3777     return 0;
3778   case Instruction::Or:
3779   case Instruction::Xor:
3780     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3781     if ((Mask->getValue().countLeadingZeros() + 
3782          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3783         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3784       break;
3785     return 0;
3786   }
3787   
3788   Instruction *New;
3789   if (isSub)
3790     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3791   else
3792     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3793   return InsertNewInstBefore(New, I);
3794 }
3795
3796 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3797 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3798                                           ICmpInst *LHS, ICmpInst *RHS) {
3799   Value *Val, *Val2;
3800   ConstantInt *LHSCst, *RHSCst;
3801   ICmpInst::Predicate LHSCC, RHSCC;
3802   
3803   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3804   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3805                          m_ConstantInt(LHSCst)), *Context) ||
3806       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3807                          m_ConstantInt(RHSCst)), *Context))
3808     return 0;
3809   
3810   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3811   // where C is a power of 2
3812   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3813       LHSCst->getValue().isPowerOf2()) {
3814     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3815     InsertNewInstBefore(NewOr, I);
3816     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3817   }
3818   
3819   // From here on, we only handle:
3820   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3821   if (Val != Val2) return 0;
3822   
3823   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3824   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3825       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3826       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3827       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3828     return 0;
3829   
3830   // We can't fold (ugt x, C) & (sgt x, C2).
3831   if (!PredicatesFoldable(LHSCC, RHSCC))
3832     return 0;
3833     
3834   // Ensure that the larger constant is on the RHS.
3835   bool ShouldSwap;
3836   if (ICmpInst::isSignedPredicate(LHSCC) ||
3837       (ICmpInst::isEquality(LHSCC) && 
3838        ICmpInst::isSignedPredicate(RHSCC)))
3839     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3840   else
3841     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3842     
3843   if (ShouldSwap) {
3844     std::swap(LHS, RHS);
3845     std::swap(LHSCst, RHSCst);
3846     std::swap(LHSCC, RHSCC);
3847   }
3848
3849   // At this point, we know we have have two icmp instructions
3850   // comparing a value against two constants and and'ing the result
3851   // together.  Because of the above check, we know that we only have
3852   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3853   // (from the FoldICmpLogical check above), that the two constants 
3854   // are not equal and that the larger constant is on the RHS
3855   assert(LHSCst != RHSCst && "Compares not folded above?");
3856
3857   switch (LHSCC) {
3858   default: LLVM_UNREACHABLE("Unknown integer condition code!");
3859   case ICmpInst::ICMP_EQ:
3860     switch (RHSCC) {
3861     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3862     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3863     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3864     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3865       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3866     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3867     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3868     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3869       return ReplaceInstUsesWith(I, LHS);
3870     }
3871   case ICmpInst::ICMP_NE:
3872     switch (RHSCC) {
3873     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3874     case ICmpInst::ICMP_ULT:
3875       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3876         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3877       break;                        // (X != 13 & X u< 15) -> no change
3878     case ICmpInst::ICMP_SLT:
3879       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3880         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3881       break;                        // (X != 13 & X s< 15) -> no change
3882     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3883     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3884     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3885       return ReplaceInstUsesWith(I, RHS);
3886     case ICmpInst::ICMP_NE:
3887       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3888         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3889         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3890                                                      Val->getName()+".off");
3891         InsertNewInstBefore(Add, I);
3892         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3893                             Context->getConstantInt(Add->getType(), 1));
3894       }
3895       break;                        // (X != 13 & X != 15) -> no change
3896     }
3897     break;
3898   case ICmpInst::ICMP_ULT:
3899     switch (RHSCC) {
3900     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3901     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3902     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3903       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3904     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3905       break;
3906     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3907     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3908       return ReplaceInstUsesWith(I, LHS);
3909     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3910       break;
3911     }
3912     break;
3913   case ICmpInst::ICMP_SLT:
3914     switch (RHSCC) {
3915     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3916     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3917     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3918       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3919     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3920       break;
3921     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3922     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3923       return ReplaceInstUsesWith(I, LHS);
3924     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3925       break;
3926     }
3927     break;
3928   case ICmpInst::ICMP_UGT:
3929     switch (RHSCC) {
3930     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3931     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3932     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3933       return ReplaceInstUsesWith(I, RHS);
3934     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3935       break;
3936     case ICmpInst::ICMP_NE:
3937       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3938         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3939       break;                        // (X u> 13 & X != 15) -> no change
3940     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3941       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3942                              RHSCst, false, true, I);
3943     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3944       break;
3945     }
3946     break;
3947   case ICmpInst::ICMP_SGT:
3948     switch (RHSCC) {
3949     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3950     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3951     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3952       return ReplaceInstUsesWith(I, RHS);
3953     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3954       break;
3955     case ICmpInst::ICMP_NE:
3956       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3957         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3958       break;                        // (X s> 13 & X != 15) -> no change
3959     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3960       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3961                              RHSCst, true, true, I);
3962     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3963       break;
3964     }
3965     break;
3966   }
3967  
3968   return 0;
3969 }
3970
3971
3972 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3973   bool Changed = SimplifyCommutative(I);
3974   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3975
3976   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3977     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3978
3979   // and X, X = X
3980   if (Op0 == Op1)
3981     return ReplaceInstUsesWith(I, Op1);
3982
3983   // See if we can simplify any instructions used by the instruction whose sole 
3984   // purpose is to compute bits we don't care about.
3985   if (SimplifyDemandedInstructionBits(I))
3986     return &I;
3987   if (isa<VectorType>(I.getType())) {
3988     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3989       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3990         return ReplaceInstUsesWith(I, I.getOperand(0));
3991     } else if (isa<ConstantAggregateZero>(Op1)) {
3992       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3993     }
3994   }
3995
3996   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3997     const APInt& AndRHSMask = AndRHS->getValue();
3998     APInt NotAndRHS(~AndRHSMask);
3999
4000     // Optimize a variety of ((val OP C1) & C2) combinations...
4001     if (isa<BinaryOperator>(Op0)) {
4002       Instruction *Op0I = cast<Instruction>(Op0);
4003       Value *Op0LHS = Op0I->getOperand(0);
4004       Value *Op0RHS = Op0I->getOperand(1);
4005       switch (Op0I->getOpcode()) {
4006       case Instruction::Xor:
4007       case Instruction::Or:
4008         // If the mask is only needed on one incoming arm, push it up.
4009         if (Op0I->hasOneUse()) {
4010           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4011             // Not masking anything out for the LHS, move to RHS.
4012             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4013                                                    Op0RHS->getName()+".masked");
4014             InsertNewInstBefore(NewRHS, I);
4015             return BinaryOperator::Create(
4016                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4017           }
4018           if (!isa<Constant>(Op0RHS) &&
4019               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4020             // Not masking anything out for the RHS, move to LHS.
4021             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4022                                                    Op0LHS->getName()+".masked");
4023             InsertNewInstBefore(NewLHS, I);
4024             return BinaryOperator::Create(
4025                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4026           }
4027         }
4028
4029         break;
4030       case Instruction::Add:
4031         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4032         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4033         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4034         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4035           return BinaryOperator::CreateAnd(V, AndRHS);
4036         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4037           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4038         break;
4039
4040       case Instruction::Sub:
4041         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4042         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4043         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4044         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4045           return BinaryOperator::CreateAnd(V, AndRHS);
4046
4047         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4048         // has 1's for all bits that the subtraction with A might affect.
4049         if (Op0I->hasOneUse()) {
4050           uint32_t BitWidth = AndRHSMask.getBitWidth();
4051           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4052           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4053
4054           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4055           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4056               MaskedValueIsZero(Op0LHS, Mask)) {
4057             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4058             InsertNewInstBefore(NewNeg, I);
4059             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4060           }
4061         }
4062         break;
4063
4064       case Instruction::Shl:
4065       case Instruction::LShr:
4066         // (1 << x) & 1 --> zext(x == 0)
4067         // (1 >> x) & 1 --> zext(x == 0)
4068         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4069           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4070                                     Op0RHS, Context->getNullValue(I.getType()));
4071           InsertNewInstBefore(NewICmp, I);
4072           return new ZExtInst(NewICmp, I.getType());
4073         }
4074         break;
4075       }
4076
4077       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4078         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4079           return Res;
4080     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4081       // If this is an integer truncation or change from signed-to-unsigned, and
4082       // if the source is an and/or with immediate, transform it.  This
4083       // frequently occurs for bitfield accesses.
4084       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4085         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4086             CastOp->getNumOperands() == 2)
4087           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4088             if (CastOp->getOpcode() == Instruction::And) {
4089               // Change: and (cast (and X, C1) to T), C2
4090               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4091               // This will fold the two constants together, which may allow 
4092               // other simplifications.
4093               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4094                 CastOp->getOperand(0), I.getType(), 
4095                 CastOp->getName()+".shrunk");
4096               NewCast = InsertNewInstBefore(NewCast, I);
4097               // trunc_or_bitcast(C1)&C2
4098               Constant *C3 =
4099                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4100               C3 = Context->getConstantExprAnd(C3, AndRHS);
4101               return BinaryOperator::CreateAnd(NewCast, C3);
4102             } else if (CastOp->getOpcode() == Instruction::Or) {
4103               // Change: and (cast (or X, C1) to T), C2
4104               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4105               Constant *C3 =
4106                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4107               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4108                 // trunc(C1)&C2
4109                 return ReplaceInstUsesWith(I, AndRHS);
4110             }
4111           }
4112       }
4113     }
4114
4115     // Try to fold constant and into select arguments.
4116     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4117       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4118         return R;
4119     if (isa<PHINode>(Op0))
4120       if (Instruction *NV = FoldOpIntoPhi(I))
4121         return NV;
4122   }
4123
4124   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4125   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4126
4127   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4128     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4129
4130   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4131   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4132     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4133                                                I.getName()+".demorgan");
4134     InsertNewInstBefore(Or, I);
4135     return BinaryOperator::CreateNot(*Context, Or);
4136   }
4137   
4138   {
4139     Value *A = 0, *B = 0, *C = 0, *D = 0;
4140     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4141       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4142         return ReplaceInstUsesWith(I, Op1);
4143     
4144       // (A|B) & ~(A&B) -> A^B
4145       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4146         if ((A == C && B == D) || (A == D && B == C))
4147           return BinaryOperator::CreateXor(A, B);
4148       }
4149     }
4150     
4151     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4152       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4153         return ReplaceInstUsesWith(I, Op0);
4154
4155       // ~(A&B) & (A|B) -> A^B
4156       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4157         if ((A == C && B == D) || (A == D && B == C))
4158           return BinaryOperator::CreateXor(A, B);
4159       }
4160     }
4161     
4162     if (Op0->hasOneUse() &&
4163         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4164       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4165         I.swapOperands();     // Simplify below
4166         std::swap(Op0, Op1);
4167       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4168         cast<BinaryOperator>(Op0)->swapOperands();
4169         I.swapOperands();     // Simplify below
4170         std::swap(Op0, Op1);
4171       }
4172     }
4173
4174     if (Op1->hasOneUse() &&
4175         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4176       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4177         cast<BinaryOperator>(Op1)->swapOperands();
4178         std::swap(A, B);
4179       }
4180       if (A == Op0) {                                // A&(A^B) -> A & ~B
4181         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4182         InsertNewInstBefore(NotB, I);
4183         return BinaryOperator::CreateAnd(A, NotB);
4184       }
4185     }
4186
4187     // (A&((~A)|B)) -> A&B
4188     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4189         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4190       return BinaryOperator::CreateAnd(A, Op1);
4191     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4192         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4193       return BinaryOperator::CreateAnd(A, Op0);
4194   }
4195   
4196   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4197     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4198     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4199       return R;
4200
4201     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4202       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4203         return Res;
4204   }
4205
4206   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4207   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4208     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4209       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4210         const Type *SrcTy = Op0C->getOperand(0)->getType();
4211         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4212             // Only do this if the casts both really cause code to be generated.
4213             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4214                               I.getType(), TD) &&
4215             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4216                               I.getType(), TD)) {
4217           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4218                                                          Op1C->getOperand(0),
4219                                                          I.getName());
4220           InsertNewInstBefore(NewOp, I);
4221           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4222         }
4223       }
4224     
4225   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4226   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4227     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4228       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4229           SI0->getOperand(1) == SI1->getOperand(1) &&
4230           (SI0->hasOneUse() || SI1->hasOneUse())) {
4231         Instruction *NewOp =
4232           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4233                                                         SI1->getOperand(0),
4234                                                         SI0->getName()), I);
4235         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4236                                       SI1->getOperand(1));
4237       }
4238   }
4239
4240   // If and'ing two fcmp, try combine them into one.
4241   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4242     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4243       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4244           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4245         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4246         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4247           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4248             // If either of the constants are nans, then the whole thing returns
4249             // false.
4250             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4251               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4252             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4253                                 LHS->getOperand(0), RHS->getOperand(0));
4254           }
4255       } else {
4256         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4257         FCmpInst::Predicate Op0CC, Op1CC;
4258         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4259                   m_Value(Op0RHS)), *Context) &&
4260             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4261                   m_Value(Op1RHS)), *Context)) {
4262           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4263             // Swap RHS operands to match LHS.
4264             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4265             std::swap(Op1LHS, Op1RHS);
4266           }
4267           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4268             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4269             if (Op0CC == Op1CC)
4270               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4271                                   Op0LHS, Op0RHS);
4272             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4273                      Op1CC == FCmpInst::FCMP_FALSE)
4274               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4275             else if (Op0CC == FCmpInst::FCMP_TRUE)
4276               return ReplaceInstUsesWith(I, Op1);
4277             else if (Op1CC == FCmpInst::FCMP_TRUE)
4278               return ReplaceInstUsesWith(I, Op0);
4279             bool Op0Ordered;
4280             bool Op1Ordered;
4281             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4282             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4283             if (Op1Pred == 0) {
4284               std::swap(Op0, Op1);
4285               std::swap(Op0Pred, Op1Pred);
4286               std::swap(Op0Ordered, Op1Ordered);
4287             }
4288             if (Op0Pred == 0) {
4289               // uno && ueq -> uno && (uno || eq) -> ueq
4290               // ord && olt -> ord && (ord && lt) -> olt
4291               if (Op0Ordered == Op1Ordered)
4292                 return ReplaceInstUsesWith(I, Op1);
4293               // uno && oeq -> uno && (ord && eq) -> false
4294               // uno && ord -> false
4295               if (!Op0Ordered)
4296                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4297               // ord && ueq -> ord && (uno || eq) -> oeq
4298               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4299                                                     Op0LHS, Op0RHS, Context));
4300             }
4301           }
4302         }
4303       }
4304     }
4305   }
4306
4307   return Changed ? &I : 0;
4308 }
4309
4310 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4311 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4312 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4313 /// the expression came from the corresponding "byte swapped" byte in some other
4314 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4315 /// we know that the expression deposits the low byte of %X into the high byte
4316 /// of the bswap result and that all other bytes are zero.  This expression is
4317 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4318 /// match.
4319 ///
4320 /// This function returns true if the match was unsuccessful and false if so.
4321 /// On entry to the function the "OverallLeftShift" is a signed integer value
4322 /// indicating the number of bytes that the subexpression is later shifted.  For
4323 /// example, if the expression is later right shifted by 16 bits, the
4324 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4325 /// byte of ByteValues is actually being set.
4326 ///
4327 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4328 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4329 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4330 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4331 /// always in the local (OverallLeftShift) coordinate space.
4332 ///
4333 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4334                               SmallVector<Value*, 8> &ByteValues) {
4335   if (Instruction *I = dyn_cast<Instruction>(V)) {
4336     // If this is an or instruction, it may be an inner node of the bswap.
4337     if (I->getOpcode() == Instruction::Or) {
4338       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4339                                ByteValues) ||
4340              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4341                                ByteValues);
4342     }
4343   
4344     // If this is a logical shift by a constant multiple of 8, recurse with
4345     // OverallLeftShift and ByteMask adjusted.
4346     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4347       unsigned ShAmt = 
4348         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4349       // Ensure the shift amount is defined and of a byte value.
4350       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4351         return true;
4352
4353       unsigned ByteShift = ShAmt >> 3;
4354       if (I->getOpcode() == Instruction::Shl) {
4355         // X << 2 -> collect(X, +2)
4356         OverallLeftShift += ByteShift;
4357         ByteMask >>= ByteShift;
4358       } else {
4359         // X >>u 2 -> collect(X, -2)
4360         OverallLeftShift -= ByteShift;
4361         ByteMask <<= ByteShift;
4362         ByteMask &= (~0U >> (32-ByteValues.size()));
4363       }
4364
4365       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4366       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4367
4368       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4369                                ByteValues);
4370     }
4371
4372     // If this is a logical 'and' with a mask that clears bytes, clear the
4373     // corresponding bytes in ByteMask.
4374     if (I->getOpcode() == Instruction::And &&
4375         isa<ConstantInt>(I->getOperand(1))) {
4376       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4377       unsigned NumBytes = ByteValues.size();
4378       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4379       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4380       
4381       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4382         // If this byte is masked out by a later operation, we don't care what
4383         // the and mask is.
4384         if ((ByteMask & (1 << i)) == 0)
4385           continue;
4386         
4387         // If the AndMask is all zeros for this byte, clear the bit.
4388         APInt MaskB = AndMask & Byte;
4389         if (MaskB == 0) {
4390           ByteMask &= ~(1U << i);
4391           continue;
4392         }
4393         
4394         // If the AndMask is not all ones for this byte, it's not a bytezap.
4395         if (MaskB != Byte)
4396           return true;
4397
4398         // Otherwise, this byte is kept.
4399       }
4400
4401       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4402                                ByteValues);
4403     }
4404   }
4405   
4406   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4407   // the input value to the bswap.  Some observations: 1) if more than one byte
4408   // is demanded from this input, then it could not be successfully assembled
4409   // into a byteswap.  At least one of the two bytes would not be aligned with
4410   // their ultimate destination.
4411   if (!isPowerOf2_32(ByteMask)) return true;
4412   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4413   
4414   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4415   // is demanded, it needs to go into byte 0 of the result.  This means that the
4416   // byte needs to be shifted until it lands in the right byte bucket.  The
4417   // shift amount depends on the position: if the byte is coming from the high
4418   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4419   // low part, it must be shifted left.
4420   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4421   if (InputByteNo < ByteValues.size()/2) {
4422     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423       return true;
4424   } else {
4425     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4426       return true;
4427   }
4428   
4429   // If the destination byte value is already defined, the values are or'd
4430   // together, which isn't a bswap (unless it's an or of the same bits).
4431   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4432     return true;
4433   ByteValues[DestByteNo] = V;
4434   return false;
4435 }
4436
4437 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4438 /// If so, insert the new bswap intrinsic and return it.
4439 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4440   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4441   if (!ITy || ITy->getBitWidth() % 16 || 
4442       // ByteMask only allows up to 32-byte values.
4443       ITy->getBitWidth() > 32*8) 
4444     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4445   
4446   /// ByteValues - For each byte of the result, we keep track of which value
4447   /// defines each byte.
4448   SmallVector<Value*, 8> ByteValues;
4449   ByteValues.resize(ITy->getBitWidth()/8);
4450     
4451   // Try to find all the pieces corresponding to the bswap.
4452   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4453   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4454     return 0;
4455   
4456   // Check to see if all of the bytes come from the same value.
4457   Value *V = ByteValues[0];
4458   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4459   
4460   // Check to make sure that all of the bytes come from the same value.
4461   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4462     if (ByteValues[i] != V)
4463       return 0;
4464   const Type *Tys[] = { ITy };
4465   Module *M = I.getParent()->getParent()->getParent();
4466   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4467   return CallInst::Create(F, V);
4468 }
4469
4470 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4471 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4472 /// we can simplify this expression to "cond ? C : D or B".
4473 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4474                                          Value *C, Value *D,
4475                                          LLVMContext *Context) {
4476   // If A is not a select of -1/0, this cannot match.
4477   Value *Cond = 0;
4478   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4479     return 0;
4480
4481   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4482   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4483     return SelectInst::Create(Cond, C, B);
4484   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4485     return SelectInst::Create(Cond, C, B);
4486   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4487   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4488     return SelectInst::Create(Cond, C, D);
4489   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4490     return SelectInst::Create(Cond, C, D);
4491   return 0;
4492 }
4493
4494 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4495 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4496                                          ICmpInst *LHS, ICmpInst *RHS) {
4497   Value *Val, *Val2;
4498   ConstantInt *LHSCst, *RHSCst;
4499   ICmpInst::Predicate LHSCC, RHSCC;
4500   
4501   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4502   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4503              m_ConstantInt(LHSCst)), *Context) ||
4504       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4505              m_ConstantInt(RHSCst)), *Context))
4506     return 0;
4507   
4508   // From here on, we only handle:
4509   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4510   if (Val != Val2) return 0;
4511   
4512   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4513   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4514       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4515       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4516       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4517     return 0;
4518   
4519   // We can't fold (ugt x, C) | (sgt x, C2).
4520   if (!PredicatesFoldable(LHSCC, RHSCC))
4521     return 0;
4522   
4523   // Ensure that the larger constant is on the RHS.
4524   bool ShouldSwap;
4525   if (ICmpInst::isSignedPredicate(LHSCC) ||
4526       (ICmpInst::isEquality(LHSCC) && 
4527        ICmpInst::isSignedPredicate(RHSCC)))
4528     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4529   else
4530     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4531   
4532   if (ShouldSwap) {
4533     std::swap(LHS, RHS);
4534     std::swap(LHSCst, RHSCst);
4535     std::swap(LHSCC, RHSCC);
4536   }
4537   
4538   // At this point, we know we have have two icmp instructions
4539   // comparing a value against two constants and or'ing the result
4540   // together.  Because of the above check, we know that we only have
4541   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4542   // FoldICmpLogical check above), that the two constants are not
4543   // equal.
4544   assert(LHSCst != RHSCst && "Compares not folded above?");
4545
4546   switch (LHSCC) {
4547   default: LLVM_UNREACHABLE("Unknown integer condition code!");
4548   case ICmpInst::ICMP_EQ:
4549     switch (RHSCC) {
4550     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4551     case ICmpInst::ICMP_EQ:
4552       if (LHSCst == SubOne(RHSCst, Context)) {
4553         // (X == 13 | X == 14) -> X-13 <u 2
4554         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4555         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4556                                                      Val->getName()+".off");
4557         InsertNewInstBefore(Add, I);
4558         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4559         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4560       }
4561       break;                         // (X == 13 | X == 15) -> no change
4562     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4563     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4564       break;
4565     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4566     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4567     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4568       return ReplaceInstUsesWith(I, RHS);
4569     }
4570     break;
4571   case ICmpInst::ICMP_NE:
4572     switch (RHSCC) {
4573     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4574     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4575     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4576     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4577       return ReplaceInstUsesWith(I, LHS);
4578     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4579     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4580     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4581       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4582     }
4583     break;
4584   case ICmpInst::ICMP_ULT:
4585     switch (RHSCC) {
4586     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4587     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4588       break;
4589     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4590       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4591       // this can cause overflow.
4592       if (RHSCst->isMaxValue(false))
4593         return ReplaceInstUsesWith(I, LHS);
4594       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4595                              false, false, I);
4596     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4597       break;
4598     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4599     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4600       return ReplaceInstUsesWith(I, RHS);
4601     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4602       break;
4603     }
4604     break;
4605   case ICmpInst::ICMP_SLT:
4606     switch (RHSCC) {
4607     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4608     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4609       break;
4610     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4611       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4612       // this can cause overflow.
4613       if (RHSCst->isMaxValue(true))
4614         return ReplaceInstUsesWith(I, LHS);
4615       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4616                              true, false, I);
4617     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4618       break;
4619     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4620     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4621       return ReplaceInstUsesWith(I, RHS);
4622     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4623       break;
4624     }
4625     break;
4626   case ICmpInst::ICMP_UGT:
4627     switch (RHSCC) {
4628     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4629     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4630     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4631       return ReplaceInstUsesWith(I, LHS);
4632     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4633       break;
4634     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4635     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4636       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4637     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4638       break;
4639     }
4640     break;
4641   case ICmpInst::ICMP_SGT:
4642     switch (RHSCC) {
4643     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4644     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4645     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4646       return ReplaceInstUsesWith(I, LHS);
4647     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4648       break;
4649     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4650     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4651       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4652     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4653       break;
4654     }
4655     break;
4656   }
4657   return 0;
4658 }
4659
4660 /// FoldOrWithConstants - This helper function folds:
4661 ///
4662 ///     ((A | B) & C1) | (B & C2)
4663 ///
4664 /// into:
4665 /// 
4666 ///     (A & C1) | B
4667 ///
4668 /// when the XOR of the two constants is "all ones" (-1).
4669 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4670                                                Value *A, Value *B, Value *C) {
4671   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4672   if (!CI1) return 0;
4673
4674   Value *V1 = 0;
4675   ConstantInt *CI2 = 0;
4676   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4677
4678   APInt Xor = CI1->getValue() ^ CI2->getValue();
4679   if (!Xor.isAllOnesValue()) return 0;
4680
4681   if (V1 == A || V1 == B) {
4682     Instruction *NewOp =
4683       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4684     return BinaryOperator::CreateOr(NewOp, V1);
4685   }
4686
4687   return 0;
4688 }
4689
4690 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4691   bool Changed = SimplifyCommutative(I);
4692   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4693
4694   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4695     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4696
4697   // or X, X = X
4698   if (Op0 == Op1)
4699     return ReplaceInstUsesWith(I, Op0);
4700
4701   // See if we can simplify any instructions used by the instruction whose sole 
4702   // purpose is to compute bits we don't care about.
4703   if (SimplifyDemandedInstructionBits(I))
4704     return &I;
4705   if (isa<VectorType>(I.getType())) {
4706     if (isa<ConstantAggregateZero>(Op1)) {
4707       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4708     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4709       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4710         return ReplaceInstUsesWith(I, I.getOperand(1));
4711     }
4712   }
4713
4714   // or X, -1 == -1
4715   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4716     ConstantInt *C1 = 0; Value *X = 0;
4717     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4718     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4719         isOnlyUse(Op0)) {
4720       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4721       InsertNewInstBefore(Or, I);
4722       Or->takeName(Op0);
4723       return BinaryOperator::CreateAnd(Or, 
4724                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4725     }
4726
4727     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4728     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4729         isOnlyUse(Op0)) {
4730       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4731       InsertNewInstBefore(Or, I);
4732       Or->takeName(Op0);
4733       return BinaryOperator::CreateXor(Or,
4734                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4735     }
4736
4737     // Try to fold constant and into select arguments.
4738     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4739       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4740         return R;
4741     if (isa<PHINode>(Op0))
4742       if (Instruction *NV = FoldOpIntoPhi(I))
4743         return NV;
4744   }
4745
4746   Value *A = 0, *B = 0;
4747   ConstantInt *C1 = 0, *C2 = 0;
4748
4749   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4750     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4751       return ReplaceInstUsesWith(I, Op1);
4752   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4753     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4754       return ReplaceInstUsesWith(I, Op0);
4755
4756   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4757   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4758   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4759       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4760       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4761        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4762     if (Instruction *BSwap = MatchBSwap(I))
4763       return BSwap;
4764   }
4765   
4766   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4767   if (Op0->hasOneUse() &&
4768       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4769       MaskedValueIsZero(Op1, C1->getValue())) {
4770     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4771     InsertNewInstBefore(NOr, I);
4772     NOr->takeName(Op0);
4773     return BinaryOperator::CreateXor(NOr, C1);
4774   }
4775
4776   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4777   if (Op1->hasOneUse() &&
4778       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4779       MaskedValueIsZero(Op0, C1->getValue())) {
4780     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4781     InsertNewInstBefore(NOr, I);
4782     NOr->takeName(Op0);
4783     return BinaryOperator::CreateXor(NOr, C1);
4784   }
4785
4786   // (A & C)|(B & D)
4787   Value *C = 0, *D = 0;
4788   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4789       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4790     Value *V1 = 0, *V2 = 0, *V3 = 0;
4791     C1 = dyn_cast<ConstantInt>(C);
4792     C2 = dyn_cast<ConstantInt>(D);
4793     if (C1 && C2) {  // (A & C1)|(B & C2)
4794       // If we have: ((V + N) & C1) | (V & C2)
4795       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4796       // replace with V+N.
4797       if (C1->getValue() == ~C2->getValue()) {
4798         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4799             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4800           // Add commutes, try both ways.
4801           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4802             return ReplaceInstUsesWith(I, A);
4803           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4804             return ReplaceInstUsesWith(I, A);
4805         }
4806         // Or commutes, try both ways.
4807         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4808             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4809           // Add commutes, try both ways.
4810           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4811             return ReplaceInstUsesWith(I, B);
4812           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4813             return ReplaceInstUsesWith(I, B);
4814         }
4815       }
4816       V1 = 0; V2 = 0; V3 = 0;
4817     }
4818     
4819     // Check to see if we have any common things being and'ed.  If so, find the
4820     // terms for V1 & (V2|V3).
4821     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4822       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4823         V1 = A, V2 = C, V3 = D;
4824       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4825         V1 = A, V2 = B, V3 = C;
4826       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4827         V1 = C, V2 = A, V3 = D;
4828       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4829         V1 = C, V2 = A, V3 = B;
4830       
4831       if (V1) {
4832         Value *Or =
4833           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4834         return BinaryOperator::CreateAnd(V1, Or);
4835       }
4836     }
4837
4838     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4839     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4840       return Match;
4841     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4842       return Match;
4843     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4844       return Match;
4845     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4846       return Match;
4847
4848     // ((A&~B)|(~A&B)) -> A^B
4849     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4850          match(B, m_Not(m_Specific(A)), *Context)))
4851       return BinaryOperator::CreateXor(A, D);
4852     // ((~B&A)|(~A&B)) -> A^B
4853     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4854          match(B, m_Not(m_Specific(C)), *Context)))
4855       return BinaryOperator::CreateXor(C, D);
4856     // ((A&~B)|(B&~A)) -> A^B
4857     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4858          match(D, m_Not(m_Specific(A)), *Context)))
4859       return BinaryOperator::CreateXor(A, B);
4860     // ((~B&A)|(B&~A)) -> A^B
4861     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4862          match(D, m_Not(m_Specific(C)), *Context)))
4863       return BinaryOperator::CreateXor(C, B);
4864   }
4865   
4866   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4867   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4868     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4869       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4870           SI0->getOperand(1) == SI1->getOperand(1) &&
4871           (SI0->hasOneUse() || SI1->hasOneUse())) {
4872         Instruction *NewOp =
4873         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4874                                                      SI1->getOperand(0),
4875                                                      SI0->getName()), I);
4876         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4877                                       SI1->getOperand(1));
4878       }
4879   }
4880
4881   // ((A|B)&1)|(B&-2) -> (A&1) | B
4882   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4883       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4884     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4885     if (Ret) return Ret;
4886   }
4887   // (B&-2)|((A|B)&1) -> (A&1) | B
4888   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4889       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4890     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4891     if (Ret) return Ret;
4892   }
4893
4894   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4895     if (A == Op1)   // ~A | A == -1
4896       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4897   } else {
4898     A = 0;
4899   }
4900   // Note, A is still live here!
4901   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4902     if (Op0 == B)
4903       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4904
4905     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4906     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4907       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4908                                               I.getName()+".demorgan"), I);
4909       return BinaryOperator::CreateNot(*Context, And);
4910     }
4911   }
4912
4913   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4914   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4915     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4916       return R;
4917
4918     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4919       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4920         return Res;
4921   }
4922     
4923   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4924   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4925     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4926       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4927         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4928             !isa<ICmpInst>(Op1C->getOperand(0))) {
4929           const Type *SrcTy = Op0C->getOperand(0)->getType();
4930           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4931               // Only do this if the casts both really cause code to be
4932               // generated.
4933               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4934                                 I.getType(), TD) &&
4935               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4936                                 I.getType(), TD)) {
4937             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4938                                                           Op1C->getOperand(0),
4939                                                           I.getName());
4940             InsertNewInstBefore(NewOp, I);
4941             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4942           }
4943         }
4944       }
4945   }
4946   
4947     
4948   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4949   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4950     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4951       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4952           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4953           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4954         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4955           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4956             // If either of the constants are nans, then the whole thing returns
4957             // true.
4958             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4959               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4960             
4961             // Otherwise, no need to compare the two constants, compare the
4962             // rest.
4963             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4964                                 LHS->getOperand(0), RHS->getOperand(0));
4965           }
4966       } else {
4967         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4968         FCmpInst::Predicate Op0CC, Op1CC;
4969         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4970                   m_Value(Op0RHS)), *Context) &&
4971             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4972                   m_Value(Op1RHS)), *Context)) {
4973           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4974             // Swap RHS operands to match LHS.
4975             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4976             std::swap(Op1LHS, Op1RHS);
4977           }
4978           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4979             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4980             if (Op0CC == Op1CC)
4981               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4982                                   Op0LHS, Op0RHS);
4983             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4984                      Op1CC == FCmpInst::FCMP_TRUE)
4985               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4986             else if (Op0CC == FCmpInst::FCMP_FALSE)
4987               return ReplaceInstUsesWith(I, Op1);
4988             else if (Op1CC == FCmpInst::FCMP_FALSE)
4989               return ReplaceInstUsesWith(I, Op0);
4990             bool Op0Ordered;
4991             bool Op1Ordered;
4992             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4993             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4994             if (Op0Ordered == Op1Ordered) {
4995               // If both are ordered or unordered, return a new fcmp with
4996               // or'ed predicates.
4997               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4998                                        Op0LHS, Op0RHS, Context);
4999               if (Instruction *I = dyn_cast<Instruction>(RV))
5000                 return I;
5001               // Otherwise, it's a constant boolean value...
5002               return ReplaceInstUsesWith(I, RV);
5003             }
5004           }
5005         }
5006       }
5007     }
5008   }
5009
5010   return Changed ? &I : 0;
5011 }
5012
5013 namespace {
5014
5015 // XorSelf - Implements: X ^ X --> 0
5016 struct XorSelf {
5017   Value *RHS;
5018   XorSelf(Value *rhs) : RHS(rhs) {}
5019   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5020   Instruction *apply(BinaryOperator &Xor) const {
5021     return &Xor;
5022   }
5023 };
5024
5025 }
5026
5027 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5028   bool Changed = SimplifyCommutative(I);
5029   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5030
5031   if (isa<UndefValue>(Op1)) {
5032     if (isa<UndefValue>(Op0))
5033       // Handle undef ^ undef -> 0 special case. This is a common
5034       // idiom (misuse).
5035       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5036     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5037   }
5038
5039   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5040   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5041     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5042     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5043   }
5044   
5045   // See if we can simplify any instructions used by the instruction whose sole 
5046   // purpose is to compute bits we don't care about.
5047   if (SimplifyDemandedInstructionBits(I))
5048     return &I;
5049   if (isa<VectorType>(I.getType()))
5050     if (isa<ConstantAggregateZero>(Op1))
5051       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5052
5053   // Is this a ~ operation?
5054   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5055     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5056     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5057     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5058       if (Op0I->getOpcode() == Instruction::And || 
5059           Op0I->getOpcode() == Instruction::Or) {
5060         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5061         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5062           Instruction *NotY =
5063             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5064                                       Op0I->getOperand(1)->getName()+".not");
5065           InsertNewInstBefore(NotY, I);
5066           if (Op0I->getOpcode() == Instruction::And)
5067             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5068           else
5069             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5070         }
5071       }
5072     }
5073   }
5074   
5075   
5076   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5077     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5078       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5079       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5080         return new ICmpInst(*Context, ICI->getInversePredicate(),
5081                             ICI->getOperand(0), ICI->getOperand(1));
5082
5083       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5084         return new FCmpInst(*Context, FCI->getInversePredicate(),
5085                             FCI->getOperand(0), FCI->getOperand(1));
5086     }
5087
5088     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5089     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5090       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5091         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5092           Instruction::CastOps Opcode = Op0C->getOpcode();
5093           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5094             if (RHS == Context->getConstantExprCast(Opcode, 
5095                                              Context->getConstantIntTrue(),
5096                                              Op0C->getDestTy())) {
5097               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5098                                      *Context,
5099                                      CI->getOpcode(), CI->getInversePredicate(),
5100                                      CI->getOperand(0), CI->getOperand(1)), I);
5101               NewCI->takeName(CI);
5102               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5103             }
5104           }
5105         }
5106       }
5107     }
5108
5109     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5110       // ~(c-X) == X-c-1 == X+(-c-1)
5111       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5112         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5113           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5114           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5115                                       Context->getConstantInt(I.getType(), 1));
5116           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5117         }
5118           
5119       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5120         if (Op0I->getOpcode() == Instruction::Add) {
5121           // ~(X-c) --> (-c-1)-X
5122           if (RHS->isAllOnesValue()) {
5123             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5124             return BinaryOperator::CreateSub(
5125                            Context->getConstantExprSub(NegOp0CI,
5126                                       Context->getConstantInt(I.getType(), 1)),
5127                                       Op0I->getOperand(0));
5128           } else if (RHS->getValue().isSignBit()) {
5129             // (X + C) ^ signbit -> (X + C + signbit)
5130             Constant *C =
5131                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5132             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5133
5134           }
5135         } else if (Op0I->getOpcode() == Instruction::Or) {
5136           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5137           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5138             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5139             // Anything in both C1 and C2 is known to be zero, remove it from
5140             // NewRHS.
5141             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5142             NewRHS = Context->getConstantExprAnd(NewRHS, 
5143                                        Context->getConstantExprNot(CommonBits));
5144             AddToWorkList(Op0I);
5145             I.setOperand(0, Op0I->getOperand(0));
5146             I.setOperand(1, NewRHS);
5147             return &I;
5148           }
5149         }
5150       }
5151     }
5152
5153     // Try to fold constant and into select arguments.
5154     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5155       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5156         return R;
5157     if (isa<PHINode>(Op0))
5158       if (Instruction *NV = FoldOpIntoPhi(I))
5159         return NV;
5160   }
5161
5162   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5163     if (X == Op1)
5164       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5165
5166   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5167     if (X == Op0)
5168       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5169
5170   
5171   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5172   if (Op1I) {
5173     Value *A, *B;
5174     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5175       if (A == Op0) {              // B^(B|A) == (A|B)^B
5176         Op1I->swapOperands();
5177         I.swapOperands();
5178         std::swap(Op0, Op1);
5179       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5180         I.swapOperands();     // Simplified below.
5181         std::swap(Op0, Op1);
5182       }
5183     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5184       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5185     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5186       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5187     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5188                Op1I->hasOneUse()){
5189       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5190         Op1I->swapOperands();
5191         std::swap(A, B);
5192       }
5193       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5194         I.swapOperands();     // Simplified below.
5195         std::swap(Op0, Op1);
5196       }
5197     }
5198   }
5199   
5200   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5201   if (Op0I) {
5202     Value *A, *B;
5203     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5204         Op0I->hasOneUse()) {
5205       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5206         std::swap(A, B);
5207       if (B == Op1) {                                // (A|B)^B == A & ~B
5208         Instruction *NotB =
5209           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5210                                                         Op1, "tmp"), I);
5211         return BinaryOperator::CreateAnd(A, NotB);
5212       }
5213     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5214       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5215     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5216       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5217     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5218                Op0I->hasOneUse()){
5219       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5220         std::swap(A, B);
5221       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5222           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5223         Instruction *N =
5224           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5225         return BinaryOperator::CreateAnd(N, Op1);
5226       }
5227     }
5228   }
5229   
5230   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5231   if (Op0I && Op1I && Op0I->isShift() && 
5232       Op0I->getOpcode() == Op1I->getOpcode() && 
5233       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5234       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5235     Instruction *NewOp =
5236       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5237                                                     Op1I->getOperand(0),
5238                                                     Op0I->getName()), I);
5239     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5240                                   Op1I->getOperand(1));
5241   }
5242     
5243   if (Op0I && Op1I) {
5244     Value *A, *B, *C, *D;
5245     // (A & B)^(A | B) -> A ^ B
5246     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5247         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5248       if ((A == C && B == D) || (A == D && B == C)) 
5249         return BinaryOperator::CreateXor(A, B);
5250     }
5251     // (A | B)^(A & B) -> A ^ B
5252     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5253         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5254       if ((A == C && B == D) || (A == D && B == C)) 
5255         return BinaryOperator::CreateXor(A, B);
5256     }
5257     
5258     // (A & B)^(C & D)
5259     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5260         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5261         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5262       // (X & Y)^(X & Y) -> (Y^Z) & X
5263       Value *X = 0, *Y = 0, *Z = 0;
5264       if (A == C)
5265         X = A, Y = B, Z = D;
5266       else if (A == D)
5267         X = A, Y = B, Z = C;
5268       else if (B == C)
5269         X = B, Y = A, Z = D;
5270       else if (B == D)
5271         X = B, Y = A, Z = C;
5272       
5273       if (X) {
5274         Instruction *NewOp =
5275         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5276         return BinaryOperator::CreateAnd(NewOp, X);
5277       }
5278     }
5279   }
5280     
5281   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5282   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5283     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5284       return R;
5285
5286   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5287   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5288     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5289       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5290         const Type *SrcTy = Op0C->getOperand(0)->getType();
5291         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5292             // Only do this if the casts both really cause code to be generated.
5293             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5294                               I.getType(), TD) &&
5295             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5296                               I.getType(), TD)) {
5297           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5298                                                          Op1C->getOperand(0),
5299                                                          I.getName());
5300           InsertNewInstBefore(NewOp, I);
5301           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5302         }
5303       }
5304   }
5305
5306   return Changed ? &I : 0;
5307 }
5308
5309 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5310                                    LLVMContext *Context) {
5311   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5312 }
5313
5314 static bool HasAddOverflow(ConstantInt *Result,
5315                            ConstantInt *In1, ConstantInt *In2,
5316                            bool IsSigned) {
5317   if (IsSigned)
5318     if (In2->getValue().isNegative())
5319       return Result->getValue().sgt(In1->getValue());
5320     else
5321       return Result->getValue().slt(In1->getValue());
5322   else
5323     return Result->getValue().ult(In1->getValue());
5324 }
5325
5326 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5329                             Constant *In2, LLVMContext *Context,
5330                             bool IsSigned = false) {
5331   Result = Context->getConstantExprAdd(In1, In2);
5332
5333   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5335       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5336       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5337                          ExtractElement(In1, Idx, Context),
5338                          ExtractElement(In2, Idx, Context),
5339                          IsSigned))
5340         return true;
5341     }
5342     return false;
5343   }
5344
5345   return HasAddOverflow(cast<ConstantInt>(Result),
5346                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5347                         IsSigned);
5348 }
5349
5350 static bool HasSubOverflow(ConstantInt *Result,
5351                            ConstantInt *In1, ConstantInt *In2,
5352                            bool IsSigned) {
5353   if (IsSigned)
5354     if (In2->getValue().isNegative())
5355       return Result->getValue().slt(In1->getValue());
5356     else
5357       return Result->getValue().sgt(In1->getValue());
5358   else
5359     return Result->getValue().ugt(In1->getValue());
5360 }
5361
5362 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5363 /// overflowed for this type.
5364 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5365                             Constant *In2, LLVMContext *Context,
5366                             bool IsSigned = false) {
5367   Result = Context->getConstantExprSub(In1, In2);
5368
5369   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5370     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5371       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5372       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5373                          ExtractElement(In1, Idx, Context),
5374                          ExtractElement(In2, Idx, Context),
5375                          IsSigned))
5376         return true;
5377     }
5378     return false;
5379   }
5380
5381   return HasSubOverflow(cast<ConstantInt>(Result),
5382                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5383                         IsSigned);
5384 }
5385
5386 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5387 /// code necessary to compute the offset from the base pointer (without adding
5388 /// in the base pointer).  Return the result as a signed integer of intptr size.
5389 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5390   TargetData &TD = IC.getTargetData();
5391   gep_type_iterator GTI = gep_type_begin(GEP);
5392   const Type *IntPtrTy = TD.getIntPtrType();
5393   LLVMContext *Context = IC.getContext();
5394   Value *Result = Context->getNullValue(IntPtrTy);
5395
5396   // Build a mask for high order bits.
5397   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5398   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5399
5400   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5401        ++i, ++GTI) {
5402     Value *Op = *i;
5403     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5404     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5405       if (OpC->isZero()) continue;
5406       
5407       // Handle a struct index, which adds its field offset to the pointer.
5408       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5409         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5410         
5411         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5412           Result = 
5413              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5414         else
5415           Result = IC.InsertNewInstBefore(
5416                    BinaryOperator::CreateAdd(Result,
5417                                         Context->getConstantInt(IntPtrTy, Size),
5418                                              GEP->getName()+".offs"), I);
5419         continue;
5420       }
5421       
5422       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5423       Constant *OC =
5424               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5425       Scale = Context->getConstantExprMul(OC, Scale);
5426       if (Constant *RC = dyn_cast<Constant>(Result))
5427         Result = Context->getConstantExprAdd(RC, Scale);
5428       else {
5429         // Emit an add instruction.
5430         Result = IC.InsertNewInstBefore(
5431            BinaryOperator::CreateAdd(Result, Scale,
5432                                      GEP->getName()+".offs"), I);
5433       }
5434       continue;
5435     }
5436     // Convert to correct type.
5437     if (Op->getType() != IntPtrTy) {
5438       if (Constant *OpC = dyn_cast<Constant>(Op))
5439         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5440       else
5441         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5442                                                                 true,
5443                                                       Op->getName()+".c"), I);
5444     }
5445     if (Size != 1) {
5446       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5447       if (Constant *OpC = dyn_cast<Constant>(Op))
5448         Op = Context->getConstantExprMul(OpC, Scale);
5449       else    // We'll let instcombine(mul) convert this to a shl if possible.
5450         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5451                                                   GEP->getName()+".idx"), I);
5452     }
5453
5454     // Emit an add instruction.
5455     if (isa<Constant>(Op) && isa<Constant>(Result))
5456       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5457                                     cast<Constant>(Result));
5458     else
5459       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5460                                                   GEP->getName()+".offs"), I);
5461   }
5462   return Result;
5463 }
5464
5465
5466 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5467 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5468 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5469 /// complex, and scales are involved.  The above expression would also be legal
5470 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5471 /// later form is less amenable to optimization though, and we are allowed to
5472 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5473 ///
5474 /// If we can't emit an optimized form for this expression, this returns null.
5475 /// 
5476 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5477                                           InstCombiner &IC) {
5478   TargetData &TD = IC.getTargetData();
5479   gep_type_iterator GTI = gep_type_begin(GEP);
5480
5481   // Check to see if this gep only has a single variable index.  If so, and if
5482   // any constant indices are a multiple of its scale, then we can compute this
5483   // in terms of the scale of the variable index.  For example, if the GEP
5484   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5485   // because the expression will cross zero at the same point.
5486   unsigned i, e = GEP->getNumOperands();
5487   int64_t Offset = 0;
5488   for (i = 1; i != e; ++i, ++GTI) {
5489     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5490       // Compute the aggregate offset of constant indices.
5491       if (CI->isZero()) continue;
5492
5493       // Handle a struct index, which adds its field offset to the pointer.
5494       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496       } else {
5497         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5498         Offset += Size*CI->getSExtValue();
5499       }
5500     } else {
5501       // Found our variable index.
5502       break;
5503     }
5504   }
5505   
5506   // If there are no variable indices, we must have a constant offset, just
5507   // evaluate it the general way.
5508   if (i == e) return 0;
5509   
5510   Value *VariableIdx = GEP->getOperand(i);
5511   // Determine the scale factor of the variable element.  For example, this is
5512   // 4 if the variable index is into an array of i32.
5513   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5514   
5515   // Verify that there are no other variable indices.  If so, emit the hard way.
5516   for (++i, ++GTI; i != e; ++i, ++GTI) {
5517     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5518     if (!CI) return 0;
5519    
5520     // Compute the aggregate offset of constant indices.
5521     if (CI->isZero()) continue;
5522     
5523     // Handle a struct index, which adds its field offset to the pointer.
5524     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5525       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5526     } else {
5527       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5528       Offset += Size*CI->getSExtValue();
5529     }
5530   }
5531   
5532   // Okay, we know we have a single variable index, which must be a
5533   // pointer/array/vector index.  If there is no offset, life is simple, return
5534   // the index.
5535   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5536   if (Offset == 0) {
5537     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5538     // we don't need to bother extending: the extension won't affect where the
5539     // computation crosses zero.
5540     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5541       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5542                                   VariableIdx->getNameStart(), &I);
5543     return VariableIdx;
5544   }
5545   
5546   // Otherwise, there is an index.  The computation we will do will be modulo
5547   // the pointer size, so get it.
5548   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5549   
5550   Offset &= PtrSizeMask;
5551   VariableScale &= PtrSizeMask;
5552
5553   // To do this transformation, any constant index must be a multiple of the
5554   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5555   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5556   // multiple of the variable scale.
5557   int64_t NewOffs = Offset / (int64_t)VariableScale;
5558   if (Offset != NewOffs*(int64_t)VariableScale)
5559     return 0;
5560
5561   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5562   const Type *IntPtrTy = TD.getIntPtrType();
5563   if (VariableIdx->getType() != IntPtrTy)
5564     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5565                                               true /*SExt*/, 
5566                                               VariableIdx->getNameStart(), &I);
5567   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5568   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5569 }
5570
5571
5572 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5573 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5574 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5575                                        ICmpInst::Predicate Cond,
5576                                        Instruction &I) {
5577   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5578
5579   // Look through bitcasts.
5580   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5581     RHS = BCI->getOperand(0);
5582
5583   Value *PtrBase = GEPLHS->getOperand(0);
5584   if (PtrBase == RHS) {
5585     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5586     // This transformation (ignoring the base and scales) is valid because we
5587     // know pointers can't overflow.  See if we can output an optimized form.
5588     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5589     
5590     // If not, synthesize the offset the hard way.
5591     if (Offset == 0)
5592       Offset = EmitGEPOffset(GEPLHS, I, *this);
5593     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5594                         Context->getNullValue(Offset->getType()));
5595   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5596     // If the base pointers are different, but the indices are the same, just
5597     // compare the base pointer.
5598     if (PtrBase != GEPRHS->getOperand(0)) {
5599       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5600       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5601                         GEPRHS->getOperand(0)->getType();
5602       if (IndicesTheSame)
5603         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5604           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5605             IndicesTheSame = false;
5606             break;
5607           }
5608
5609       // If all indices are the same, just compare the base pointers.
5610       if (IndicesTheSame)
5611         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5612                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5613
5614       // Otherwise, the base pointers are different and the indices are
5615       // different, bail out.
5616       return 0;
5617     }
5618
5619     // If one of the GEPs has all zero indices, recurse.
5620     bool AllZeros = true;
5621     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5622       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5623           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5624         AllZeros = false;
5625         break;
5626       }
5627     if (AllZeros)
5628       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5629                           ICmpInst::getSwappedPredicate(Cond), I);
5630
5631     // If the other GEP has all zero indices, recurse.
5632     AllZeros = true;
5633     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5635           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5636         AllZeros = false;
5637         break;
5638       }
5639     if (AllZeros)
5640       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5641
5642     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5643       // If the GEPs only differ by one index, compare it.
5644       unsigned NumDifferences = 0;  // Keep track of # differences.
5645       unsigned DiffOperand = 0;     // The operand that differs.
5646       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5647         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5648           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5649                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5650             // Irreconcilable differences.
5651             NumDifferences = 2;
5652             break;
5653           } else {
5654             if (NumDifferences++) break;
5655             DiffOperand = i;
5656           }
5657         }
5658
5659       if (NumDifferences == 0)   // SAME GEP?
5660         return ReplaceInstUsesWith(I, // No comparison is needed here.
5661                                    Context->getConstantInt(Type::Int1Ty,
5662                                              ICmpInst::isTrueWhenEqual(Cond)));
5663
5664       else if (NumDifferences == 1) {
5665         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5666         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5667         // Make sure we do a signed comparison here.
5668         return new ICmpInst(*Context,
5669                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5670       }
5671     }
5672
5673     // Only lower this if the icmp is the only user of the GEP or if we expect
5674     // the result to fold to a constant!
5675     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5676         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5677       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5678       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5679       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5680       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5681     }
5682   }
5683   return 0;
5684 }
5685
5686 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5687 ///
5688 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5689                                                 Instruction *LHSI,
5690                                                 Constant *RHSC) {
5691   if (!isa<ConstantFP>(RHSC)) return 0;
5692   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5693   
5694   // Get the width of the mantissa.  We don't want to hack on conversions that
5695   // might lose information from the integer, e.g. "i64 -> float"
5696   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5697   if (MantissaWidth == -1) return 0;  // Unknown.
5698   
5699   // Check to see that the input is converted from an integer type that is small
5700   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5701   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5702   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5703   
5704   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5705   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5706   if (LHSUnsigned)
5707     ++InputSize;
5708   
5709   // If the conversion would lose info, don't hack on this.
5710   if ((int)InputSize > MantissaWidth)
5711     return 0;
5712   
5713   // Otherwise, we can potentially simplify the comparison.  We know that it
5714   // will always come through as an integer value and we know the constant is
5715   // not a NAN (it would have been previously simplified).
5716   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5717   
5718   ICmpInst::Predicate Pred;
5719   switch (I.getPredicate()) {
5720   default: LLVM_UNREACHABLE("Unexpected predicate!");
5721   case FCmpInst::FCMP_UEQ:
5722   case FCmpInst::FCMP_OEQ:
5723     Pred = ICmpInst::ICMP_EQ;
5724     break;
5725   case FCmpInst::FCMP_UGT:
5726   case FCmpInst::FCMP_OGT:
5727     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5728     break;
5729   case FCmpInst::FCMP_UGE:
5730   case FCmpInst::FCMP_OGE:
5731     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5732     break;
5733   case FCmpInst::FCMP_ULT:
5734   case FCmpInst::FCMP_OLT:
5735     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5736     break;
5737   case FCmpInst::FCMP_ULE:
5738   case FCmpInst::FCMP_OLE:
5739     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5740     break;
5741   case FCmpInst::FCMP_UNE:
5742   case FCmpInst::FCMP_ONE:
5743     Pred = ICmpInst::ICMP_NE;
5744     break;
5745   case FCmpInst::FCMP_ORD:
5746     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5747   case FCmpInst::FCMP_UNO:
5748     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5749   }
5750   
5751   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5752   
5753   // Now we know that the APFloat is a normal number, zero or inf.
5754   
5755   // See if the FP constant is too large for the integer.  For example,
5756   // comparing an i8 to 300.0.
5757   unsigned IntWidth = IntTy->getScalarSizeInBits();
5758   
5759   if (!LHSUnsigned) {
5760     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5761     // and large values.
5762     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5763     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5764                           APFloat::rmNearestTiesToEven);
5765     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5766       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5767           Pred == ICmpInst::ICMP_SLE)
5768         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5769       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5770     }
5771   } else {
5772     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5773     // +INF and large values.
5774     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5775     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5776                           APFloat::rmNearestTiesToEven);
5777     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5778       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5779           Pred == ICmpInst::ICMP_ULE)
5780         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5781       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5782     }
5783   }
5784   
5785   if (!LHSUnsigned) {
5786     // See if the RHS value is < SignedMin.
5787     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5788     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5789                           APFloat::rmNearestTiesToEven);
5790     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5791       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5792           Pred == ICmpInst::ICMP_SGE)
5793         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5794       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5795     }
5796   }
5797
5798   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5799   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5800   // casting the FP value to the integer value and back, checking for equality.
5801   // Don't do this for zero, because -0.0 is not fractional.
5802   Constant *RHSInt = LHSUnsigned
5803     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5804     : Context->getConstantExprFPToSI(RHSC, IntTy);
5805   if (!RHS.isZero()) {
5806     bool Equal = LHSUnsigned
5807       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5808       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5809     if (!Equal) {
5810       // If we had a comparison against a fractional value, we have to adjust
5811       // the compare predicate and sometimes the value.  RHSC is rounded towards
5812       // zero at this point.
5813       switch (Pred) {
5814       default: LLVM_UNREACHABLE("Unexpected integer comparison!");
5815       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5816         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5817       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5818         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5819       case ICmpInst::ICMP_ULE:
5820         // (float)int <= 4.4   --> int <= 4
5821         // (float)int <= -4.4  --> false
5822         if (RHS.isNegative())
5823           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5824         break;
5825       case ICmpInst::ICMP_SLE:
5826         // (float)int <= 4.4   --> int <= 4
5827         // (float)int <= -4.4  --> int < -4
5828         if (RHS.isNegative())
5829           Pred = ICmpInst::ICMP_SLT;
5830         break;
5831       case ICmpInst::ICMP_ULT:
5832         // (float)int < -4.4   --> false
5833         // (float)int < 4.4    --> int <= 4
5834         if (RHS.isNegative())
5835           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5836         Pred = ICmpInst::ICMP_ULE;
5837         break;
5838       case ICmpInst::ICMP_SLT:
5839         // (float)int < -4.4   --> int < -4
5840         // (float)int < 4.4    --> int <= 4
5841         if (!RHS.isNegative())
5842           Pred = ICmpInst::ICMP_SLE;
5843         break;
5844       case ICmpInst::ICMP_UGT:
5845         // (float)int > 4.4    --> int > 4
5846         // (float)int > -4.4   --> true
5847         if (RHS.isNegative())
5848           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5849         break;
5850       case ICmpInst::ICMP_SGT:
5851         // (float)int > 4.4    --> int > 4
5852         // (float)int > -4.4   --> int >= -4
5853         if (RHS.isNegative())
5854           Pred = ICmpInst::ICMP_SGE;
5855         break;
5856       case ICmpInst::ICMP_UGE:
5857         // (float)int >= -4.4   --> true
5858         // (float)int >= 4.4    --> int > 4
5859         if (!RHS.isNegative())
5860           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5861         Pred = ICmpInst::ICMP_UGT;
5862         break;
5863       case ICmpInst::ICMP_SGE:
5864         // (float)int >= -4.4   --> int >= -4
5865         // (float)int >= 4.4    --> int > 4
5866         if (!RHS.isNegative())
5867           Pred = ICmpInst::ICMP_SGT;
5868         break;
5869       }
5870     }
5871   }
5872
5873   // Lower this FP comparison into an appropriate integer version of the
5874   // comparison.
5875   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5876 }
5877
5878 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5879   bool Changed = SimplifyCompare(I);
5880   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5881
5882   // Fold trivial predicates.
5883   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5884     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5885   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5886     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5887   
5888   // Simplify 'fcmp pred X, X'
5889   if (Op0 == Op1) {
5890     switch (I.getPredicate()) {
5891     default: LLVM_UNREACHABLE("Unknown predicate!");
5892     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5893     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5894     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5895       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5896     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5897     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5898     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5899       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5900       
5901     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5902     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5903     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5904     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5905       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5906       I.setPredicate(FCmpInst::FCMP_UNO);
5907       I.setOperand(1, Context->getNullValue(Op0->getType()));
5908       return &I;
5909       
5910     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5911     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5912     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5913     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5914       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5915       I.setPredicate(FCmpInst::FCMP_ORD);
5916       I.setOperand(1, Context->getNullValue(Op0->getType()));
5917       return &I;
5918     }
5919   }
5920     
5921   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5922     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5923
5924   // Handle fcmp with constant RHS
5925   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5926     // If the constant is a nan, see if we can fold the comparison based on it.
5927     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5928       if (CFP->getValueAPF().isNaN()) {
5929         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5930           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5931         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5932                "Comparison must be either ordered or unordered!");
5933         // True if unordered.
5934         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5935       }
5936     }
5937     
5938     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5939       switch (LHSI->getOpcode()) {
5940       case Instruction::PHI:
5941         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5942         // block.  If in the same block, we're encouraging jump threading.  If
5943         // not, we are just pessimizing the code by making an i1 phi.
5944         if (LHSI->getParent() == I.getParent())
5945           if (Instruction *NV = FoldOpIntoPhi(I))
5946             return NV;
5947         break;
5948       case Instruction::SIToFP:
5949       case Instruction::UIToFP:
5950         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5951           return NV;
5952         break;
5953       case Instruction::Select:
5954         // If either operand of the select is a constant, we can fold the
5955         // comparison into the select arms, which will cause one to be
5956         // constant folded and the select turned into a bitwise or.
5957         Value *Op1 = 0, *Op2 = 0;
5958         if (LHSI->hasOneUse()) {
5959           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5960             // Fold the known value into the constant operand.
5961             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5962             // Insert a new FCmp of the other select operand.
5963             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5964                                                       LHSI->getOperand(2), RHSC,
5965                                                       I.getName()), I);
5966           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5967             // Fold the known value into the constant operand.
5968             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5969             // Insert a new FCmp of the other select operand.
5970             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5971                                                       LHSI->getOperand(1), RHSC,
5972                                                       I.getName()), I);
5973           }
5974         }
5975
5976         if (Op1)
5977           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5978         break;
5979       }
5980   }
5981
5982   return Changed ? &I : 0;
5983 }
5984
5985 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5986   bool Changed = SimplifyCompare(I);
5987   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5988   const Type *Ty = Op0->getType();
5989
5990   // icmp X, X
5991   if (Op0 == Op1)
5992     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5993                                                    I.isTrueWhenEqual()));
5994
5995   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5996     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5997   
5998   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5999   // addresses never equal each other!  We already know that Op0 != Op1.
6000   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6001        isa<ConstantPointerNull>(Op0)) &&
6002       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6003        isa<ConstantPointerNull>(Op1)))
6004     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
6005                                                    !I.isTrueWhenEqual()));
6006
6007   // icmp's with boolean values can always be turned into bitwise operations
6008   if (Ty == Type::Int1Ty) {
6009     switch (I.getPredicate()) {
6010     default: LLVM_UNREACHABLE("Invalid icmp instruction!");
6011     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6012       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6013       InsertNewInstBefore(Xor, I);
6014       return BinaryOperator::CreateNot(*Context, Xor);
6015     }
6016     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6017       return BinaryOperator::CreateXor(Op0, Op1);
6018
6019     case ICmpInst::ICMP_UGT:
6020       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6021       // FALL THROUGH
6022     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6023       Instruction *Not = BinaryOperator::CreateNot(*Context,
6024                                                    Op0, I.getName()+"tmp");
6025       InsertNewInstBefore(Not, I);
6026       return BinaryOperator::CreateAnd(Not, Op1);
6027     }
6028     case ICmpInst::ICMP_SGT:
6029       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6030       // FALL THROUGH
6031     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6032       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6033                                                    Op1, I.getName()+"tmp");
6034       InsertNewInstBefore(Not, I);
6035       return BinaryOperator::CreateAnd(Not, Op0);
6036     }
6037     case ICmpInst::ICMP_UGE:
6038       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6039       // FALL THROUGH
6040     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6041       Instruction *Not = BinaryOperator::CreateNot(*Context,
6042                                                    Op0, I.getName()+"tmp");
6043       InsertNewInstBefore(Not, I);
6044       return BinaryOperator::CreateOr(Not, Op1);
6045     }
6046     case ICmpInst::ICMP_SGE:
6047       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6048       // FALL THROUGH
6049     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6050       Instruction *Not = BinaryOperator::CreateNot(*Context,
6051                                                    Op1, I.getName()+"tmp");
6052       InsertNewInstBefore(Not, I);
6053       return BinaryOperator::CreateOr(Not, Op0);
6054     }
6055     }
6056   }
6057
6058   unsigned BitWidth = 0;
6059   if (TD)
6060     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6061   else if (Ty->isIntOrIntVector())
6062     BitWidth = Ty->getScalarSizeInBits();
6063
6064   bool isSignBit = false;
6065
6066   // See if we are doing a comparison with a constant.
6067   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6068     Value *A = 0, *B = 0;
6069     
6070     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6071     if (I.isEquality() && CI->isNullValue() &&
6072         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6073       // (icmp cond A B) if cond is equality
6074       return new ICmpInst(*Context, I.getPredicate(), A, B);
6075     }
6076     
6077     // If we have an icmp le or icmp ge instruction, turn it into the
6078     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6079     // them being folded in the code below.
6080     switch (I.getPredicate()) {
6081     default: break;
6082     case ICmpInst::ICMP_ULE:
6083       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6084         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6085       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6086                           AddOne(CI, Context));
6087     case ICmpInst::ICMP_SLE:
6088       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6089         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6090       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6091                           AddOne(CI, Context));
6092     case ICmpInst::ICMP_UGE:
6093       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6094         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6095       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6096                           SubOne(CI, Context));
6097     case ICmpInst::ICMP_SGE:
6098       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6099         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6100       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6101                           SubOne(CI, Context));
6102     }
6103     
6104     // If this comparison is a normal comparison, it demands all
6105     // bits, if it is a sign bit comparison, it only demands the sign bit.
6106     bool UnusedBit;
6107     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6108   }
6109
6110   // See if we can fold the comparison based on range information we can get
6111   // by checking whether bits are known to be zero or one in the input.
6112   if (BitWidth != 0) {
6113     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6114     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6115
6116     if (SimplifyDemandedBits(I.getOperandUse(0),
6117                              isSignBit ? APInt::getSignBit(BitWidth)
6118                                        : APInt::getAllOnesValue(BitWidth),
6119                              Op0KnownZero, Op0KnownOne, 0))
6120       return &I;
6121     if (SimplifyDemandedBits(I.getOperandUse(1),
6122                              APInt::getAllOnesValue(BitWidth),
6123                              Op1KnownZero, Op1KnownOne, 0))
6124       return &I;
6125
6126     // Given the known and unknown bits, compute a range that the LHS could be
6127     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6128     // EQ and NE we use unsigned values.
6129     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6130     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6131     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6132       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6133                                              Op0Min, Op0Max);
6134       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6135                                              Op1Min, Op1Max);
6136     } else {
6137       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6138                                                Op0Min, Op0Max);
6139       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6140                                                Op1Min, Op1Max);
6141     }
6142
6143     // If Min and Max are known to be the same, then SimplifyDemandedBits
6144     // figured out that the LHS is a constant.  Just constant fold this now so
6145     // that code below can assume that Min != Max.
6146     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6147       return new ICmpInst(*Context, I.getPredicate(),
6148                           Context->getConstantInt(Op0Min), Op1);
6149     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6150       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6151                           Context->getConstantInt(Op1Min));
6152
6153     // Based on the range information we know about the LHS, see if we can
6154     // simplify this comparison.  For example, (x&4) < 8  is always true.
6155     switch (I.getPredicate()) {
6156     default: LLVM_UNREACHABLE("Unknown icmp opcode!");
6157     case ICmpInst::ICMP_EQ:
6158       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6159         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6160       break;
6161     case ICmpInst::ICMP_NE:
6162       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6163         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6164       break;
6165     case ICmpInst::ICMP_ULT:
6166       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6167         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6168       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6169         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6170       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6171         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6172       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6173         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6174           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6175                               SubOne(CI, Context));
6176
6177         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6178         if (CI->isMinValue(true))
6179           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6180                            Context->getAllOnesValue(Op0->getType()));
6181       }
6182       break;
6183     case ICmpInst::ICMP_UGT:
6184       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6185         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6186       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6187         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6188
6189       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6190         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6191       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6192         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6193           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6194                               AddOne(CI, Context));
6195
6196         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6197         if (CI->isMaxValue(true))
6198           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6199                               Context->getNullValue(Op0->getType()));
6200       }
6201       break;
6202     case ICmpInst::ICMP_SLT:
6203       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6204         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6205       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6206         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6207       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6208         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6209       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6210         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6211           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6212                               SubOne(CI, Context));
6213       }
6214       break;
6215     case ICmpInst::ICMP_SGT:
6216       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6217         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6218       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6219         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6220
6221       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6222         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6223       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6224         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6225           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6226                               AddOne(CI, Context));
6227       }
6228       break;
6229     case ICmpInst::ICMP_SGE:
6230       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6231       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6232         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6233       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6234         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6235       break;
6236     case ICmpInst::ICMP_SLE:
6237       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6238       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6239         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6240       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6241         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6242       break;
6243     case ICmpInst::ICMP_UGE:
6244       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6245       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6246         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6247       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6248         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6249       break;
6250     case ICmpInst::ICMP_ULE:
6251       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6252       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6253         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6254       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6255         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6256       break;
6257     }
6258
6259     // Turn a signed comparison into an unsigned one if both operands
6260     // are known to have the same sign.
6261     if (I.isSignedPredicate() &&
6262         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6263          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6264       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6265   }
6266
6267   // Test if the ICmpInst instruction is used exclusively by a select as
6268   // part of a minimum or maximum operation. If so, refrain from doing
6269   // any other folding. This helps out other analyses which understand
6270   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6271   // and CodeGen. And in this case, at least one of the comparison
6272   // operands has at least one user besides the compare (the select),
6273   // which would often largely negate the benefit of folding anyway.
6274   if (I.hasOneUse())
6275     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6276       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6277           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6278         return 0;
6279
6280   // See if we are doing a comparison between a constant and an instruction that
6281   // can be folded into the comparison.
6282   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6283     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6284     // instruction, see if that instruction also has constants so that the 
6285     // instruction can be folded into the icmp 
6286     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6288         return Res;
6289   }
6290
6291   // Handle icmp with constant (but not simple integer constant) RHS
6292   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6293     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6294       switch (LHSI->getOpcode()) {
6295       case Instruction::GetElementPtr:
6296         if (RHSC->isNullValue()) {
6297           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6298           bool isAllZeros = true;
6299           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6300             if (!isa<Constant>(LHSI->getOperand(i)) ||
6301                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6302               isAllZeros = false;
6303               break;
6304             }
6305           if (isAllZeros)
6306             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6307                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6308         }
6309         break;
6310
6311       case Instruction::PHI:
6312         // Only fold icmp into the PHI if the phi and fcmp are in the same
6313         // block.  If in the same block, we're encouraging jump threading.  If
6314         // not, we are just pessimizing the code by making an i1 phi.
6315         if (LHSI->getParent() == I.getParent())
6316           if (Instruction *NV = FoldOpIntoPhi(I))
6317             return NV;
6318         break;
6319       case Instruction::Select: {
6320         // If either operand of the select is a constant, we can fold the
6321         // comparison into the select arms, which will cause one to be
6322         // constant folded and the select turned into a bitwise or.
6323         Value *Op1 = 0, *Op2 = 0;
6324         if (LHSI->hasOneUse()) {
6325           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6326             // Fold the known value into the constant operand.
6327             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6328             // Insert a new ICmp of the other select operand.
6329             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6330                                                    LHSI->getOperand(2), RHSC,
6331                                                    I.getName()), I);
6332           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6333             // Fold the known value into the constant operand.
6334             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6335             // Insert a new ICmp of the other select operand.
6336             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6337                                                    LHSI->getOperand(1), RHSC,
6338                                                    I.getName()), I);
6339           }
6340         }
6341
6342         if (Op1)
6343           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6344         break;
6345       }
6346       case Instruction::Malloc:
6347         // If we have (malloc != null), and if the malloc has a single use, we
6348         // can assume it is successful and remove the malloc.
6349         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6350           AddToWorkList(LHSI);
6351           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6352                                                          !I.isTrueWhenEqual()));
6353         }
6354         break;
6355       }
6356   }
6357
6358   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6359   if (User *GEP = dyn_castGetElementPtr(Op0))
6360     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6361       return NI;
6362   if (User *GEP = dyn_castGetElementPtr(Op1))
6363     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6364                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6365       return NI;
6366
6367   // Test to see if the operands of the icmp are casted versions of other
6368   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6369   // now.
6370   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6371     if (isa<PointerType>(Op0->getType()) && 
6372         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6373       // We keep moving the cast from the left operand over to the right
6374       // operand, where it can often be eliminated completely.
6375       Op0 = CI->getOperand(0);
6376
6377       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6378       // so eliminate it as well.
6379       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6380         Op1 = CI2->getOperand(0);
6381
6382       // If Op1 is a constant, we can fold the cast into the constant.
6383       if (Op0->getType() != Op1->getType()) {
6384         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6385           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6386         } else {
6387           // Otherwise, cast the RHS right before the icmp
6388           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6389         }
6390       }
6391       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6392     }
6393   }
6394   
6395   if (isa<CastInst>(Op0)) {
6396     // Handle the special case of: icmp (cast bool to X), <cst>
6397     // This comes up when you have code like
6398     //   int X = A < B;
6399     //   if (X) ...
6400     // For generality, we handle any zero-extension of any operand comparison
6401     // with a constant or another cast from the same type.
6402     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6403       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6404         return R;
6405   }
6406   
6407   // See if it's the same type of instruction on the left and right.
6408   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6409     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6410       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6411           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6412         switch (Op0I->getOpcode()) {
6413         default: break;
6414         case Instruction::Add:
6415         case Instruction::Sub:
6416         case Instruction::Xor:
6417           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6418             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6419                                 Op1I->getOperand(0));
6420           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6421           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422             if (CI->getValue().isSignBit()) {
6423               ICmpInst::Predicate Pred = I.isSignedPredicate()
6424                                              ? I.getUnsignedPredicate()
6425                                              : I.getSignedPredicate();
6426               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6427                                   Op1I->getOperand(0));
6428             }
6429             
6430             if (CI->getValue().isMaxSignedValue()) {
6431               ICmpInst::Predicate Pred = I.isSignedPredicate()
6432                                              ? I.getUnsignedPredicate()
6433                                              : I.getSignedPredicate();
6434               Pred = I.getSwappedPredicate(Pred);
6435               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6436                                   Op1I->getOperand(0));
6437             }
6438           }
6439           break;
6440         case Instruction::Mul:
6441           if (!I.isEquality())
6442             break;
6443
6444           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6445             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6446             // Mask = -1 >> count-trailing-zeros(Cst).
6447             if (!CI->isZero() && !CI->isOne()) {
6448               const APInt &AP = CI->getValue();
6449               ConstantInt *Mask = Context->getConstantInt(
6450                                       APInt::getLowBitsSet(AP.getBitWidth(),
6451                                                            AP.getBitWidth() -
6452                                                       AP.countTrailingZeros()));
6453               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6454                                                             Mask);
6455               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6456                                                             Mask);
6457               InsertNewInstBefore(And1, I);
6458               InsertNewInstBefore(And2, I);
6459               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6460             }
6461           }
6462           break;
6463         }
6464       }
6465     }
6466   }
6467   
6468   // ~x < ~y --> y < x
6469   { Value *A, *B;
6470     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6471         match(Op1, m_Not(m_Value(B)), *Context))
6472       return new ICmpInst(*Context, I.getPredicate(), B, A);
6473   }
6474   
6475   if (I.isEquality()) {
6476     Value *A, *B, *C, *D;
6477     
6478     // -x == -y --> x == y
6479     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6480         match(Op1, m_Neg(m_Value(B)), *Context))
6481       return new ICmpInst(*Context, I.getPredicate(), A, B);
6482     
6483     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6484       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6485         Value *OtherVal = A == Op1 ? B : A;
6486         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6487                             Context->getNullValue(A->getType()));
6488       }
6489
6490       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6491         // A^c1 == C^c2 --> A == C^(c1^c2)
6492         ConstantInt *C1, *C2;
6493         if (match(B, m_ConstantInt(C1), *Context) &&
6494             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6495           Constant *NC = 
6496                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6497           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6498           return new ICmpInst(*Context, I.getPredicate(), A,
6499                               InsertNewInstBefore(Xor, I));
6500         }
6501         
6502         // A^B == A^D -> B == D
6503         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6504         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6505         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6506         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6507       }
6508     }
6509     
6510     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6511         (A == Op0 || B == Op0)) {
6512       // A == (A^B)  ->  B == 0
6513       Value *OtherVal = A == Op0 ? B : A;
6514       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6515                           Context->getNullValue(A->getType()));
6516     }
6517
6518     // (A-B) == A  ->  B == 0
6519     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6520       return new ICmpInst(*Context, I.getPredicate(), B, 
6521                           Context->getNullValue(B->getType()));
6522
6523     // A == (A-B)  ->  B == 0
6524     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6525       return new ICmpInst(*Context, I.getPredicate(), B,
6526                           Context->getNullValue(B->getType()));
6527     
6528     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6529     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6530         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6531         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6532       Value *X = 0, *Y = 0, *Z = 0;
6533       
6534       if (A == C) {
6535         X = B; Y = D; Z = A;
6536       } else if (A == D) {
6537         X = B; Y = C; Z = A;
6538       } else if (B == C) {
6539         X = A; Y = D; Z = B;
6540       } else if (B == D) {
6541         X = A; Y = C; Z = B;
6542       }
6543       
6544       if (X) {   // Build (X^Y) & Z
6545         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6546         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6547         I.setOperand(0, Op1);
6548         I.setOperand(1, Context->getNullValue(Op1->getType()));
6549         return &I;
6550       }
6551     }
6552   }
6553   return Changed ? &I : 0;
6554 }
6555
6556
6557 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6558 /// and CmpRHS are both known to be integer constants.
6559 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6560                                           ConstantInt *DivRHS) {
6561   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6562   const APInt &CmpRHSV = CmpRHS->getValue();
6563   
6564   // FIXME: If the operand types don't match the type of the divide 
6565   // then don't attempt this transform. The code below doesn't have the
6566   // logic to deal with a signed divide and an unsigned compare (and
6567   // vice versa). This is because (x /s C1) <s C2  produces different 
6568   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6569   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6570   // work. :(  The if statement below tests that condition and bails 
6571   // if it finds it. 
6572   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6573   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6574     return 0;
6575   if (DivRHS->isZero())
6576     return 0; // The ProdOV computation fails on divide by zero.
6577   if (DivIsSigned && DivRHS->isAllOnesValue())
6578     return 0; // The overflow computation also screws up here
6579   if (DivRHS->isOne())
6580     return 0; // Not worth bothering, and eliminates some funny cases
6581               // with INT_MIN.
6582
6583   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6584   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6585   // C2 (CI). By solving for X we can turn this into a range check 
6586   // instead of computing a divide. 
6587   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6588
6589   // Determine if the product overflows by seeing if the product is
6590   // not equal to the divide. Make sure we do the same kind of divide
6591   // as in the LHS instruction that we're folding. 
6592   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6593                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6594
6595   // Get the ICmp opcode
6596   ICmpInst::Predicate Pred = ICI.getPredicate();
6597
6598   // Figure out the interval that is being checked.  For example, a comparison
6599   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6600   // Compute this interval based on the constants involved and the signedness of
6601   // the compare/divide.  This computes a half-open interval, keeping track of
6602   // whether either value in the interval overflows.  After analysis each
6603   // overflow variable is set to 0 if it's corresponding bound variable is valid
6604   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6605   int LoOverflow = 0, HiOverflow = 0;
6606   Constant *LoBound = 0, *HiBound = 0;
6607   
6608   if (!DivIsSigned) {  // udiv
6609     // e.g. X/5 op 3  --> [15, 20)
6610     LoBound = Prod;
6611     HiOverflow = LoOverflow = ProdOV;
6612     if (!HiOverflow)
6613       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6614   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6615     if (CmpRHSV == 0) {       // (X / pos) op 0
6616       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6617       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6618                                                                     Context)));
6619       HiBound = DivRHS;
6620     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6621       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6622       HiOverflow = LoOverflow = ProdOV;
6623       if (!HiOverflow)
6624         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6625     } else {                       // (X / pos) op neg
6626       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6627       HiBound = AddOne(Prod, Context);
6628       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6629       if (!LoOverflow) {
6630         ConstantInt* DivNeg =
6631                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6632         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6633                                      true) ? -1 : 0;
6634        }
6635     }
6636   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6637     if (CmpRHSV == 0) {       // (X / neg) op 0
6638       // e.g. X/-5 op 0  --> [-4, 5)
6639       LoBound = AddOne(DivRHS, Context);
6640       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6641       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6642         HiOverflow = 1;            // [INTMIN+1, overflow)
6643         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6644       }
6645     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6646       // e.g. X/-5 op 3  --> [-19, -14)
6647       HiBound = AddOne(Prod, Context);
6648       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6649       if (!LoOverflow)
6650         LoOverflow = AddWithOverflow(LoBound, HiBound,
6651                                      DivRHS, Context, true) ? -1 : 0;
6652     } else {                       // (X / neg) op neg
6653       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6654       LoOverflow = HiOverflow = ProdOV;
6655       if (!HiOverflow)
6656         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6657     }
6658     
6659     // Dividing by a negative swaps the condition.  LT <-> GT
6660     Pred = ICmpInst::getSwappedPredicate(Pred);
6661   }
6662
6663   Value *X = DivI->getOperand(0);
6664   switch (Pred) {
6665   default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
6666   case ICmpInst::ICMP_EQ:
6667     if (LoOverflow && HiOverflow)
6668       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6669     else if (HiOverflow)
6670       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6671                           ICmpInst::ICMP_UGE, X, LoBound);
6672     else if (LoOverflow)
6673       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6674                           ICmpInst::ICMP_ULT, X, HiBound);
6675     else
6676       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6677   case ICmpInst::ICMP_NE:
6678     if (LoOverflow && HiOverflow)
6679       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6680     else if (HiOverflow)
6681       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6682                           ICmpInst::ICMP_ULT, X, LoBound);
6683     else if (LoOverflow)
6684       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6685                           ICmpInst::ICMP_UGE, X, HiBound);
6686     else
6687       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6688   case ICmpInst::ICMP_ULT:
6689   case ICmpInst::ICMP_SLT:
6690     if (LoOverflow == +1)   // Low bound is greater than input range.
6691       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6692     if (LoOverflow == -1)   // Low bound is less than input range.
6693       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6694     return new ICmpInst(*Context, Pred, X, LoBound);
6695   case ICmpInst::ICMP_UGT:
6696   case ICmpInst::ICMP_SGT:
6697     if (HiOverflow == +1)       // High bound greater than input range.
6698       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6699     else if (HiOverflow == -1)  // High bound less than input range.
6700       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6701     if (Pred == ICmpInst::ICMP_UGT)
6702       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6703     else
6704       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6705   }
6706 }
6707
6708
6709 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6710 ///
6711 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6712                                                           Instruction *LHSI,
6713                                                           ConstantInt *RHS) {
6714   const APInt &RHSV = RHS->getValue();
6715   
6716   switch (LHSI->getOpcode()) {
6717   case Instruction::Trunc:
6718     if (ICI.isEquality() && LHSI->hasOneUse()) {
6719       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6720       // of the high bits truncated out of x are known.
6721       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6722              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6723       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6724       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6725       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6726       
6727       // If all the high bits are known, we can do this xform.
6728       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6729         // Pull in the high bits from known-ones set.
6730         APInt NewRHS(RHS->getValue());
6731         NewRHS.zext(SrcBits);
6732         NewRHS |= KnownOne;
6733         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6734                             Context->getConstantInt(NewRHS));
6735       }
6736     }
6737     break;
6738       
6739   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6740     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6741       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6742       // fold the xor.
6743       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6744           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6745         Value *CompareVal = LHSI->getOperand(0);
6746         
6747         // If the sign bit of the XorCST is not set, there is no change to
6748         // the operation, just stop using the Xor.
6749         if (!XorCST->getValue().isNegative()) {
6750           ICI.setOperand(0, CompareVal);
6751           AddToWorkList(LHSI);
6752           return &ICI;
6753         }
6754         
6755         // Was the old condition true if the operand is positive?
6756         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6757         
6758         // If so, the new one isn't.
6759         isTrueIfPositive ^= true;
6760         
6761         if (isTrueIfPositive)
6762           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6763                               SubOne(RHS, Context));
6764         else
6765           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6766                               AddOne(RHS, Context));
6767       }
6768
6769       if (LHSI->hasOneUse()) {
6770         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6771         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6772           const APInt &SignBit = XorCST->getValue();
6773           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6774                                          ? ICI.getUnsignedPredicate()
6775                                          : ICI.getSignedPredicate();
6776           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6777                               Context->getConstantInt(RHSV ^ SignBit));
6778         }
6779
6780         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6781         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6782           const APInt &NotSignBit = XorCST->getValue();
6783           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6784                                          ? ICI.getUnsignedPredicate()
6785                                          : ICI.getSignedPredicate();
6786           Pred = ICI.getSwappedPredicate(Pred);
6787           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6788                               Context->getConstantInt(RHSV ^ NotSignBit));
6789         }
6790       }
6791     }
6792     break;
6793   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6794     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6795         LHSI->getOperand(0)->hasOneUse()) {
6796       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6797       
6798       // If the LHS is an AND of a truncating cast, we can widen the
6799       // and/compare to be the input width without changing the value
6800       // produced, eliminating a cast.
6801       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6802         // We can do this transformation if either the AND constant does not
6803         // have its sign bit set or if it is an equality comparison. 
6804         // Extending a relational comparison when we're checking the sign
6805         // bit would not work.
6806         if (Cast->hasOneUse() &&
6807             (ICI.isEquality() ||
6808              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6809           uint32_t BitWidth = 
6810             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6811           APInt NewCST = AndCST->getValue();
6812           NewCST.zext(BitWidth);
6813           APInt NewCI = RHSV;
6814           NewCI.zext(BitWidth);
6815           Instruction *NewAnd = 
6816             BinaryOperator::CreateAnd(Cast->getOperand(0),
6817                                Context->getConstantInt(NewCST),LHSI->getName());
6818           InsertNewInstBefore(NewAnd, ICI);
6819           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6820                               Context->getConstantInt(NewCI));
6821         }
6822       }
6823       
6824       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6825       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6826       // happens a LOT in code produced by the C front-end, for bitfield
6827       // access.
6828       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6829       if (Shift && !Shift->isShift())
6830         Shift = 0;
6831       
6832       ConstantInt *ShAmt;
6833       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6834       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6835       const Type *AndTy = AndCST->getType();          // Type of the and.
6836       
6837       // We can fold this as long as we can't shift unknown bits
6838       // into the mask.  This can only happen with signed shift
6839       // rights, as they sign-extend.
6840       if (ShAmt) {
6841         bool CanFold = Shift->isLogicalShift();
6842         if (!CanFold) {
6843           // To test for the bad case of the signed shr, see if any
6844           // of the bits shifted in could be tested after the mask.
6845           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6846           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6847           
6848           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6849           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6850                AndCST->getValue()) == 0)
6851             CanFold = true;
6852         }
6853         
6854         if (CanFold) {
6855           Constant *NewCst;
6856           if (Shift->getOpcode() == Instruction::Shl)
6857             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6858           else
6859             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6860           
6861           // Check to see if we are shifting out any of the bits being
6862           // compared.
6863           if (Context->getConstantExpr(Shift->getOpcode(),
6864                                        NewCst, ShAmt) != RHS) {
6865             // If we shifted bits out, the fold is not going to work out.
6866             // As a special case, check to see if this means that the
6867             // result is always true or false now.
6868             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6869               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6870             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6871               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6872           } else {
6873             ICI.setOperand(1, NewCst);
6874             Constant *NewAndCST;
6875             if (Shift->getOpcode() == Instruction::Shl)
6876               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6877             else
6878               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6879             LHSI->setOperand(1, NewAndCST);
6880             LHSI->setOperand(0, Shift->getOperand(0));
6881             AddToWorkList(Shift); // Shift is dead.
6882             AddUsesToWorkList(ICI);
6883             return &ICI;
6884           }
6885         }
6886       }
6887       
6888       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6889       // preferable because it allows the C<<Y expression to be hoisted out
6890       // of a loop if Y is invariant and X is not.
6891       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6892           ICI.isEquality() && !Shift->isArithmeticShift() &&
6893           !isa<Constant>(Shift->getOperand(0))) {
6894         // Compute C << Y.
6895         Value *NS;
6896         if (Shift->getOpcode() == Instruction::LShr) {
6897           NS = BinaryOperator::CreateShl(AndCST, 
6898                                          Shift->getOperand(1), "tmp");
6899         } else {
6900           // Insert a logical shift.
6901           NS = BinaryOperator::CreateLShr(AndCST,
6902                                           Shift->getOperand(1), "tmp");
6903         }
6904         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6905         
6906         // Compute X & (C << Y).
6907         Instruction *NewAnd = 
6908           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6909         InsertNewInstBefore(NewAnd, ICI);
6910         
6911         ICI.setOperand(0, NewAnd);
6912         return &ICI;
6913       }
6914     }
6915     break;
6916     
6917   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6918     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6919     if (!ShAmt) break;
6920     
6921     uint32_t TypeBits = RHSV.getBitWidth();
6922     
6923     // Check that the shift amount is in range.  If not, don't perform
6924     // undefined shifts.  When the shift is visited it will be
6925     // simplified.
6926     if (ShAmt->uge(TypeBits))
6927       break;
6928     
6929     if (ICI.isEquality()) {
6930       // If we are comparing against bits always shifted out, the
6931       // comparison cannot succeed.
6932       Constant *Comp =
6933         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6934                                                                  ShAmt);
6935       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6936         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6937         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6938         return ReplaceInstUsesWith(ICI, Cst);
6939       }
6940       
6941       if (LHSI->hasOneUse()) {
6942         // Otherwise strength reduce the shift into an and.
6943         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6944         Constant *Mask =
6945           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6946                                                        TypeBits-ShAmtVal));
6947         
6948         Instruction *AndI =
6949           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6950                                     Mask, LHSI->getName()+".mask");
6951         Value *And = InsertNewInstBefore(AndI, ICI);
6952         return new ICmpInst(*Context, ICI.getPredicate(), And,
6953                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6954       }
6955     }
6956     
6957     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6958     bool TrueIfSigned = false;
6959     if (LHSI->hasOneUse() &&
6960         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6961       // (X << 31) <s 0  --> (X&1) != 0
6962       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6963                                            (TypeBits-ShAmt->getZExtValue()-1));
6964       Instruction *AndI =
6965         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6966                                   Mask, LHSI->getName()+".mask");
6967       Value *And = InsertNewInstBefore(AndI, ICI);
6968       
6969       return new ICmpInst(*Context,
6970                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6971                           And, Context->getNullValue(And->getType()));
6972     }
6973     break;
6974   }
6975     
6976   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6977   case Instruction::AShr: {
6978     // Only handle equality comparisons of shift-by-constant.
6979     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6980     if (!ShAmt || !ICI.isEquality()) break;
6981
6982     // Check that the shift amount is in range.  If not, don't perform
6983     // undefined shifts.  When the shift is visited it will be
6984     // simplified.
6985     uint32_t TypeBits = RHSV.getBitWidth();
6986     if (ShAmt->uge(TypeBits))
6987       break;
6988     
6989     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6990       
6991     // If we are comparing against bits always shifted out, the
6992     // comparison cannot succeed.
6993     APInt Comp = RHSV << ShAmtVal;
6994     if (LHSI->getOpcode() == Instruction::LShr)
6995       Comp = Comp.lshr(ShAmtVal);
6996     else
6997       Comp = Comp.ashr(ShAmtVal);
6998     
6999     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7000       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7001       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
7002       return ReplaceInstUsesWith(ICI, Cst);
7003     }
7004     
7005     // Otherwise, check to see if the bits shifted out are known to be zero.
7006     // If so, we can compare against the unshifted value:
7007     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7008     if (LHSI->hasOneUse() &&
7009         MaskedValueIsZero(LHSI->getOperand(0), 
7010                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7011       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7012                           Context->getConstantExprShl(RHS, ShAmt));
7013     }
7014       
7015     if (LHSI->hasOneUse()) {
7016       // Otherwise strength reduce the shift into an and.
7017       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7018       Constant *Mask = Context->getConstantInt(Val);
7019       
7020       Instruction *AndI =
7021         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7022                                   Mask, LHSI->getName()+".mask");
7023       Value *And = InsertNewInstBefore(AndI, ICI);
7024       return new ICmpInst(*Context, ICI.getPredicate(), And,
7025                           Context->getConstantExprShl(RHS, ShAmt));
7026     }
7027     break;
7028   }
7029     
7030   case Instruction::SDiv:
7031   case Instruction::UDiv:
7032     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7033     // Fold this div into the comparison, producing a range check. 
7034     // Determine, based on the divide type, what the range is being 
7035     // checked.  If there is an overflow on the low or high side, remember 
7036     // it, otherwise compute the range [low, hi) bounding the new value.
7037     // See: InsertRangeTest above for the kinds of replacements possible.
7038     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7039       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7040                                           DivRHS))
7041         return R;
7042     break;
7043
7044   case Instruction::Add:
7045     // Fold: icmp pred (add, X, C1), C2
7046
7047     if (!ICI.isEquality()) {
7048       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7049       if (!LHSC) break;
7050       const APInt &LHSV = LHSC->getValue();
7051
7052       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7053                             .subtract(LHSV);
7054
7055       if (ICI.isSignedPredicate()) {
7056         if (CR.getLower().isSignBit()) {
7057           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7058                               Context->getConstantInt(CR.getUpper()));
7059         } else if (CR.getUpper().isSignBit()) {
7060           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7061                               Context->getConstantInt(CR.getLower()));
7062         }
7063       } else {
7064         if (CR.getLower().isMinValue()) {
7065           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7066                               Context->getConstantInt(CR.getUpper()));
7067         } else if (CR.getUpper().isMinValue()) {
7068           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7069                               Context->getConstantInt(CR.getLower()));
7070         }
7071       }
7072     }
7073     break;
7074   }
7075   
7076   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7077   if (ICI.isEquality()) {
7078     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7079     
7080     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7081     // the second operand is a constant, simplify a bit.
7082     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7083       switch (BO->getOpcode()) {
7084       case Instruction::SRem:
7085         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7086         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7087           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7088           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7089             Instruction *NewRem =
7090               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7091                                          BO->getName());
7092             InsertNewInstBefore(NewRem, ICI);
7093             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7094                                 Context->getNullValue(BO->getType()));
7095           }
7096         }
7097         break;
7098       case Instruction::Add:
7099         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7100         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7101           if (BO->hasOneUse())
7102             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7103                                 Context->getConstantExprSub(RHS, BOp1C));
7104         } else if (RHSV == 0) {
7105           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7106           // efficiently invertible, or if the add has just this one use.
7107           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7108           
7109           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7110             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7111           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7112             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7113           else if (BO->hasOneUse()) {
7114             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7115             InsertNewInstBefore(Neg, ICI);
7116             Neg->takeName(BO);
7117             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7118           }
7119         }
7120         break;
7121       case Instruction::Xor:
7122         // For the xor case, we can xor two constants together, eliminating
7123         // the explicit xor.
7124         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7125           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7126                               Context->getConstantExprXor(RHS, BOC));
7127         
7128         // FALLTHROUGH
7129       case Instruction::Sub:
7130         // Replace (([sub|xor] A, B) != 0) with (A != B)
7131         if (RHSV == 0)
7132           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7133                               BO->getOperand(1));
7134         break;
7135         
7136       case Instruction::Or:
7137         // If bits are being or'd in that are not present in the constant we
7138         // are comparing against, then the comparison could never succeed!
7139         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7140           Constant *NotCI = Context->getConstantExprNot(RHS);
7141           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7142             return ReplaceInstUsesWith(ICI,
7143                                        Context->getConstantInt(Type::Int1Ty, 
7144                                        isICMP_NE));
7145         }
7146         break;
7147         
7148       case Instruction::And:
7149         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7150           // If bits are being compared against that are and'd out, then the
7151           // comparison can never succeed!
7152           if ((RHSV & ~BOC->getValue()) != 0)
7153             return ReplaceInstUsesWith(ICI,
7154                                        Context->getConstantInt(Type::Int1Ty,
7155                                        isICMP_NE));
7156           
7157           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7158           if (RHS == BOC && RHSV.isPowerOf2())
7159             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7160                                 ICmpInst::ICMP_NE, LHSI,
7161                                 Context->getNullValue(RHS->getType()));
7162           
7163           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7164           if (BOC->getValue().isSignBit()) {
7165             Value *X = BO->getOperand(0);
7166             Constant *Zero = Context->getNullValue(X->getType());
7167             ICmpInst::Predicate pred = isICMP_NE ? 
7168               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7169             return new ICmpInst(*Context, pred, X, Zero);
7170           }
7171           
7172           // ((X & ~7) == 0) --> X < 8
7173           if (RHSV == 0 && isHighOnes(BOC)) {
7174             Value *X = BO->getOperand(0);
7175             Constant *NegX = Context->getConstantExprNeg(BOC);
7176             ICmpInst::Predicate pred = isICMP_NE ? 
7177               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7178             return new ICmpInst(*Context, pred, X, NegX);
7179           }
7180         }
7181       default: break;
7182       }
7183     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7184       // Handle icmp {eq|ne} <intrinsic>, intcst.
7185       if (II->getIntrinsicID() == Intrinsic::bswap) {
7186         AddToWorkList(II);
7187         ICI.setOperand(0, II->getOperand(1));
7188         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7189         return &ICI;
7190       }
7191     }
7192   }
7193   return 0;
7194 }
7195
7196 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7197 /// We only handle extending casts so far.
7198 ///
7199 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7200   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7201   Value *LHSCIOp        = LHSCI->getOperand(0);
7202   const Type *SrcTy     = LHSCIOp->getType();
7203   const Type *DestTy    = LHSCI->getType();
7204   Value *RHSCIOp;
7205
7206   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7207   // integer type is the same size as the pointer type.
7208   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7209       getTargetData().getPointerSizeInBits() == 
7210          cast<IntegerType>(DestTy)->getBitWidth()) {
7211     Value *RHSOp = 0;
7212     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7213       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7214     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7215       RHSOp = RHSC->getOperand(0);
7216       // If the pointer types don't match, insert a bitcast.
7217       if (LHSCIOp->getType() != RHSOp->getType())
7218         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7219     }
7220
7221     if (RHSOp)
7222       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7223   }
7224   
7225   // The code below only handles extension cast instructions, so far.
7226   // Enforce this.
7227   if (LHSCI->getOpcode() != Instruction::ZExt &&
7228       LHSCI->getOpcode() != Instruction::SExt)
7229     return 0;
7230
7231   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7232   bool isSignedCmp = ICI.isSignedPredicate();
7233
7234   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7235     // Not an extension from the same type?
7236     RHSCIOp = CI->getOperand(0);
7237     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7238       return 0;
7239     
7240     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7241     // and the other is a zext), then we can't handle this.
7242     if (CI->getOpcode() != LHSCI->getOpcode())
7243       return 0;
7244
7245     // Deal with equality cases early.
7246     if (ICI.isEquality())
7247       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7248
7249     // A signed comparison of sign extended values simplifies into a
7250     // signed comparison.
7251     if (isSignedCmp && isSignedExt)
7252       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7253
7254     // The other three cases all fold into an unsigned comparison.
7255     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7256   }
7257
7258   // If we aren't dealing with a constant on the RHS, exit early
7259   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7260   if (!CI)
7261     return 0;
7262
7263   // Compute the constant that would happen if we truncated to SrcTy then
7264   // reextended to DestTy.
7265   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7266   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7267                                                 Res1, DestTy);
7268
7269   // If the re-extended constant didn't change...
7270   if (Res2 == CI) {
7271     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7272     // For example, we might have:
7273     //    %A = sext i16 %X to i32
7274     //    %B = icmp ugt i32 %A, 1330
7275     // It is incorrect to transform this into 
7276     //    %B = icmp ugt i16 %X, 1330
7277     // because %A may have negative value. 
7278     //
7279     // However, we allow this when the compare is EQ/NE, because they are
7280     // signless.
7281     if (isSignedExt == isSignedCmp || ICI.isEquality())
7282       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7283     return 0;
7284   }
7285
7286   // The re-extended constant changed so the constant cannot be represented 
7287   // in the shorter type. Consequently, we cannot emit a simple comparison.
7288
7289   // First, handle some easy cases. We know the result cannot be equal at this
7290   // point so handle the ICI.isEquality() cases
7291   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7292     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7293   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7294     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7295
7296   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7297   // should have been folded away previously and not enter in here.
7298   Value *Result;
7299   if (isSignedCmp) {
7300     // We're performing a signed comparison.
7301     if (cast<ConstantInt>(CI)->getValue().isNegative())
7302       Result = Context->getConstantIntFalse();          // X < (small) --> false
7303     else
7304       Result = Context->getConstantIntTrue();           // X < (large) --> true
7305   } else {
7306     // We're performing an unsigned comparison.
7307     if (isSignedExt) {
7308       // We're performing an unsigned comp with a sign extended value.
7309       // This is true if the input is >= 0. [aka >s -1]
7310       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7311       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7312                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7313     } else {
7314       // Unsigned extend & unsigned compare -> always true.
7315       Result = Context->getConstantIntTrue();
7316     }
7317   }
7318
7319   // Finally, return the value computed.
7320   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7321       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7322     return ReplaceInstUsesWith(ICI, Result);
7323
7324   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7325           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7326          "ICmp should be folded!");
7327   if (Constant *CI = dyn_cast<Constant>(Result))
7328     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7329   return BinaryOperator::CreateNot(*Context, Result);
7330 }
7331
7332 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7333   return commonShiftTransforms(I);
7334 }
7335
7336 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7337   return commonShiftTransforms(I);
7338 }
7339
7340 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7341   if (Instruction *R = commonShiftTransforms(I))
7342     return R;
7343   
7344   Value *Op0 = I.getOperand(0);
7345   
7346   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7347   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7348     if (CSI->isAllOnesValue())
7349       return ReplaceInstUsesWith(I, CSI);
7350
7351   // See if we can turn a signed shr into an unsigned shr.
7352   if (MaskedValueIsZero(Op0,
7353                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7354     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7355
7356   // Arithmetic shifting an all-sign-bit value is a no-op.
7357   unsigned NumSignBits = ComputeNumSignBits(Op0);
7358   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7359     return ReplaceInstUsesWith(I, Op0);
7360
7361   return 0;
7362 }
7363
7364 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7365   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7366   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7367
7368   // shl X, 0 == X and shr X, 0 == X
7369   // shl 0, X == 0 and shr 0, X == 0
7370   if (Op1 == Context->getNullValue(Op1->getType()) ||
7371       Op0 == Context->getNullValue(Op0->getType()))
7372     return ReplaceInstUsesWith(I, Op0);
7373   
7374   if (isa<UndefValue>(Op0)) {            
7375     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7376       return ReplaceInstUsesWith(I, Op0);
7377     else                                    // undef << X -> 0, undef >>u X -> 0
7378       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7379   }
7380   if (isa<UndefValue>(Op1)) {
7381     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7382       return ReplaceInstUsesWith(I, Op0);          
7383     else                                     // X << undef, X >>u undef -> 0
7384       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7385   }
7386
7387   // See if we can fold away this shift.
7388   if (SimplifyDemandedInstructionBits(I))
7389     return &I;
7390
7391   // Try to fold constant and into select arguments.
7392   if (isa<Constant>(Op0))
7393     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7394       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7395         return R;
7396
7397   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7398     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7399       return Res;
7400   return 0;
7401 }
7402
7403 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7404                                                BinaryOperator &I) {
7405   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7406
7407   // See if we can simplify any instructions used by the instruction whose sole 
7408   // purpose is to compute bits we don't care about.
7409   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7410   
7411   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7412   // a signed shift.
7413   //
7414   if (Op1->uge(TypeBits)) {
7415     if (I.getOpcode() != Instruction::AShr)
7416       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7417     else {
7418       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7419       return &I;
7420     }
7421   }
7422   
7423   // ((X*C1) << C2) == (X * (C1 << C2))
7424   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7425     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7426       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7427         return BinaryOperator::CreateMul(BO->getOperand(0),
7428                                         Context->getConstantExprShl(BOOp, Op1));
7429   
7430   // Try to fold constant and into select arguments.
7431   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7432     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7433       return R;
7434   if (isa<PHINode>(Op0))
7435     if (Instruction *NV = FoldOpIntoPhi(I))
7436       return NV;
7437   
7438   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7439   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7440     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7441     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7442     // place.  Don't try to do this transformation in this case.  Also, we
7443     // require that the input operand is a shift-by-constant so that we have
7444     // confidence that the shifts will get folded together.  We could do this
7445     // xform in more cases, but it is unlikely to be profitable.
7446     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7447         isa<ConstantInt>(TrOp->getOperand(1))) {
7448       // Okay, we'll do this xform.  Make the shift of shift.
7449       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7450       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7451                                                 I.getName());
7452       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7453
7454       // For logical shifts, the truncation has the effect of making the high
7455       // part of the register be zeros.  Emulate this by inserting an AND to
7456       // clear the top bits as needed.  This 'and' will usually be zapped by
7457       // other xforms later if dead.
7458       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7459       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7460       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7461       
7462       // The mask we constructed says what the trunc would do if occurring
7463       // between the shifts.  We want to know the effect *after* the second
7464       // shift.  We know that it is a logical shift by a constant, so adjust the
7465       // mask as appropriate.
7466       if (I.getOpcode() == Instruction::Shl)
7467         MaskV <<= Op1->getZExtValue();
7468       else {
7469         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7470         MaskV = MaskV.lshr(Op1->getZExtValue());
7471       }
7472
7473       Instruction *And =
7474         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7475                                   TI->getName());
7476       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7477
7478       // Return the value truncated to the interesting size.
7479       return new TruncInst(And, I.getType());
7480     }
7481   }
7482   
7483   if (Op0->hasOneUse()) {
7484     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7485       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7486       Value *V1, *V2;
7487       ConstantInt *CC;
7488       switch (Op0BO->getOpcode()) {
7489         default: break;
7490         case Instruction::Add:
7491         case Instruction::And:
7492         case Instruction::Or:
7493         case Instruction::Xor: {
7494           // These operators commute.
7495           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7496           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7497               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7498                     m_Specific(Op1)), *Context)){
7499             Instruction *YS = BinaryOperator::CreateShl(
7500                                             Op0BO->getOperand(0), Op1,
7501                                             Op0BO->getName());
7502             InsertNewInstBefore(YS, I); // (Y << C)
7503             Instruction *X = 
7504               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7505                                      Op0BO->getOperand(1)->getName());
7506             InsertNewInstBefore(X, I);  // (X + (Y << C))
7507             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7508             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7509                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7510           }
7511           
7512           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7513           Value *Op0BOOp1 = Op0BO->getOperand(1);
7514           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7515               match(Op0BOOp1, 
7516                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7517                           m_ConstantInt(CC)), *Context) &&
7518               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7519             Instruction *YS = BinaryOperator::CreateShl(
7520                                                      Op0BO->getOperand(0), Op1,
7521                                                      Op0BO->getName());
7522             InsertNewInstBefore(YS, I); // (Y << C)
7523             Instruction *XM =
7524               BinaryOperator::CreateAnd(V1,
7525                                         Context->getConstantExprShl(CC, Op1),
7526                                         V1->getName()+".mask");
7527             InsertNewInstBefore(XM, I); // X & (CC << C)
7528             
7529             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7530           }
7531         }
7532           
7533         // FALL THROUGH.
7534         case Instruction::Sub: {
7535           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7536           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7537               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7538                     m_Specific(Op1)), *Context)){
7539             Instruction *YS = BinaryOperator::CreateShl(
7540                                                      Op0BO->getOperand(1), Op1,
7541                                                      Op0BO->getName());
7542             InsertNewInstBefore(YS, I); // (Y << C)
7543             Instruction *X =
7544               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7545                                      Op0BO->getOperand(0)->getName());
7546             InsertNewInstBefore(X, I);  // (X + (Y << C))
7547             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7548             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7549                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7550           }
7551           
7552           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7553           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7554               match(Op0BO->getOperand(0),
7555                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7556                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7557               cast<BinaryOperator>(Op0BO->getOperand(0))
7558                   ->getOperand(0)->hasOneUse()) {
7559             Instruction *YS = BinaryOperator::CreateShl(
7560                                                      Op0BO->getOperand(1), Op1,
7561                                                      Op0BO->getName());
7562             InsertNewInstBefore(YS, I); // (Y << C)
7563             Instruction *XM =
7564               BinaryOperator::CreateAnd(V1, 
7565                                         Context->getConstantExprShl(CC, Op1),
7566                                         V1->getName()+".mask");
7567             InsertNewInstBefore(XM, I); // X & (CC << C)
7568             
7569             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7570           }
7571           
7572           break;
7573         }
7574       }
7575       
7576       
7577       // If the operand is an bitwise operator with a constant RHS, and the
7578       // shift is the only use, we can pull it out of the shift.
7579       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7580         bool isValid = true;     // Valid only for And, Or, Xor
7581         bool highBitSet = false; // Transform if high bit of constant set?
7582         
7583         switch (Op0BO->getOpcode()) {
7584           default: isValid = false; break;   // Do not perform transform!
7585           case Instruction::Add:
7586             isValid = isLeftShift;
7587             break;
7588           case Instruction::Or:
7589           case Instruction::Xor:
7590             highBitSet = false;
7591             break;
7592           case Instruction::And:
7593             highBitSet = true;
7594             break;
7595         }
7596         
7597         // If this is a signed shift right, and the high bit is modified
7598         // by the logical operation, do not perform the transformation.
7599         // The highBitSet boolean indicates the value of the high bit of
7600         // the constant which would cause it to be modified for this
7601         // operation.
7602         //
7603         if (isValid && I.getOpcode() == Instruction::AShr)
7604           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7605         
7606         if (isValid) {
7607           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7608           
7609           Instruction *NewShift =
7610             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7611           InsertNewInstBefore(NewShift, I);
7612           NewShift->takeName(Op0BO);
7613           
7614           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7615                                         NewRHS);
7616         }
7617       }
7618     }
7619   }
7620   
7621   // Find out if this is a shift of a shift by a constant.
7622   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7623   if (ShiftOp && !ShiftOp->isShift())
7624     ShiftOp = 0;
7625   
7626   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7627     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7628     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7629     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7630     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7631     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7632     Value *X = ShiftOp->getOperand(0);
7633     
7634     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7635     
7636     const IntegerType *Ty = cast<IntegerType>(I.getType());
7637     
7638     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7639     if (I.getOpcode() == ShiftOp->getOpcode()) {
7640       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7641       // saturates.
7642       if (AmtSum >= TypeBits) {
7643         if (I.getOpcode() != Instruction::AShr)
7644           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7645         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7646       }
7647       
7648       return BinaryOperator::Create(I.getOpcode(), X,
7649                                     Context->getConstantInt(Ty, AmtSum));
7650     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7651                I.getOpcode() == Instruction::AShr) {
7652       if (AmtSum >= TypeBits)
7653         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7654       
7655       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7656       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7657     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7658                I.getOpcode() == Instruction::LShr) {
7659       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7660       if (AmtSum >= TypeBits)
7661         AmtSum = TypeBits-1;
7662       
7663       Instruction *Shift =
7664         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7665       InsertNewInstBefore(Shift, I);
7666
7667       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7668       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7669     }
7670     
7671     // Okay, if we get here, one shift must be left, and the other shift must be
7672     // right.  See if the amounts are equal.
7673     if (ShiftAmt1 == ShiftAmt2) {
7674       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7675       if (I.getOpcode() == Instruction::Shl) {
7676         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7677         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7678       }
7679       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7680       if (I.getOpcode() == Instruction::LShr) {
7681         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7682         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7683       }
7684       // We can simplify ((X << C) >>s C) into a trunc + sext.
7685       // NOTE: we could do this for any C, but that would make 'unusual' integer
7686       // types.  For now, just stick to ones well-supported by the code
7687       // generators.
7688       const Type *SExtType = 0;
7689       switch (Ty->getBitWidth() - ShiftAmt1) {
7690       case 1  :
7691       case 8  :
7692       case 16 :
7693       case 32 :
7694       case 64 :
7695       case 128:
7696         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7697         break;
7698       default: break;
7699       }
7700       if (SExtType) {
7701         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7702         InsertNewInstBefore(NewTrunc, I);
7703         return new SExtInst(NewTrunc, Ty);
7704       }
7705       // Otherwise, we can't handle it yet.
7706     } else if (ShiftAmt1 < ShiftAmt2) {
7707       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7708       
7709       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7710       if (I.getOpcode() == Instruction::Shl) {
7711         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7712                ShiftOp->getOpcode() == Instruction::AShr);
7713         Instruction *Shift =
7714           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7715         InsertNewInstBefore(Shift, I);
7716         
7717         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7718         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7719       }
7720       
7721       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7722       if (I.getOpcode() == Instruction::LShr) {
7723         assert(ShiftOp->getOpcode() == Instruction::Shl);
7724         Instruction *Shift =
7725           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7726         InsertNewInstBefore(Shift, I);
7727         
7728         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7729         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7730       }
7731       
7732       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7733     } else {
7734       assert(ShiftAmt2 < ShiftAmt1);
7735       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7736
7737       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7738       if (I.getOpcode() == Instruction::Shl) {
7739         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7740                ShiftOp->getOpcode() == Instruction::AShr);
7741         Instruction *Shift =
7742           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7743                                  Context->getConstantInt(Ty, ShiftDiff));
7744         InsertNewInstBefore(Shift, I);
7745         
7746         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7747         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7748       }
7749       
7750       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7751       if (I.getOpcode() == Instruction::LShr) {
7752         assert(ShiftOp->getOpcode() == Instruction::Shl);
7753         Instruction *Shift =
7754           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7755         InsertNewInstBefore(Shift, I);
7756         
7757         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7758         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7759       }
7760       
7761       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7762     }
7763   }
7764   return 0;
7765 }
7766
7767
7768 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7769 /// expression.  If so, decompose it, returning some value X, such that Val is
7770 /// X*Scale+Offset.
7771 ///
7772 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7773                                         int &Offset, LLVMContext *Context) {
7774   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7775   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7776     Offset = CI->getZExtValue();
7777     Scale  = 0;
7778     return Context->getConstantInt(Type::Int32Ty, 0);
7779   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7780     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7781       if (I->getOpcode() == Instruction::Shl) {
7782         // This is a value scaled by '1 << the shift amt'.
7783         Scale = 1U << RHS->getZExtValue();
7784         Offset = 0;
7785         return I->getOperand(0);
7786       } else if (I->getOpcode() == Instruction::Mul) {
7787         // This value is scaled by 'RHS'.
7788         Scale = RHS->getZExtValue();
7789         Offset = 0;
7790         return I->getOperand(0);
7791       } else if (I->getOpcode() == Instruction::Add) {
7792         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7793         // where C1 is divisible by C2.
7794         unsigned SubScale;
7795         Value *SubVal = 
7796           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7797                                     Offset, Context);
7798         Offset += RHS->getZExtValue();
7799         Scale = SubScale;
7800         return SubVal;
7801       }
7802     }
7803   }
7804
7805   // Otherwise, we can't look past this.
7806   Scale = 1;
7807   Offset = 0;
7808   return Val;
7809 }
7810
7811
7812 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7813 /// try to eliminate the cast by moving the type information into the alloc.
7814 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7815                                                    AllocationInst &AI) {
7816   const PointerType *PTy = cast<PointerType>(CI.getType());
7817   
7818   // Remove any uses of AI that are dead.
7819   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7820   
7821   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7822     Instruction *User = cast<Instruction>(*UI++);
7823     if (isInstructionTriviallyDead(User)) {
7824       while (UI != E && *UI == User)
7825         ++UI; // If this instruction uses AI more than once, don't break UI.
7826       
7827       ++NumDeadInst;
7828       DOUT << "IC: DCE: " << *User;
7829       EraseInstFromFunction(*User);
7830     }
7831   }
7832   
7833   // Get the type really allocated and the type casted to.
7834   const Type *AllocElTy = AI.getAllocatedType();
7835   const Type *CastElTy = PTy->getElementType();
7836   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7837
7838   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7839   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7840   if (CastElTyAlign < AllocElTyAlign) return 0;
7841
7842   // If the allocation has multiple uses, only promote it if we are strictly
7843   // increasing the alignment of the resultant allocation.  If we keep it the
7844   // same, we open the door to infinite loops of various kinds.  (A reference
7845   // from a dbg.declare doesn't count as a use for this purpose.)
7846   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7847       CastElTyAlign == AllocElTyAlign) return 0;
7848
7849   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7850   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7851   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7852
7853   // See if we can satisfy the modulus by pulling a scale out of the array
7854   // size argument.
7855   unsigned ArraySizeScale;
7856   int ArrayOffset;
7857   Value *NumElements = // See if the array size is a decomposable linear expr.
7858     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7859                               ArrayOffset, Context);
7860  
7861   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7862   // do the xform.
7863   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7864       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7865
7866   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7867   Value *Amt = 0;
7868   if (Scale == 1) {
7869     Amt = NumElements;
7870   } else {
7871     // If the allocation size is constant, form a constant mul expression
7872     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7873     if (isa<ConstantInt>(NumElements))
7874       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7875                                  cast<ConstantInt>(Amt));
7876     // otherwise multiply the amount and the number of elements
7877     else {
7878       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7879       Amt = InsertNewInstBefore(Tmp, AI);
7880     }
7881   }
7882   
7883   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7884     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7885     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7886     Amt = InsertNewInstBefore(Tmp, AI);
7887   }
7888   
7889   AllocationInst *New;
7890   if (isa<MallocInst>(AI))
7891     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7892   else
7893     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7894   InsertNewInstBefore(New, AI);
7895   New->takeName(&AI);
7896   
7897   // If the allocation has one real use plus a dbg.declare, just remove the
7898   // declare.
7899   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7900     EraseInstFromFunction(*DI);
7901   }
7902   // If the allocation has multiple real uses, insert a cast and change all
7903   // things that used it to use the new cast.  This will also hack on CI, but it
7904   // will die soon.
7905   else if (!AI.hasOneUse()) {
7906     AddUsesToWorkList(AI);
7907     // New is the allocation instruction, pointer typed. AI is the original
7908     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7909     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7910     InsertNewInstBefore(NewCast, AI);
7911     AI.replaceAllUsesWith(NewCast);
7912   }
7913   return ReplaceInstUsesWith(CI, New);
7914 }
7915
7916 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7917 /// and return it as type Ty without inserting any new casts and without
7918 /// changing the computed value.  This is used by code that tries to decide
7919 /// whether promoting or shrinking integer operations to wider or smaller types
7920 /// will allow us to eliminate a truncate or extend.
7921 ///
7922 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7923 /// extension operation if Ty is larger.
7924 ///
7925 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7926 /// should return true if trunc(V) can be computed by computing V in the smaller
7927 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7928 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7929 /// efficiently truncated.
7930 ///
7931 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7932 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7933 /// the final result.
7934 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7935                                               unsigned CastOpc,
7936                                               int &NumCastsRemoved){
7937   // We can always evaluate constants in another type.
7938   if (isa<Constant>(V))
7939     return true;
7940   
7941   Instruction *I = dyn_cast<Instruction>(V);
7942   if (!I) return false;
7943   
7944   const Type *OrigTy = V->getType();
7945   
7946   // If this is an extension or truncate, we can often eliminate it.
7947   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7948     // If this is a cast from the destination type, we can trivially eliminate
7949     // it, and this will remove a cast overall.
7950     if (I->getOperand(0)->getType() == Ty) {
7951       // If the first operand is itself a cast, and is eliminable, do not count
7952       // this as an eliminable cast.  We would prefer to eliminate those two
7953       // casts first.
7954       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7955         ++NumCastsRemoved;
7956       return true;
7957     }
7958   }
7959
7960   // We can't extend or shrink something that has multiple uses: doing so would
7961   // require duplicating the instruction in general, which isn't profitable.
7962   if (!I->hasOneUse()) return false;
7963
7964   unsigned Opc = I->getOpcode();
7965   switch (Opc) {
7966   case Instruction::Add:
7967   case Instruction::Sub:
7968   case Instruction::Mul:
7969   case Instruction::And:
7970   case Instruction::Or:
7971   case Instruction::Xor:
7972     // These operators can all arbitrarily be extended or truncated.
7973     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7974                                       NumCastsRemoved) &&
7975            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7976                                       NumCastsRemoved);
7977
7978   case Instruction::UDiv:
7979   case Instruction::URem: {
7980     // UDiv and URem can be truncated if all the truncated bits are zero.
7981     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7982     uint32_t BitWidth = Ty->getScalarSizeInBits();
7983     if (BitWidth < OrigBitWidth) {
7984       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7985       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7986           MaskedValueIsZero(I->getOperand(1), Mask)) {
7987         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7988                                           NumCastsRemoved) &&
7989                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7990                                           NumCastsRemoved);
7991       }
7992     }
7993     break;
7994   }
7995   case Instruction::Shl:
7996     // If we are truncating the result of this SHL, and if it's a shift of a
7997     // constant amount, we can always perform a SHL in a smaller type.
7998     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7999       uint32_t BitWidth = Ty->getScalarSizeInBits();
8000       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8001           CI->getLimitedValue(BitWidth) < BitWidth)
8002         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8003                                           NumCastsRemoved);
8004     }
8005     break;
8006   case Instruction::LShr:
8007     // If this is a truncate of a logical shr, we can truncate it to a smaller
8008     // lshr iff we know that the bits we would otherwise be shifting in are
8009     // already zeros.
8010     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8011       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8012       uint32_t BitWidth = Ty->getScalarSizeInBits();
8013       if (BitWidth < OrigBitWidth &&
8014           MaskedValueIsZero(I->getOperand(0),
8015             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8016           CI->getLimitedValue(BitWidth) < BitWidth) {
8017         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8018                                           NumCastsRemoved);
8019       }
8020     }
8021     break;
8022   case Instruction::ZExt:
8023   case Instruction::SExt:
8024   case Instruction::Trunc:
8025     // If this is the same kind of case as our original (e.g. zext+zext), we
8026     // can safely replace it.  Note that replacing it does not reduce the number
8027     // of casts in the input.
8028     if (Opc == CastOpc)
8029       return true;
8030
8031     // sext (zext ty1), ty2 -> zext ty2
8032     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8033       return true;
8034     break;
8035   case Instruction::Select: {
8036     SelectInst *SI = cast<SelectInst>(I);
8037     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8038                                       NumCastsRemoved) &&
8039            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8040                                       NumCastsRemoved);
8041   }
8042   case Instruction::PHI: {
8043     // We can change a phi if we can change all operands.
8044     PHINode *PN = cast<PHINode>(I);
8045     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8046       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8047                                       NumCastsRemoved))
8048         return false;
8049     return true;
8050   }
8051   default:
8052     // TODO: Can handle more cases here.
8053     break;
8054   }
8055   
8056   return false;
8057 }
8058
8059 /// EvaluateInDifferentType - Given an expression that 
8060 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8061 /// evaluate the expression.
8062 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8063                                              bool isSigned) {
8064   if (Constant *C = dyn_cast<Constant>(V))
8065     return Context->getConstantExprIntegerCast(C, Ty,
8066                                                isSigned /*Sext or ZExt*/);
8067
8068   // Otherwise, it must be an instruction.
8069   Instruction *I = cast<Instruction>(V);
8070   Instruction *Res = 0;
8071   unsigned Opc = I->getOpcode();
8072   switch (Opc) {
8073   case Instruction::Add:
8074   case Instruction::Sub:
8075   case Instruction::Mul:
8076   case Instruction::And:
8077   case Instruction::Or:
8078   case Instruction::Xor:
8079   case Instruction::AShr:
8080   case Instruction::LShr:
8081   case Instruction::Shl:
8082   case Instruction::UDiv:
8083   case Instruction::URem: {
8084     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8085     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8086     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8087     break;
8088   }    
8089   case Instruction::Trunc:
8090   case Instruction::ZExt:
8091   case Instruction::SExt:
8092     // If the source type of the cast is the type we're trying for then we can
8093     // just return the source.  There's no need to insert it because it is not
8094     // new.
8095     if (I->getOperand(0)->getType() == Ty)
8096       return I->getOperand(0);
8097     
8098     // Otherwise, must be the same type of cast, so just reinsert a new one.
8099     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8100                            Ty);
8101     break;
8102   case Instruction::Select: {
8103     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8104     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8105     Res = SelectInst::Create(I->getOperand(0), True, False);
8106     break;
8107   }
8108   case Instruction::PHI: {
8109     PHINode *OPN = cast<PHINode>(I);
8110     PHINode *NPN = PHINode::Create(Ty);
8111     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8112       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8113       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8114     }
8115     Res = NPN;
8116     break;
8117   }
8118   default: 
8119     // TODO: Can handle more cases here.
8120     LLVM_UNREACHABLE("Unreachable!");
8121     break;
8122   }
8123   
8124   Res->takeName(I);
8125   return InsertNewInstBefore(Res, *I);
8126 }
8127
8128 /// @brief Implement the transforms common to all CastInst visitors.
8129 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8130   Value *Src = CI.getOperand(0);
8131
8132   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8133   // eliminate it now.
8134   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8135     if (Instruction::CastOps opc = 
8136         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8137       // The first cast (CSrc) is eliminable so we need to fix up or replace
8138       // the second cast (CI). CSrc will then have a good chance of being dead.
8139       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8140     }
8141   }
8142
8143   // If we are casting a select then fold the cast into the select
8144   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8145     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8146       return NV;
8147
8148   // If we are casting a PHI then fold the cast into the PHI
8149   if (isa<PHINode>(Src))
8150     if (Instruction *NV = FoldOpIntoPhi(CI))
8151       return NV;
8152   
8153   return 0;
8154 }
8155
8156 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8157 /// or not there is a sequence of GEP indices into the type that will land us at
8158 /// the specified offset.  If so, fill them into NewIndices and return the
8159 /// resultant element type, otherwise return null.
8160 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8161                                        SmallVectorImpl<Value*> &NewIndices,
8162                                        const TargetData *TD,
8163                                        LLVMContext *Context) {
8164   if (!Ty->isSized()) return 0;
8165   
8166   // Start with the index over the outer type.  Note that the type size
8167   // might be zero (even if the offset isn't zero) if the indexed type
8168   // is something like [0 x {int, int}]
8169   const Type *IntPtrTy = TD->getIntPtrType();
8170   int64_t FirstIdx = 0;
8171   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8172     FirstIdx = Offset/TySize;
8173     Offset -= FirstIdx*TySize;
8174     
8175     // Handle hosts where % returns negative instead of values [0..TySize).
8176     if (Offset < 0) {
8177       --FirstIdx;
8178       Offset += TySize;
8179       assert(Offset >= 0);
8180     }
8181     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8182   }
8183   
8184   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8185     
8186   // Index into the types.  If we fail, set OrigBase to null.
8187   while (Offset) {
8188     // Indexing into tail padding between struct/array elements.
8189     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8190       return 0;
8191     
8192     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8193       const StructLayout *SL = TD->getStructLayout(STy);
8194       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8195              "Offset must stay within the indexed type");
8196       
8197       unsigned Elt = SL->getElementContainingOffset(Offset);
8198       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8199       
8200       Offset -= SL->getElementOffset(Elt);
8201       Ty = STy->getElementType(Elt);
8202     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8203       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8204       assert(EltSize && "Cannot index into a zero-sized array");
8205       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8206       Offset %= EltSize;
8207       Ty = AT->getElementType();
8208     } else {
8209       // Otherwise, we can't index into the middle of this atomic type, bail.
8210       return 0;
8211     }
8212   }
8213   
8214   return Ty;
8215 }
8216
8217 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8218 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8219   Value *Src = CI.getOperand(0);
8220   
8221   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8222     // If casting the result of a getelementptr instruction with no offset, turn
8223     // this into a cast of the original pointer!
8224     if (GEP->hasAllZeroIndices()) {
8225       // Changing the cast operand is usually not a good idea but it is safe
8226       // here because the pointer operand is being replaced with another 
8227       // pointer operand so the opcode doesn't need to change.
8228       AddToWorkList(GEP);
8229       CI.setOperand(0, GEP->getOperand(0));
8230       return &CI;
8231     }
8232     
8233     // If the GEP has a single use, and the base pointer is a bitcast, and the
8234     // GEP computes a constant offset, see if we can convert these three
8235     // instructions into fewer.  This typically happens with unions and other
8236     // non-type-safe code.
8237     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8238       if (GEP->hasAllConstantIndices()) {
8239         // We are guaranteed to get a constant from EmitGEPOffset.
8240         ConstantInt *OffsetV =
8241                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8242         int64_t Offset = OffsetV->getSExtValue();
8243         
8244         // Get the base pointer input of the bitcast, and the type it points to.
8245         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8246         const Type *GEPIdxTy =
8247           cast<PointerType>(OrigBase->getType())->getElementType();
8248         SmallVector<Value*, 8> NewIndices;
8249         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8250           // If we were able to index down into an element, create the GEP
8251           // and bitcast the result.  This eliminates one bitcast, potentially
8252           // two.
8253           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8254                                                         NewIndices.begin(),
8255                                                         NewIndices.end(), "");
8256           InsertNewInstBefore(NGEP, CI);
8257           NGEP->takeName(GEP);
8258           
8259           if (isa<BitCastInst>(CI))
8260             return new BitCastInst(NGEP, CI.getType());
8261           assert(isa<PtrToIntInst>(CI));
8262           return new PtrToIntInst(NGEP, CI.getType());
8263         }
8264       }      
8265     }
8266   }
8267     
8268   return commonCastTransforms(CI);
8269 }
8270
8271 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8272 /// type like i42.  We don't want to introduce operations on random non-legal
8273 /// integer types where they don't already exist in the code.  In the future,
8274 /// we should consider making this based off target-data, so that 32-bit targets
8275 /// won't get i64 operations etc.
8276 static bool isSafeIntegerType(const Type *Ty) {
8277   switch (Ty->getPrimitiveSizeInBits()) {
8278   case 8:
8279   case 16:
8280   case 32:
8281   case 64:
8282     return true;
8283   default: 
8284     return false;
8285   }
8286 }
8287
8288 /// commonIntCastTransforms - This function implements the common transforms
8289 /// for trunc, zext, and sext.
8290 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8291   if (Instruction *Result = commonCastTransforms(CI))
8292     return Result;
8293
8294   Value *Src = CI.getOperand(0);
8295   const Type *SrcTy = Src->getType();
8296   const Type *DestTy = CI.getType();
8297   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8298   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8299
8300   // See if we can simplify any instructions used by the LHS whose sole 
8301   // purpose is to compute bits we don't care about.
8302   if (SimplifyDemandedInstructionBits(CI))
8303     return &CI;
8304
8305   // If the source isn't an instruction or has more than one use then we
8306   // can't do anything more. 
8307   Instruction *SrcI = dyn_cast<Instruction>(Src);
8308   if (!SrcI || !Src->hasOneUse())
8309     return 0;
8310
8311   // Attempt to propagate the cast into the instruction for int->int casts.
8312   int NumCastsRemoved = 0;
8313   // Only do this if the dest type is a simple type, don't convert the
8314   // expression tree to something weird like i93 unless the source is also
8315   // strange.
8316   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8317        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8318       CanEvaluateInDifferentType(SrcI, DestTy,
8319                                  CI.getOpcode(), NumCastsRemoved)) {
8320     // If this cast is a truncate, evaluting in a different type always
8321     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8322     // we need to do an AND to maintain the clear top-part of the computation,
8323     // so we require that the input have eliminated at least one cast.  If this
8324     // is a sign extension, we insert two new casts (to do the extension) so we
8325     // require that two casts have been eliminated.
8326     bool DoXForm = false;
8327     bool JustReplace = false;
8328     switch (CI.getOpcode()) {
8329     default:
8330       // All the others use floating point so we shouldn't actually 
8331       // get here because of the check above.
8332       LLVM_UNREACHABLE("Unknown cast type");
8333     case Instruction::Trunc:
8334       DoXForm = true;
8335       break;
8336     case Instruction::ZExt: {
8337       DoXForm = NumCastsRemoved >= 1;
8338       if (!DoXForm && 0) {
8339         // If it's unnecessary to issue an AND to clear the high bits, it's
8340         // always profitable to do this xform.
8341         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8342         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8343         if (MaskedValueIsZero(TryRes, Mask))
8344           return ReplaceInstUsesWith(CI, TryRes);
8345         
8346         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8347           if (TryI->use_empty())
8348             EraseInstFromFunction(*TryI);
8349       }
8350       break;
8351     }
8352     case Instruction::SExt: {
8353       DoXForm = NumCastsRemoved >= 2;
8354       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8355         // If we do not have to emit the truncate + sext pair, then it's always
8356         // profitable to do this xform.
8357         //
8358         // It's not safe to eliminate the trunc + sext pair if one of the
8359         // eliminated cast is a truncate. e.g.
8360         // t2 = trunc i32 t1 to i16
8361         // t3 = sext i16 t2 to i32
8362         // !=
8363         // i32 t1
8364         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8365         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8366         if (NumSignBits > (DestBitSize - SrcBitSize))
8367           return ReplaceInstUsesWith(CI, TryRes);
8368         
8369         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8370           if (TryI->use_empty())
8371             EraseInstFromFunction(*TryI);
8372       }
8373       break;
8374     }
8375     }
8376     
8377     if (DoXForm) {
8378       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8379            << " cast: " << CI;
8380       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8381                                            CI.getOpcode() == Instruction::SExt);
8382       if (JustReplace)
8383         // Just replace this cast with the result.
8384         return ReplaceInstUsesWith(CI, Res);
8385
8386       assert(Res->getType() == DestTy);
8387       switch (CI.getOpcode()) {
8388       default: LLVM_UNREACHABLE("Unknown cast type!");
8389       case Instruction::Trunc:
8390         // Just replace this cast with the result.
8391         return ReplaceInstUsesWith(CI, Res);
8392       case Instruction::ZExt: {
8393         assert(SrcBitSize < DestBitSize && "Not a zext?");
8394
8395         // If the high bits are already zero, just replace this cast with the
8396         // result.
8397         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8398         if (MaskedValueIsZero(Res, Mask))
8399           return ReplaceInstUsesWith(CI, Res);
8400
8401         // We need to emit an AND to clear the high bits.
8402         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8403                                                             SrcBitSize));
8404         return BinaryOperator::CreateAnd(Res, C);
8405       }
8406       case Instruction::SExt: {
8407         // If the high bits are already filled with sign bit, just replace this
8408         // cast with the result.
8409         unsigned NumSignBits = ComputeNumSignBits(Res);
8410         if (NumSignBits > (DestBitSize - SrcBitSize))
8411           return ReplaceInstUsesWith(CI, Res);
8412
8413         // We need to emit a cast to truncate, then a cast to sext.
8414         return CastInst::Create(Instruction::SExt,
8415             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8416                              CI), DestTy);
8417       }
8418       }
8419     }
8420   }
8421   
8422   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8423   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8424
8425   switch (SrcI->getOpcode()) {
8426   case Instruction::Add:
8427   case Instruction::Mul:
8428   case Instruction::And:
8429   case Instruction::Or:
8430   case Instruction::Xor:
8431     // If we are discarding information, rewrite.
8432     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8433       // Don't insert two casts unless at least one can be eliminated.
8434       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8435           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8436         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8437         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8438         return BinaryOperator::Create(
8439             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8440       }
8441     }
8442
8443     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8444     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8445         SrcI->getOpcode() == Instruction::Xor &&
8446         Op1 == Context->getConstantIntTrue() &&
8447         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8448       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8449       return BinaryOperator::CreateXor(New,
8450                                       Context->getConstantInt(CI.getType(), 1));
8451     }
8452     break;
8453
8454   case Instruction::Shl: {
8455     // Canonicalize trunc inside shl, if we can.
8456     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8457     if (CI && DestBitSize < SrcBitSize &&
8458         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8459       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8460       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8461       return BinaryOperator::CreateShl(Op0c, Op1c);
8462     }
8463     break;
8464   }
8465   }
8466   return 0;
8467 }
8468
8469 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8470   if (Instruction *Result = commonIntCastTransforms(CI))
8471     return Result;
8472   
8473   Value *Src = CI.getOperand(0);
8474   const Type *Ty = CI.getType();
8475   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8476   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8477
8478   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8479   if (DestBitWidth == 1 &&
8480       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8481     Constant *One = Context->getConstantInt(Src->getType(), 1);
8482     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8483     Value *Zero = Context->getNullValue(Src->getType());
8484     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8485   }
8486
8487   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8488   ConstantInt *ShAmtV = 0;
8489   Value *ShiftOp = 0;
8490   if (Src->hasOneUse() &&
8491       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8492     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8493     
8494     // Get a mask for the bits shifting in.
8495     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8496     if (MaskedValueIsZero(ShiftOp, Mask)) {
8497       if (ShAmt >= DestBitWidth)        // All zeros.
8498         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8499       
8500       // Okay, we can shrink this.  Truncate the input, then return a new
8501       // shift.
8502       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8503       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8504       return BinaryOperator::CreateLShr(V1, V2);
8505     }
8506   }
8507   
8508   return 0;
8509 }
8510
8511 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8512 /// in order to eliminate the icmp.
8513 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8514                                              bool DoXform) {
8515   // If we are just checking for a icmp eq of a single bit and zext'ing it
8516   // to an integer, then shift the bit to the appropriate place and then
8517   // cast to integer to avoid the comparison.
8518   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8519     const APInt &Op1CV = Op1C->getValue();
8520       
8521     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8522     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8523     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8524         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8525       if (!DoXform) return ICI;
8526
8527       Value *In = ICI->getOperand(0);
8528       Value *Sh = Context->getConstantInt(In->getType(),
8529                                    In->getType()->getScalarSizeInBits()-1);
8530       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8531                                                         In->getName()+".lobit"),
8532                                CI);
8533       if (In->getType() != CI.getType())
8534         In = CastInst::CreateIntegerCast(In, CI.getType(),
8535                                          false/*ZExt*/, "tmp", &CI);
8536
8537       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8538         Constant *One = Context->getConstantInt(In->getType(), 1);
8539         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8540                                                          In->getName()+".not"),
8541                                  CI);
8542       }
8543
8544       return ReplaceInstUsesWith(CI, In);
8545     }
8546       
8547       
8548       
8549     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8550     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8551     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8552     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8553     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8554     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8555     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8556     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8557     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8558         // This only works for EQ and NE
8559         ICI->isEquality()) {
8560       // If Op1C some other power of two, convert:
8561       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8562       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8563       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8564       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8565         
8566       APInt KnownZeroMask(~KnownZero);
8567       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8568         if (!DoXform) return ICI;
8569
8570         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8571         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8572           // (X&4) == 2 --> false
8573           // (X&4) != 2 --> true
8574           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8575           Res = Context->getConstantExprZExt(Res, CI.getType());
8576           return ReplaceInstUsesWith(CI, Res);
8577         }
8578           
8579         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8580         Value *In = ICI->getOperand(0);
8581         if (ShiftAmt) {
8582           // Perform a logical shr by shiftamt.
8583           // Insert the shift to put the result in the low bit.
8584           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8585                               Context->getConstantInt(In->getType(), ShiftAmt),
8586                                                    In->getName()+".lobit"), CI);
8587         }
8588           
8589         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8590           Constant *One = Context->getConstantInt(In->getType(), 1);
8591           In = BinaryOperator::CreateXor(In, One, "tmp");
8592           InsertNewInstBefore(cast<Instruction>(In), CI);
8593         }
8594           
8595         if (CI.getType() == In->getType())
8596           return ReplaceInstUsesWith(CI, In);
8597         else
8598           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8599       }
8600     }
8601   }
8602
8603   return 0;
8604 }
8605
8606 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8607   // If one of the common conversion will work ..
8608   if (Instruction *Result = commonIntCastTransforms(CI))
8609     return Result;
8610
8611   Value *Src = CI.getOperand(0);
8612
8613   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8614   // types and if the sizes are just right we can convert this into a logical
8615   // 'and' which will be much cheaper than the pair of casts.
8616   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8617     // Get the sizes of the types involved.  We know that the intermediate type
8618     // will be smaller than A or C, but don't know the relation between A and C.
8619     Value *A = CSrc->getOperand(0);
8620     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8621     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8622     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8623     // If we're actually extending zero bits, then if
8624     // SrcSize <  DstSize: zext(a & mask)
8625     // SrcSize == DstSize: a & mask
8626     // SrcSize  > DstSize: trunc(a) & mask
8627     if (SrcSize < DstSize) {
8628       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8629       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8630       Instruction *And =
8631         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8632       InsertNewInstBefore(And, CI);
8633       return new ZExtInst(And, CI.getType());
8634     } else if (SrcSize == DstSize) {
8635       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8636       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8637                                                            AndValue));
8638     } else if (SrcSize > DstSize) {
8639       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8640       InsertNewInstBefore(Trunc, CI);
8641       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8642       return BinaryOperator::CreateAnd(Trunc, 
8643                                        Context->getConstantInt(Trunc->getType(),
8644                                                                AndValue));
8645     }
8646   }
8647
8648   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8649     return transformZExtICmp(ICI, CI);
8650
8651   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8652   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8653     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8654     // of the (zext icmp) will be transformed.
8655     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8656     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8657     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8658         (transformZExtICmp(LHS, CI, false) ||
8659          transformZExtICmp(RHS, CI, false))) {
8660       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8661       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8662       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8663     }
8664   }
8665
8666   // zext(trunc(t) & C) -> (t & zext(C)).
8667   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8668     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8669       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8670         Value *TI0 = TI->getOperand(0);
8671         if (TI0->getType() == CI.getType())
8672           return
8673             BinaryOperator::CreateAnd(TI0,
8674                                 Context->getConstantExprZExt(C, CI.getType()));
8675       }
8676
8677   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8678   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8679     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8680       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8681         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8682             And->getOperand(1) == C)
8683           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8684             Value *TI0 = TI->getOperand(0);
8685             if (TI0->getType() == CI.getType()) {
8686               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8687               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8688               InsertNewInstBefore(NewAnd, *And);
8689               return BinaryOperator::CreateXor(NewAnd, ZC);
8690             }
8691           }
8692
8693   return 0;
8694 }
8695
8696 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8697   if (Instruction *I = commonIntCastTransforms(CI))
8698     return I;
8699   
8700   Value *Src = CI.getOperand(0);
8701   
8702   // Canonicalize sign-extend from i1 to a select.
8703   if (Src->getType() == Type::Int1Ty)
8704     return SelectInst::Create(Src,
8705                               Context->getAllOnesValue(CI.getType()),
8706                               Context->getNullValue(CI.getType()));
8707
8708   // See if the value being truncated is already sign extended.  If so, just
8709   // eliminate the trunc/sext pair.
8710   if (getOpcode(Src) == Instruction::Trunc) {
8711     Value *Op = cast<User>(Src)->getOperand(0);
8712     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8713     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8714     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8715     unsigned NumSignBits = ComputeNumSignBits(Op);
8716
8717     if (OpBits == DestBits) {
8718       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8719       // bits, it is already ready.
8720       if (NumSignBits > DestBits-MidBits)
8721         return ReplaceInstUsesWith(CI, Op);
8722     } else if (OpBits < DestBits) {
8723       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8724       // bits, just sext from i32.
8725       if (NumSignBits > OpBits-MidBits)
8726         return new SExtInst(Op, CI.getType(), "tmp");
8727     } else {
8728       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8729       // bits, just truncate to i32.
8730       if (NumSignBits > OpBits-MidBits)
8731         return new TruncInst(Op, CI.getType(), "tmp");
8732     }
8733   }
8734
8735   // If the input is a shl/ashr pair of a same constant, then this is a sign
8736   // extension from a smaller value.  If we could trust arbitrary bitwidth
8737   // integers, we could turn this into a truncate to the smaller bit and then
8738   // use a sext for the whole extension.  Since we don't, look deeper and check
8739   // for a truncate.  If the source and dest are the same type, eliminate the
8740   // trunc and extend and just do shifts.  For example, turn:
8741   //   %a = trunc i32 %i to i8
8742   //   %b = shl i8 %a, 6
8743   //   %c = ashr i8 %b, 6
8744   //   %d = sext i8 %c to i32
8745   // into:
8746   //   %a = shl i32 %i, 30
8747   //   %d = ashr i32 %a, 30
8748   Value *A = 0;
8749   ConstantInt *BA = 0, *CA = 0;
8750   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8751                         m_ConstantInt(CA)), *Context) &&
8752       BA == CA && isa<TruncInst>(A)) {
8753     Value *I = cast<TruncInst>(A)->getOperand(0);
8754     if (I->getType() == CI.getType()) {
8755       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8756       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8757       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8758       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8759       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8760                                                         CI.getName()), CI);
8761       return BinaryOperator::CreateAShr(I, ShAmtV);
8762     }
8763   }
8764   
8765   return 0;
8766 }
8767
8768 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8769 /// in the specified FP type without changing its value.
8770 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8771                               LLVMContext *Context) {
8772   bool losesInfo;
8773   APFloat F = CFP->getValueAPF();
8774   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8775   if (!losesInfo)
8776     return Context->getConstantFP(F);
8777   return 0;
8778 }
8779
8780 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8781 /// through it until we get the source value.
8782 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8783   if (Instruction *I = dyn_cast<Instruction>(V))
8784     if (I->getOpcode() == Instruction::FPExt)
8785       return LookThroughFPExtensions(I->getOperand(0), Context);
8786   
8787   // If this value is a constant, return the constant in the smallest FP type
8788   // that can accurately represent it.  This allows us to turn
8789   // (float)((double)X+2.0) into x+2.0f.
8790   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8791     if (CFP->getType() == Type::PPC_FP128Ty)
8792       return V;  // No constant folding of this.
8793     // See if the value can be truncated to float and then reextended.
8794     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8795       return V;
8796     if (CFP->getType() == Type::DoubleTy)
8797       return V;  // Won't shrink.
8798     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8799       return V;
8800     // Don't try to shrink to various long double types.
8801   }
8802   
8803   return V;
8804 }
8805
8806 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8807   if (Instruction *I = commonCastTransforms(CI))
8808     return I;
8809   
8810   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8811   // smaller than the destination type, we can eliminate the truncate by doing
8812   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8813   // many builtins (sqrt, etc).
8814   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8815   if (OpI && OpI->hasOneUse()) {
8816     switch (OpI->getOpcode()) {
8817     default: break;
8818     case Instruction::FAdd:
8819     case Instruction::FSub:
8820     case Instruction::FMul:
8821     case Instruction::FDiv:
8822     case Instruction::FRem:
8823       const Type *SrcTy = OpI->getType();
8824       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8825       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8826       if (LHSTrunc->getType() != SrcTy && 
8827           RHSTrunc->getType() != SrcTy) {
8828         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8829         // If the source types were both smaller than the destination type of
8830         // the cast, do this xform.
8831         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8832             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8833           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8834                                       CI.getType(), CI);
8835           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8836                                       CI.getType(), CI);
8837           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8838         }
8839       }
8840       break;  
8841     }
8842   }
8843   return 0;
8844 }
8845
8846 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8847   return commonCastTransforms(CI);
8848 }
8849
8850 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8851   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8852   if (OpI == 0)
8853     return commonCastTransforms(FI);
8854
8855   // fptoui(uitofp(X)) --> X
8856   // fptoui(sitofp(X)) --> X
8857   // This is safe if the intermediate type has enough bits in its mantissa to
8858   // accurately represent all values of X.  For example, do not do this with
8859   // i64->float->i64.  This is also safe for sitofp case, because any negative
8860   // 'X' value would cause an undefined result for the fptoui. 
8861   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8862       OpI->getOperand(0)->getType() == FI.getType() &&
8863       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8864                     OpI->getType()->getFPMantissaWidth())
8865     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8866
8867   return commonCastTransforms(FI);
8868 }
8869
8870 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8871   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8872   if (OpI == 0)
8873     return commonCastTransforms(FI);
8874   
8875   // fptosi(sitofp(X)) --> X
8876   // fptosi(uitofp(X)) --> X
8877   // This is safe if the intermediate type has enough bits in its mantissa to
8878   // accurately represent all values of X.  For example, do not do this with
8879   // i64->float->i64.  This is also safe for sitofp case, because any negative
8880   // 'X' value would cause an undefined result for the fptoui. 
8881   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8882       OpI->getOperand(0)->getType() == FI.getType() &&
8883       (int)FI.getType()->getScalarSizeInBits() <=
8884                     OpI->getType()->getFPMantissaWidth())
8885     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8886   
8887   return commonCastTransforms(FI);
8888 }
8889
8890 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8891   return commonCastTransforms(CI);
8892 }
8893
8894 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8895   return commonCastTransforms(CI);
8896 }
8897
8898 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8899   // If the destination integer type is smaller than the intptr_t type for
8900   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8901   // trunc to be exposed to other transforms.  Don't do this for extending
8902   // ptrtoint's, because we don't know if the target sign or zero extends its
8903   // pointers.
8904   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8905     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8906                                                     TD->getIntPtrType(),
8907                                                     "tmp"), CI);
8908     return new TruncInst(P, CI.getType());
8909   }
8910   
8911   return commonPointerCastTransforms(CI);
8912 }
8913
8914 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8915   // If the source integer type is larger than the intptr_t type for
8916   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8917   // allows the trunc to be exposed to other transforms.  Don't do this for
8918   // extending inttoptr's, because we don't know if the target sign or zero
8919   // extends to pointers.
8920   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8921       TD->getPointerSizeInBits()) {
8922     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8923                                                  TD->getIntPtrType(),
8924                                                  "tmp"), CI);
8925     return new IntToPtrInst(P, CI.getType());
8926   }
8927   
8928   if (Instruction *I = commonCastTransforms(CI))
8929     return I;
8930   
8931   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8932   if (!DestPointee->isSized()) return 0;
8933
8934   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8935   ConstantInt *Cst;
8936   Value *X;
8937   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8938                                     m_ConstantInt(Cst)), *Context)) {
8939     // If the source and destination operands have the same type, see if this
8940     // is a single-index GEP.
8941     if (X->getType() == CI.getType()) {
8942       // Get the size of the pointee type.
8943       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8944
8945       // Convert the constant to intptr type.
8946       APInt Offset = Cst->getValue();
8947       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8948
8949       // If Offset is evenly divisible by Size, we can do this xform.
8950       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8951         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8952         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8953       }
8954     }
8955     // TODO: Could handle other cases, e.g. where add is indexing into field of
8956     // struct etc.
8957   } else if (CI.getOperand(0)->hasOneUse() &&
8958              match(CI.getOperand(0), m_Add(m_Value(X),
8959                    m_ConstantInt(Cst)), *Context)) {
8960     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8961     // "inttoptr+GEP" instead of "add+intptr".
8962     
8963     // Get the size of the pointee type.
8964     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8965     
8966     // Convert the constant to intptr type.
8967     APInt Offset = Cst->getValue();
8968     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8969     
8970     // If Offset is evenly divisible by Size, we can do this xform.
8971     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8972       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8973       
8974       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8975                                                             "tmp"), CI);
8976       return GetElementPtrInst::Create(P,
8977                                        Context->getConstantInt(Offset), "tmp");
8978     }
8979   }
8980   return 0;
8981 }
8982
8983 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8984   // If the operands are integer typed then apply the integer transforms,
8985   // otherwise just apply the common ones.
8986   Value *Src = CI.getOperand(0);
8987   const Type *SrcTy = Src->getType();
8988   const Type *DestTy = CI.getType();
8989
8990   if (isa<PointerType>(SrcTy)) {
8991     if (Instruction *I = commonPointerCastTransforms(CI))
8992       return I;
8993   } else {
8994     if (Instruction *Result = commonCastTransforms(CI))
8995       return Result;
8996   }
8997
8998
8999   // Get rid of casts from one type to the same type. These are useless and can
9000   // be replaced by the operand.
9001   if (DestTy == Src->getType())
9002     return ReplaceInstUsesWith(CI, Src);
9003
9004   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9005     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9006     const Type *DstElTy = DstPTy->getElementType();
9007     const Type *SrcElTy = SrcPTy->getElementType();
9008     
9009     // If the address spaces don't match, don't eliminate the bitcast, which is
9010     // required for changing types.
9011     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9012       return 0;
9013     
9014     // If we are casting a malloc or alloca to a pointer to a type of the same
9015     // size, rewrite the allocation instruction to allocate the "right" type.
9016     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9017       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9018         return V;
9019     
9020     // If the source and destination are pointers, and this cast is equivalent
9021     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9022     // This can enhance SROA and other transforms that want type-safe pointers.
9023     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9024     unsigned NumZeros = 0;
9025     while (SrcElTy != DstElTy && 
9026            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9027            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9028       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9029       ++NumZeros;
9030     }
9031
9032     // If we found a path from the src to dest, create the getelementptr now.
9033     if (SrcElTy == DstElTy) {
9034       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9035       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9036                                        ((Instruction*) NULL));
9037     }
9038   }
9039
9040   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9041     if (SVI->hasOneUse()) {
9042       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9043       // a bitconvert to a vector with the same # elts.
9044       if (isa<VectorType>(DestTy) && 
9045           cast<VectorType>(DestTy)->getNumElements() ==
9046                 SVI->getType()->getNumElements() &&
9047           SVI->getType()->getNumElements() ==
9048             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9049         CastInst *Tmp;
9050         // If either of the operands is a cast from CI.getType(), then
9051         // evaluating the shuffle in the casted destination's type will allow
9052         // us to eliminate at least one cast.
9053         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9054              Tmp->getOperand(0)->getType() == DestTy) ||
9055             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9056              Tmp->getOperand(0)->getType() == DestTy)) {
9057           Value *LHS = InsertCastBefore(Instruction::BitCast,
9058                                         SVI->getOperand(0), DestTy, CI);
9059           Value *RHS = InsertCastBefore(Instruction::BitCast,
9060                                         SVI->getOperand(1), DestTy, CI);
9061           // Return a new shuffle vector.  Use the same element ID's, as we
9062           // know the vector types match #elts.
9063           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9064         }
9065       }
9066     }
9067   }
9068   return 0;
9069 }
9070
9071 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9072 ///   %C = or %A, %B
9073 ///   %D = select %cond, %C, %A
9074 /// into:
9075 ///   %C = select %cond, %B, 0
9076 ///   %D = or %A, %C
9077 ///
9078 /// Assuming that the specified instruction is an operand to the select, return
9079 /// a bitmask indicating which operands of this instruction are foldable if they
9080 /// equal the other incoming value of the select.
9081 ///
9082 static unsigned GetSelectFoldableOperands(Instruction *I) {
9083   switch (I->getOpcode()) {
9084   case Instruction::Add:
9085   case Instruction::Mul:
9086   case Instruction::And:
9087   case Instruction::Or:
9088   case Instruction::Xor:
9089     return 3;              // Can fold through either operand.
9090   case Instruction::Sub:   // Can only fold on the amount subtracted.
9091   case Instruction::Shl:   // Can only fold on the shift amount.
9092   case Instruction::LShr:
9093   case Instruction::AShr:
9094     return 1;
9095   default:
9096     return 0;              // Cannot fold
9097   }
9098 }
9099
9100 /// GetSelectFoldableConstant - For the same transformation as the previous
9101 /// function, return the identity constant that goes into the select.
9102 static Constant *GetSelectFoldableConstant(Instruction *I,
9103                                            LLVMContext *Context) {
9104   switch (I->getOpcode()) {
9105   default: LLVM_UNREACHABLE("This cannot happen!");
9106   case Instruction::Add:
9107   case Instruction::Sub:
9108   case Instruction::Or:
9109   case Instruction::Xor:
9110   case Instruction::Shl:
9111   case Instruction::LShr:
9112   case Instruction::AShr:
9113     return Context->getNullValue(I->getType());
9114   case Instruction::And:
9115     return Context->getAllOnesValue(I->getType());
9116   case Instruction::Mul:
9117     return Context->getConstantInt(I->getType(), 1);
9118   }
9119 }
9120
9121 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9122 /// have the same opcode and only one use each.  Try to simplify this.
9123 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9124                                           Instruction *FI) {
9125   if (TI->getNumOperands() == 1) {
9126     // If this is a non-volatile load or a cast from the same type,
9127     // merge.
9128     if (TI->isCast()) {
9129       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9130         return 0;
9131     } else {
9132       return 0;  // unknown unary op.
9133     }
9134
9135     // Fold this by inserting a select from the input values.
9136     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9137                                            FI->getOperand(0), SI.getName()+".v");
9138     InsertNewInstBefore(NewSI, SI);
9139     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9140                             TI->getType());
9141   }
9142
9143   // Only handle binary operators here.
9144   if (!isa<BinaryOperator>(TI))
9145     return 0;
9146
9147   // Figure out if the operations have any operands in common.
9148   Value *MatchOp, *OtherOpT, *OtherOpF;
9149   bool MatchIsOpZero;
9150   if (TI->getOperand(0) == FI->getOperand(0)) {
9151     MatchOp  = TI->getOperand(0);
9152     OtherOpT = TI->getOperand(1);
9153     OtherOpF = FI->getOperand(1);
9154     MatchIsOpZero = true;
9155   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9156     MatchOp  = TI->getOperand(1);
9157     OtherOpT = TI->getOperand(0);
9158     OtherOpF = FI->getOperand(0);
9159     MatchIsOpZero = false;
9160   } else if (!TI->isCommutative()) {
9161     return 0;
9162   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9163     MatchOp  = TI->getOperand(0);
9164     OtherOpT = TI->getOperand(1);
9165     OtherOpF = FI->getOperand(0);
9166     MatchIsOpZero = true;
9167   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9168     MatchOp  = TI->getOperand(1);
9169     OtherOpT = TI->getOperand(0);
9170     OtherOpF = FI->getOperand(1);
9171     MatchIsOpZero = true;
9172   } else {
9173     return 0;
9174   }
9175
9176   // If we reach here, they do have operations in common.
9177   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9178                                          OtherOpF, SI.getName()+".v");
9179   InsertNewInstBefore(NewSI, SI);
9180
9181   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9182     if (MatchIsOpZero)
9183       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9184     else
9185       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9186   }
9187   LLVM_UNREACHABLE("Shouldn't get here");
9188   return 0;
9189 }
9190
9191 static bool isSelect01(Constant *C1, Constant *C2) {
9192   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9193   if (!C1I)
9194     return false;
9195   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9196   if (!C2I)
9197     return false;
9198   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9199 }
9200
9201 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9202 /// facilitate further optimization.
9203 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9204                                             Value *FalseVal) {
9205   // See the comment above GetSelectFoldableOperands for a description of the
9206   // transformation we are doing here.
9207   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9208     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9209         !isa<Constant>(FalseVal)) {
9210       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9211         unsigned OpToFold = 0;
9212         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9213           OpToFold = 1;
9214         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9215           OpToFold = 2;
9216         }
9217
9218         if (OpToFold) {
9219           Constant *C = GetSelectFoldableConstant(TVI, Context);
9220           Value *OOp = TVI->getOperand(2-OpToFold);
9221           // Avoid creating select between 2 constants unless it's selecting
9222           // between 0 and 1.
9223           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9224             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9225             InsertNewInstBefore(NewSel, SI);
9226             NewSel->takeName(TVI);
9227             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9228               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9229             LLVM_UNREACHABLE("Unknown instruction!!");
9230           }
9231         }
9232       }
9233     }
9234   }
9235
9236   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9237     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9238         !isa<Constant>(TrueVal)) {
9239       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9240         unsigned OpToFold = 0;
9241         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9242           OpToFold = 1;
9243         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9244           OpToFold = 2;
9245         }
9246
9247         if (OpToFold) {
9248           Constant *C = GetSelectFoldableConstant(FVI, Context);
9249           Value *OOp = FVI->getOperand(2-OpToFold);
9250           // Avoid creating select between 2 constants unless it's selecting
9251           // between 0 and 1.
9252           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9253             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9254             InsertNewInstBefore(NewSel, SI);
9255             NewSel->takeName(FVI);
9256             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9257               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9258             LLVM_UNREACHABLE("Unknown instruction!!");
9259           }
9260         }
9261       }
9262     }
9263   }
9264
9265   return 0;
9266 }
9267
9268 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9269 /// ICmpInst as its first operand.
9270 ///
9271 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9272                                                    ICmpInst *ICI) {
9273   bool Changed = false;
9274   ICmpInst::Predicate Pred = ICI->getPredicate();
9275   Value *CmpLHS = ICI->getOperand(0);
9276   Value *CmpRHS = ICI->getOperand(1);
9277   Value *TrueVal = SI.getTrueValue();
9278   Value *FalseVal = SI.getFalseValue();
9279
9280   // Check cases where the comparison is with a constant that
9281   // can be adjusted to fit the min/max idiom. We may edit ICI in
9282   // place here, so make sure the select is the only user.
9283   if (ICI->hasOneUse())
9284     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9285       switch (Pred) {
9286       default: break;
9287       case ICmpInst::ICMP_ULT:
9288       case ICmpInst::ICMP_SLT: {
9289         // X < MIN ? T : F  -->  F
9290         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9291           return ReplaceInstUsesWith(SI, FalseVal);
9292         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9293         Constant *AdjustedRHS = SubOne(CI, Context);
9294         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9295             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9296           Pred = ICmpInst::getSwappedPredicate(Pred);
9297           CmpRHS = AdjustedRHS;
9298           std::swap(FalseVal, TrueVal);
9299           ICI->setPredicate(Pred);
9300           ICI->setOperand(1, CmpRHS);
9301           SI.setOperand(1, TrueVal);
9302           SI.setOperand(2, FalseVal);
9303           Changed = true;
9304         }
9305         break;
9306       }
9307       case ICmpInst::ICMP_UGT:
9308       case ICmpInst::ICMP_SGT: {
9309         // X > MAX ? T : F  -->  F
9310         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9311           return ReplaceInstUsesWith(SI, FalseVal);
9312         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9313         Constant *AdjustedRHS = AddOne(CI, Context);
9314         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9315             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9316           Pred = ICmpInst::getSwappedPredicate(Pred);
9317           CmpRHS = AdjustedRHS;
9318           std::swap(FalseVal, TrueVal);
9319           ICI->setPredicate(Pred);
9320           ICI->setOperand(1, CmpRHS);
9321           SI.setOperand(1, TrueVal);
9322           SI.setOperand(2, FalseVal);
9323           Changed = true;
9324         }
9325         break;
9326       }
9327       }
9328
9329       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9330       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9331       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9332       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9333           match(FalseVal, m_ConstantInt<0>(), *Context))
9334         Pred = ICI->getPredicate();
9335       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9336                match(FalseVal, m_ConstantInt<-1>(), *Context))
9337         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9338       
9339       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9340         // If we are just checking for a icmp eq of a single bit and zext'ing it
9341         // to an integer, then shift the bit to the appropriate place and then
9342         // cast to integer to avoid the comparison.
9343         const APInt &Op1CV = CI->getValue();
9344     
9345         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9346         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9347         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9348             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9349           Value *In = ICI->getOperand(0);
9350           Value *Sh = Context->getConstantInt(In->getType(),
9351                                        In->getType()->getScalarSizeInBits()-1);
9352           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9353                                                           In->getName()+".lobit"),
9354                                    *ICI);
9355           if (In->getType() != SI.getType())
9356             In = CastInst::CreateIntegerCast(In, SI.getType(),
9357                                              true/*SExt*/, "tmp", ICI);
9358     
9359           if (Pred == ICmpInst::ICMP_SGT)
9360             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9361                                        In->getName()+".not"), *ICI);
9362     
9363           return ReplaceInstUsesWith(SI, In);
9364         }
9365       }
9366     }
9367
9368   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9369     // Transform (X == Y) ? X : Y  -> Y
9370     if (Pred == ICmpInst::ICMP_EQ)
9371       return ReplaceInstUsesWith(SI, FalseVal);
9372     // Transform (X != Y) ? X : Y  -> X
9373     if (Pred == ICmpInst::ICMP_NE)
9374       return ReplaceInstUsesWith(SI, TrueVal);
9375     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9376
9377   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9378     // Transform (X == Y) ? Y : X  -> X
9379     if (Pred == ICmpInst::ICMP_EQ)
9380       return ReplaceInstUsesWith(SI, FalseVal);
9381     // Transform (X != Y) ? Y : X  -> Y
9382     if (Pred == ICmpInst::ICMP_NE)
9383       return ReplaceInstUsesWith(SI, TrueVal);
9384     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9385   }
9386
9387   /// NOTE: if we wanted to, this is where to detect integer ABS
9388
9389   return Changed ? &SI : 0;
9390 }
9391
9392 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9393   Value *CondVal = SI.getCondition();
9394   Value *TrueVal = SI.getTrueValue();
9395   Value *FalseVal = SI.getFalseValue();
9396
9397   // select true, X, Y  -> X
9398   // select false, X, Y -> Y
9399   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9400     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9401
9402   // select C, X, X -> X
9403   if (TrueVal == FalseVal)
9404     return ReplaceInstUsesWith(SI, TrueVal);
9405
9406   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9407     return ReplaceInstUsesWith(SI, FalseVal);
9408   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9409     return ReplaceInstUsesWith(SI, TrueVal);
9410   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9411     if (isa<Constant>(TrueVal))
9412       return ReplaceInstUsesWith(SI, TrueVal);
9413     else
9414       return ReplaceInstUsesWith(SI, FalseVal);
9415   }
9416
9417   if (SI.getType() == Type::Int1Ty) {
9418     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9419       if (C->getZExtValue()) {
9420         // Change: A = select B, true, C --> A = or B, C
9421         return BinaryOperator::CreateOr(CondVal, FalseVal);
9422       } else {
9423         // Change: A = select B, false, C --> A = and !B, C
9424         Value *NotCond =
9425           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9426                                              "not."+CondVal->getName()), SI);
9427         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9428       }
9429     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9430       if (C->getZExtValue() == false) {
9431         // Change: A = select B, C, false --> A = and B, C
9432         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9433       } else {
9434         // Change: A = select B, C, true --> A = or !B, C
9435         Value *NotCond =
9436           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9437                                              "not."+CondVal->getName()), SI);
9438         return BinaryOperator::CreateOr(NotCond, TrueVal);
9439       }
9440     }
9441     
9442     // select a, b, a  -> a&b
9443     // select a, a, b  -> a|b
9444     if (CondVal == TrueVal)
9445       return BinaryOperator::CreateOr(CondVal, FalseVal);
9446     else if (CondVal == FalseVal)
9447       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9448   }
9449
9450   // Selecting between two integer constants?
9451   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9452     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9453       // select C, 1, 0 -> zext C to int
9454       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9455         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9456       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9457         // select C, 0, 1 -> zext !C to int
9458         Value *NotCond =
9459           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9460                                                "not."+CondVal->getName()), SI);
9461         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9462       }
9463
9464       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9465         // If one of the constants is zero (we know they can't both be) and we
9466         // have an icmp instruction with zero, and we have an 'and' with the
9467         // non-constant value, eliminate this whole mess.  This corresponds to
9468         // cases like this: ((X & 27) ? 27 : 0)
9469         if (TrueValC->isZero() || FalseValC->isZero())
9470           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9471               cast<Constant>(IC->getOperand(1))->isNullValue())
9472             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9473               if (ICA->getOpcode() == Instruction::And &&
9474                   isa<ConstantInt>(ICA->getOperand(1)) &&
9475                   (ICA->getOperand(1) == TrueValC ||
9476                    ICA->getOperand(1) == FalseValC) &&
9477                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9478                 // Okay, now we know that everything is set up, we just don't
9479                 // know whether we have a icmp_ne or icmp_eq and whether the 
9480                 // true or false val is the zero.
9481                 bool ShouldNotVal = !TrueValC->isZero();
9482                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9483                 Value *V = ICA;
9484                 if (ShouldNotVal)
9485                   V = InsertNewInstBefore(BinaryOperator::Create(
9486                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9487                 return ReplaceInstUsesWith(SI, V);
9488               }
9489       }
9490     }
9491
9492   // See if we are selecting two values based on a comparison of the two values.
9493   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9494     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9495       // Transform (X == Y) ? X : Y  -> Y
9496       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9497         // This is not safe in general for floating point:  
9498         // consider X== -0, Y== +0.
9499         // It becomes safe if either operand is a nonzero constant.
9500         ConstantFP *CFPt, *CFPf;
9501         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9502               !CFPt->getValueAPF().isZero()) ||
9503             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9504              !CFPf->getValueAPF().isZero()))
9505         return ReplaceInstUsesWith(SI, FalseVal);
9506       }
9507       // Transform (X != Y) ? X : Y  -> X
9508       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9509         return ReplaceInstUsesWith(SI, TrueVal);
9510       // NOTE: if we wanted to, this is where to detect MIN/MAX
9511
9512     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9513       // Transform (X == Y) ? Y : X  -> X
9514       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9515         // This is not safe in general for floating point:  
9516         // consider X== -0, Y== +0.
9517         // It becomes safe if either operand is a nonzero constant.
9518         ConstantFP *CFPt, *CFPf;
9519         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9520               !CFPt->getValueAPF().isZero()) ||
9521             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9522              !CFPf->getValueAPF().isZero()))
9523           return ReplaceInstUsesWith(SI, FalseVal);
9524       }
9525       // Transform (X != Y) ? Y : X  -> Y
9526       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9527         return ReplaceInstUsesWith(SI, TrueVal);
9528       // NOTE: if we wanted to, this is where to detect MIN/MAX
9529     }
9530     // NOTE: if we wanted to, this is where to detect ABS
9531   }
9532
9533   // See if we are selecting two values based on a comparison of the two values.
9534   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9535     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9536       return Result;
9537
9538   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9539     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9540       if (TI->hasOneUse() && FI->hasOneUse()) {
9541         Instruction *AddOp = 0, *SubOp = 0;
9542
9543         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9544         if (TI->getOpcode() == FI->getOpcode())
9545           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9546             return IV;
9547
9548         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9549         // even legal for FP.
9550         if ((TI->getOpcode() == Instruction::Sub &&
9551              FI->getOpcode() == Instruction::Add) ||
9552             (TI->getOpcode() == Instruction::FSub &&
9553              FI->getOpcode() == Instruction::FAdd)) {
9554           AddOp = FI; SubOp = TI;
9555         } else if ((FI->getOpcode() == Instruction::Sub &&
9556                     TI->getOpcode() == Instruction::Add) ||
9557                    (FI->getOpcode() == Instruction::FSub &&
9558                     TI->getOpcode() == Instruction::FAdd)) {
9559           AddOp = TI; SubOp = FI;
9560         }
9561
9562         if (AddOp) {
9563           Value *OtherAddOp = 0;
9564           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9565             OtherAddOp = AddOp->getOperand(1);
9566           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9567             OtherAddOp = AddOp->getOperand(0);
9568           }
9569
9570           if (OtherAddOp) {
9571             // So at this point we know we have (Y -> OtherAddOp):
9572             //        select C, (add X, Y), (sub X, Z)
9573             Value *NegVal;  // Compute -Z
9574             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9575               NegVal = Context->getConstantExprNeg(C);
9576             } else {
9577               NegVal = InsertNewInstBefore(
9578                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9579                                               "tmp"), SI);
9580             }
9581
9582             Value *NewTrueOp = OtherAddOp;
9583             Value *NewFalseOp = NegVal;
9584             if (AddOp != TI)
9585               std::swap(NewTrueOp, NewFalseOp);
9586             Instruction *NewSel =
9587               SelectInst::Create(CondVal, NewTrueOp,
9588                                  NewFalseOp, SI.getName() + ".p");
9589
9590             NewSel = InsertNewInstBefore(NewSel, SI);
9591             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9592           }
9593         }
9594       }
9595
9596   // See if we can fold the select into one of our operands.
9597   if (SI.getType()->isInteger()) {
9598     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9599     if (FoldI)
9600       return FoldI;
9601   }
9602
9603   if (BinaryOperator::isNot(CondVal)) {
9604     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9605     SI.setOperand(1, FalseVal);
9606     SI.setOperand(2, TrueVal);
9607     return &SI;
9608   }
9609
9610   return 0;
9611 }
9612
9613 /// EnforceKnownAlignment - If the specified pointer points to an object that
9614 /// we control, modify the object's alignment to PrefAlign. This isn't
9615 /// often possible though. If alignment is important, a more reliable approach
9616 /// is to simply align all global variables and allocation instructions to
9617 /// their preferred alignment from the beginning.
9618 ///
9619 static unsigned EnforceKnownAlignment(Value *V,
9620                                       unsigned Align, unsigned PrefAlign) {
9621
9622   User *U = dyn_cast<User>(V);
9623   if (!U) return Align;
9624
9625   switch (getOpcode(U)) {
9626   default: break;
9627   case Instruction::BitCast:
9628     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9629   case Instruction::GetElementPtr: {
9630     // If all indexes are zero, it is just the alignment of the base pointer.
9631     bool AllZeroOperands = true;
9632     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9633       if (!isa<Constant>(*i) ||
9634           !cast<Constant>(*i)->isNullValue()) {
9635         AllZeroOperands = false;
9636         break;
9637       }
9638
9639     if (AllZeroOperands) {
9640       // Treat this like a bitcast.
9641       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9642     }
9643     break;
9644   }
9645   }
9646
9647   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9648     // If there is a large requested alignment and we can, bump up the alignment
9649     // of the global.
9650     if (!GV->isDeclaration()) {
9651       if (GV->getAlignment() >= PrefAlign)
9652         Align = GV->getAlignment();
9653       else {
9654         GV->setAlignment(PrefAlign);
9655         Align = PrefAlign;
9656       }
9657     }
9658   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9659     // If there is a requested alignment and if this is an alloca, round up.  We
9660     // don't do this for malloc, because some systems can't respect the request.
9661     if (isa<AllocaInst>(AI)) {
9662       if (AI->getAlignment() >= PrefAlign)
9663         Align = AI->getAlignment();
9664       else {
9665         AI->setAlignment(PrefAlign);
9666         Align = PrefAlign;
9667       }
9668     }
9669   }
9670
9671   return Align;
9672 }
9673
9674 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9675 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9676 /// and it is more than the alignment of the ultimate object, see if we can
9677 /// increase the alignment of the ultimate object, making this check succeed.
9678 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9679                                                   unsigned PrefAlign) {
9680   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9681                       sizeof(PrefAlign) * CHAR_BIT;
9682   APInt Mask = APInt::getAllOnesValue(BitWidth);
9683   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9684   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9685   unsigned TrailZ = KnownZero.countTrailingOnes();
9686   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9687
9688   if (PrefAlign > Align)
9689     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9690   
9691     // We don't need to make any adjustment.
9692   return Align;
9693 }
9694
9695 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9696   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9697   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9698   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9699   unsigned CopyAlign = MI->getAlignment();
9700
9701   if (CopyAlign < MinAlign) {
9702     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9703                                              MinAlign, false));
9704     return MI;
9705   }
9706   
9707   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9708   // load/store.
9709   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9710   if (MemOpLength == 0) return 0;
9711   
9712   // Source and destination pointer types are always "i8*" for intrinsic.  See
9713   // if the size is something we can handle with a single primitive load/store.
9714   // A single load+store correctly handles overlapping memory in the memmove
9715   // case.
9716   unsigned Size = MemOpLength->getZExtValue();
9717   if (Size == 0) return MI;  // Delete this mem transfer.
9718   
9719   if (Size > 8 || (Size&(Size-1)))
9720     return 0;  // If not 1/2/4/8 bytes, exit.
9721   
9722   // Use an integer load+store unless we can find something better.
9723   Type *NewPtrTy =
9724                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9725   
9726   // Memcpy forces the use of i8* for the source and destination.  That means
9727   // that if you're using memcpy to move one double around, you'll get a cast
9728   // from double* to i8*.  We'd much rather use a double load+store rather than
9729   // an i64 load+store, here because this improves the odds that the source or
9730   // dest address will be promotable.  See if we can find a better type than the
9731   // integer datatype.
9732   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9733     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9734     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9735       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9736       // down through these levels if so.
9737       while (!SrcETy->isSingleValueType()) {
9738         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9739           if (STy->getNumElements() == 1)
9740             SrcETy = STy->getElementType(0);
9741           else
9742             break;
9743         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9744           if (ATy->getNumElements() == 1)
9745             SrcETy = ATy->getElementType();
9746           else
9747             break;
9748         } else
9749           break;
9750       }
9751       
9752       if (SrcETy->isSingleValueType())
9753         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9754     }
9755   }
9756   
9757   
9758   // If the memcpy/memmove provides better alignment info than we can
9759   // infer, use it.
9760   SrcAlign = std::max(SrcAlign, CopyAlign);
9761   DstAlign = std::max(DstAlign, CopyAlign);
9762   
9763   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9764   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9765   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9766   InsertNewInstBefore(L, *MI);
9767   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9768
9769   // Set the size of the copy to 0, it will be deleted on the next iteration.
9770   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9771   return MI;
9772 }
9773
9774 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9775   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9776   if (MI->getAlignment() < Alignment) {
9777     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9778                                              Alignment, false));
9779     return MI;
9780   }
9781   
9782   // Extract the length and alignment and fill if they are constant.
9783   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9784   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9785   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9786     return 0;
9787   uint64_t Len = LenC->getZExtValue();
9788   Alignment = MI->getAlignment();
9789   
9790   // If the length is zero, this is a no-op
9791   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9792   
9793   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9794   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9795     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9796     
9797     Value *Dest = MI->getDest();
9798     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9799
9800     // Alignment 0 is identity for alignment 1 for memset, but not store.
9801     if (Alignment == 0) Alignment = 1;
9802     
9803     // Extract the fill value and store.
9804     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9805     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9806                                       Dest, false, Alignment), *MI);
9807     
9808     // Set the size of the copy to 0, it will be deleted on the next iteration.
9809     MI->setLength(Context->getNullValue(LenC->getType()));
9810     return MI;
9811   }
9812
9813   return 0;
9814 }
9815
9816
9817 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9818 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9819 /// the heavy lifting.
9820 ///
9821 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9822   // If the caller function is nounwind, mark the call as nounwind, even if the
9823   // callee isn't.
9824   if (CI.getParent()->getParent()->doesNotThrow() &&
9825       !CI.doesNotThrow()) {
9826     CI.setDoesNotThrow();
9827     return &CI;
9828   }
9829   
9830   
9831   
9832   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9833   if (!II) return visitCallSite(&CI);
9834   
9835   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9836   // visitCallSite.
9837   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9838     bool Changed = false;
9839
9840     // memmove/cpy/set of zero bytes is a noop.
9841     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9842       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9843
9844       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9845         if (CI->getZExtValue() == 1) {
9846           // Replace the instruction with just byte operations.  We would
9847           // transform other cases to loads/stores, but we don't know if
9848           // alignment is sufficient.
9849         }
9850     }
9851
9852     // If we have a memmove and the source operation is a constant global,
9853     // then the source and dest pointers can't alias, so we can change this
9854     // into a call to memcpy.
9855     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9856       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9857         if (GVSrc->isConstant()) {
9858           Module *M = CI.getParent()->getParent()->getParent();
9859           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9860           const Type *Tys[1];
9861           Tys[0] = CI.getOperand(3)->getType();
9862           CI.setOperand(0, 
9863                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9864           Changed = true;
9865         }
9866
9867       // memmove(x,x,size) -> noop.
9868       if (MMI->getSource() == MMI->getDest())
9869         return EraseInstFromFunction(CI);
9870     }
9871
9872     // If we can determine a pointer alignment that is bigger than currently
9873     // set, update the alignment.
9874     if (isa<MemTransferInst>(MI)) {
9875       if (Instruction *I = SimplifyMemTransfer(MI))
9876         return I;
9877     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9878       if (Instruction *I = SimplifyMemSet(MSI))
9879         return I;
9880     }
9881           
9882     if (Changed) return II;
9883   }
9884   
9885   switch (II->getIntrinsicID()) {
9886   default: break;
9887   case Intrinsic::bswap:
9888     // bswap(bswap(x)) -> x
9889     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9890       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9891         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9892     break;
9893   case Intrinsic::ppc_altivec_lvx:
9894   case Intrinsic::ppc_altivec_lvxl:
9895   case Intrinsic::x86_sse_loadu_ps:
9896   case Intrinsic::x86_sse2_loadu_pd:
9897   case Intrinsic::x86_sse2_loadu_dq:
9898     // Turn PPC lvx     -> load if the pointer is known aligned.
9899     // Turn X86 loadups -> load if the pointer is known aligned.
9900     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9901       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9902                                    Context->getPointerTypeUnqual(II->getType()),
9903                                        CI);
9904       return new LoadInst(Ptr);
9905     }
9906     break;
9907   case Intrinsic::ppc_altivec_stvx:
9908   case Intrinsic::ppc_altivec_stvxl:
9909     // Turn stvx -> store if the pointer is known aligned.
9910     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9911       const Type *OpPtrTy = 
9912         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9913       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9914       return new StoreInst(II->getOperand(1), Ptr);
9915     }
9916     break;
9917   case Intrinsic::x86_sse_storeu_ps:
9918   case Intrinsic::x86_sse2_storeu_pd:
9919   case Intrinsic::x86_sse2_storeu_dq:
9920     // Turn X86 storeu -> store if the pointer is known aligned.
9921     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9922       const Type *OpPtrTy = 
9923         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9924       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9925       return new StoreInst(II->getOperand(2), Ptr);
9926     }
9927     break;
9928     
9929   case Intrinsic::x86_sse_cvttss2si: {
9930     // These intrinsics only demands the 0th element of its input vector.  If
9931     // we can simplify the input based on that, do so now.
9932     unsigned VWidth =
9933       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9934     APInt DemandedElts(VWidth, 1);
9935     APInt UndefElts(VWidth, 0);
9936     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9937                                               UndefElts)) {
9938       II->setOperand(1, V);
9939       return II;
9940     }
9941     break;
9942   }
9943     
9944   case Intrinsic::ppc_altivec_vperm:
9945     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9946     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9947       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9948       
9949       // Check that all of the elements are integer constants or undefs.
9950       bool AllEltsOk = true;
9951       for (unsigned i = 0; i != 16; ++i) {
9952         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9953             !isa<UndefValue>(Mask->getOperand(i))) {
9954           AllEltsOk = false;
9955           break;
9956         }
9957       }
9958       
9959       if (AllEltsOk) {
9960         // Cast the input vectors to byte vectors.
9961         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9962         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9963         Value *Result = Context->getUndef(Op0->getType());
9964         
9965         // Only extract each element once.
9966         Value *ExtractedElts[32];
9967         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9968         
9969         for (unsigned i = 0; i != 16; ++i) {
9970           if (isa<UndefValue>(Mask->getOperand(i)))
9971             continue;
9972           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9973           Idx &= 31;  // Match the hardware behavior.
9974           
9975           if (ExtractedElts[Idx] == 0) {
9976             Instruction *Elt = 
9977               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9978             InsertNewInstBefore(Elt, CI);
9979             ExtractedElts[Idx] = Elt;
9980           }
9981         
9982           // Insert this value into the result vector.
9983           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9984                                              i, "tmp");
9985           InsertNewInstBefore(cast<Instruction>(Result), CI);
9986         }
9987         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9988       }
9989     }
9990     break;
9991
9992   case Intrinsic::stackrestore: {
9993     // If the save is right next to the restore, remove the restore.  This can
9994     // happen when variable allocas are DCE'd.
9995     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9996       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9997         BasicBlock::iterator BI = SS;
9998         if (&*++BI == II)
9999           return EraseInstFromFunction(CI);
10000       }
10001     }
10002     
10003     // Scan down this block to see if there is another stack restore in the
10004     // same block without an intervening call/alloca.
10005     BasicBlock::iterator BI = II;
10006     TerminatorInst *TI = II->getParent()->getTerminator();
10007     bool CannotRemove = false;
10008     for (++BI; &*BI != TI; ++BI) {
10009       if (isa<AllocaInst>(BI)) {
10010         CannotRemove = true;
10011         break;
10012       }
10013       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10014         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10015           // If there is a stackrestore below this one, remove this one.
10016           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10017             return EraseInstFromFunction(CI);
10018           // Otherwise, ignore the intrinsic.
10019         } else {
10020           // If we found a non-intrinsic call, we can't remove the stack
10021           // restore.
10022           CannotRemove = true;
10023           break;
10024         }
10025       }
10026     }
10027     
10028     // If the stack restore is in a return/unwind block and if there are no
10029     // allocas or calls between the restore and the return, nuke the restore.
10030     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10031       return EraseInstFromFunction(CI);
10032     break;
10033   }
10034   }
10035
10036   return visitCallSite(II);
10037 }
10038
10039 // InvokeInst simplification
10040 //
10041 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10042   return visitCallSite(&II);
10043 }
10044
10045 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10046 /// passed through the varargs area, we can eliminate the use of the cast.
10047 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10048                                          const CastInst * const CI,
10049                                          const TargetData * const TD,
10050                                          const int ix) {
10051   if (!CI->isLosslessCast())
10052     return false;
10053
10054   // The size of ByVal arguments is derived from the type, so we
10055   // can't change to a type with a different size.  If the size were
10056   // passed explicitly we could avoid this check.
10057   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10058     return true;
10059
10060   const Type* SrcTy = 
10061             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10062   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10063   if (!SrcTy->isSized() || !DstTy->isSized())
10064     return false;
10065   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10066     return false;
10067   return true;
10068 }
10069
10070 // visitCallSite - Improvements for call and invoke instructions.
10071 //
10072 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10073   bool Changed = false;
10074
10075   // If the callee is a constexpr cast of a function, attempt to move the cast
10076   // to the arguments of the call/invoke.
10077   if (transformConstExprCastCall(CS)) return 0;
10078
10079   Value *Callee = CS.getCalledValue();
10080
10081   if (Function *CalleeF = dyn_cast<Function>(Callee))
10082     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10083       Instruction *OldCall = CS.getInstruction();
10084       // If the call and callee calling conventions don't match, this call must
10085       // be unreachable, as the call is undefined.
10086       new StoreInst(Context->getConstantIntTrue(),
10087                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10088                                   OldCall);
10089       if (!OldCall->use_empty())
10090         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10091       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10092         return EraseInstFromFunction(*OldCall);
10093       return 0;
10094     }
10095
10096   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10097     // This instruction is not reachable, just remove it.  We insert a store to
10098     // undef so that we know that this code is not reachable, despite the fact
10099     // that we can't modify the CFG here.
10100     new StoreInst(Context->getConstantIntTrue(),
10101                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10102                   CS.getInstruction());
10103
10104     if (!CS.getInstruction()->use_empty())
10105       CS.getInstruction()->
10106         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10107
10108     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10109       // Don't break the CFG, insert a dummy cond branch.
10110       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10111                          Context->getConstantIntTrue(), II);
10112     }
10113     return EraseInstFromFunction(*CS.getInstruction());
10114   }
10115
10116   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10117     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10118       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10119         return transformCallThroughTrampoline(CS);
10120
10121   const PointerType *PTy = cast<PointerType>(Callee->getType());
10122   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10123   if (FTy->isVarArg()) {
10124     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10125     // See if we can optimize any arguments passed through the varargs area of
10126     // the call.
10127     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10128            E = CS.arg_end(); I != E; ++I, ++ix) {
10129       CastInst *CI = dyn_cast<CastInst>(*I);
10130       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10131         *I = CI->getOperand(0);
10132         Changed = true;
10133       }
10134     }
10135   }
10136
10137   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10138     // Inline asm calls cannot throw - mark them 'nounwind'.
10139     CS.setDoesNotThrow();
10140     Changed = true;
10141   }
10142
10143   return Changed ? CS.getInstruction() : 0;
10144 }
10145
10146 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10147 // attempt to move the cast to the arguments of the call/invoke.
10148 //
10149 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10150   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10151   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10152   if (CE->getOpcode() != Instruction::BitCast || 
10153       !isa<Function>(CE->getOperand(0)))
10154     return false;
10155   Function *Callee = cast<Function>(CE->getOperand(0));
10156   Instruction *Caller = CS.getInstruction();
10157   const AttrListPtr &CallerPAL = CS.getAttributes();
10158
10159   // Okay, this is a cast from a function to a different type.  Unless doing so
10160   // would cause a type conversion of one of our arguments, change this call to
10161   // be a direct call with arguments casted to the appropriate types.
10162   //
10163   const FunctionType *FT = Callee->getFunctionType();
10164   const Type *OldRetTy = Caller->getType();
10165   const Type *NewRetTy = FT->getReturnType();
10166
10167   if (isa<StructType>(NewRetTy))
10168     return false; // TODO: Handle multiple return values.
10169
10170   // Check to see if we are changing the return type...
10171   if (OldRetTy != NewRetTy) {
10172     if (Callee->isDeclaration() &&
10173         // Conversion is ok if changing from one pointer type to another or from
10174         // a pointer to an integer of the same size.
10175         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10176           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10177       return false;   // Cannot transform this return value.
10178
10179     if (!Caller->use_empty() &&
10180         // void -> non-void is handled specially
10181         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10182       return false;   // Cannot transform this return value.
10183
10184     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10185       Attributes RAttrs = CallerPAL.getRetAttributes();
10186       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10187         return false;   // Attribute not compatible with transformed value.
10188     }
10189
10190     // If the callsite is an invoke instruction, and the return value is used by
10191     // a PHI node in a successor, we cannot change the return type of the call
10192     // because there is no place to put the cast instruction (without breaking
10193     // the critical edge).  Bail out in this case.
10194     if (!Caller->use_empty())
10195       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10196         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10197              UI != E; ++UI)
10198           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10199             if (PN->getParent() == II->getNormalDest() ||
10200                 PN->getParent() == II->getUnwindDest())
10201               return false;
10202   }
10203
10204   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10205   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10206
10207   CallSite::arg_iterator AI = CS.arg_begin();
10208   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10209     const Type *ParamTy = FT->getParamType(i);
10210     const Type *ActTy = (*AI)->getType();
10211
10212     if (!CastInst::isCastable(ActTy, ParamTy))
10213       return false;   // Cannot transform this parameter value.
10214
10215     if (CallerPAL.getParamAttributes(i + 1) 
10216         & Attribute::typeIncompatible(ParamTy))
10217       return false;   // Attribute not compatible with transformed value.
10218
10219     // Converting from one pointer type to another or between a pointer and an
10220     // integer of the same size is safe even if we do not have a body.
10221     bool isConvertible = ActTy == ParamTy ||
10222       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10223        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10224     if (Callee->isDeclaration() && !isConvertible) return false;
10225   }
10226
10227   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10228       Callee->isDeclaration())
10229     return false;   // Do not delete arguments unless we have a function body.
10230
10231   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10232       !CallerPAL.isEmpty())
10233     // In this case we have more arguments than the new function type, but we
10234     // won't be dropping them.  Check that these extra arguments have attributes
10235     // that are compatible with being a vararg call argument.
10236     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10237       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10238         break;
10239       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10240       if (PAttrs & Attribute::VarArgsIncompatible)
10241         return false;
10242     }
10243
10244   // Okay, we decided that this is a safe thing to do: go ahead and start
10245   // inserting cast instructions as necessary...
10246   std::vector<Value*> Args;
10247   Args.reserve(NumActualArgs);
10248   SmallVector<AttributeWithIndex, 8> attrVec;
10249   attrVec.reserve(NumCommonArgs);
10250
10251   // Get any return attributes.
10252   Attributes RAttrs = CallerPAL.getRetAttributes();
10253
10254   // If the return value is not being used, the type may not be compatible
10255   // with the existing attributes.  Wipe out any problematic attributes.
10256   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10257
10258   // Add the new return attributes.
10259   if (RAttrs)
10260     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10261
10262   AI = CS.arg_begin();
10263   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10264     const Type *ParamTy = FT->getParamType(i);
10265     if ((*AI)->getType() == ParamTy) {
10266       Args.push_back(*AI);
10267     } else {
10268       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10269           false, ParamTy, false);
10270       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10271       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10272     }
10273
10274     // Add any parameter attributes.
10275     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10276       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10277   }
10278
10279   // If the function takes more arguments than the call was taking, add them
10280   // now...
10281   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10282     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10283
10284   // If we are removing arguments to the function, emit an obnoxious warning...
10285   if (FT->getNumParams() < NumActualArgs) {
10286     if (!FT->isVarArg()) {
10287       cerr << "WARNING: While resolving call to function '"
10288            << Callee->getName() << "' arguments were dropped!\n";
10289     } else {
10290       // Add all of the arguments in their promoted form to the arg list...
10291       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10292         const Type *PTy = getPromotedType((*AI)->getType());
10293         if (PTy != (*AI)->getType()) {
10294           // Must promote to pass through va_arg area!
10295           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10296                                                                 PTy, false);
10297           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10298           InsertNewInstBefore(Cast, *Caller);
10299           Args.push_back(Cast);
10300         } else {
10301           Args.push_back(*AI);
10302         }
10303
10304         // Add any parameter attributes.
10305         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10306           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10307       }
10308     }
10309   }
10310
10311   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10312     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10313
10314   if (NewRetTy == Type::VoidTy)
10315     Caller->setName("");   // Void type should not have a name.
10316
10317   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10318
10319   Instruction *NC;
10320   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10321     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10322                             Args.begin(), Args.end(),
10323                             Caller->getName(), Caller);
10324     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10325     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10326   } else {
10327     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10328                           Caller->getName(), Caller);
10329     CallInst *CI = cast<CallInst>(Caller);
10330     if (CI->isTailCall())
10331       cast<CallInst>(NC)->setTailCall();
10332     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10333     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10334   }
10335
10336   // Insert a cast of the return type as necessary.
10337   Value *NV = NC;
10338   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10339     if (NV->getType() != Type::VoidTy) {
10340       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10341                                                             OldRetTy, false);
10342       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10343
10344       // If this is an invoke instruction, we should insert it after the first
10345       // non-phi, instruction in the normal successor block.
10346       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10347         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10348         InsertNewInstBefore(NC, *I);
10349       } else {
10350         // Otherwise, it's a call, just insert cast right after the call instr
10351         InsertNewInstBefore(NC, *Caller);
10352       }
10353       AddUsersToWorkList(*Caller);
10354     } else {
10355       NV = Context->getUndef(Caller->getType());
10356     }
10357   }
10358
10359   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10360     Caller->replaceAllUsesWith(NV);
10361   Caller->eraseFromParent();
10362   RemoveFromWorkList(Caller);
10363   return true;
10364 }
10365
10366 // transformCallThroughTrampoline - Turn a call to a function created by the
10367 // init_trampoline intrinsic into a direct call to the underlying function.
10368 //
10369 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10370   Value *Callee = CS.getCalledValue();
10371   const PointerType *PTy = cast<PointerType>(Callee->getType());
10372   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10373   const AttrListPtr &Attrs = CS.getAttributes();
10374
10375   // If the call already has the 'nest' attribute somewhere then give up -
10376   // otherwise 'nest' would occur twice after splicing in the chain.
10377   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10378     return 0;
10379
10380   IntrinsicInst *Tramp =
10381     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10382
10383   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10384   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10385   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10386
10387   const AttrListPtr &NestAttrs = NestF->getAttributes();
10388   if (!NestAttrs.isEmpty()) {
10389     unsigned NestIdx = 1;
10390     const Type *NestTy = 0;
10391     Attributes NestAttr = Attribute::None;
10392
10393     // Look for a parameter marked with the 'nest' attribute.
10394     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10395          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10396       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10397         // Record the parameter type and any other attributes.
10398         NestTy = *I;
10399         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10400         break;
10401       }
10402
10403     if (NestTy) {
10404       Instruction *Caller = CS.getInstruction();
10405       std::vector<Value*> NewArgs;
10406       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10407
10408       SmallVector<AttributeWithIndex, 8> NewAttrs;
10409       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10410
10411       // Insert the nest argument into the call argument list, which may
10412       // mean appending it.  Likewise for attributes.
10413
10414       // Add any result attributes.
10415       if (Attributes Attr = Attrs.getRetAttributes())
10416         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10417
10418       {
10419         unsigned Idx = 1;
10420         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10421         do {
10422           if (Idx == NestIdx) {
10423             // Add the chain argument and attributes.
10424             Value *NestVal = Tramp->getOperand(3);
10425             if (NestVal->getType() != NestTy)
10426               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10427             NewArgs.push_back(NestVal);
10428             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10429           }
10430
10431           if (I == E)
10432             break;
10433
10434           // Add the original argument and attributes.
10435           NewArgs.push_back(*I);
10436           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10437             NewAttrs.push_back
10438               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10439
10440           ++Idx, ++I;
10441         } while (1);
10442       }
10443
10444       // Add any function attributes.
10445       if (Attributes Attr = Attrs.getFnAttributes())
10446         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10447
10448       // The trampoline may have been bitcast to a bogus type (FTy).
10449       // Handle this by synthesizing a new function type, equal to FTy
10450       // with the chain parameter inserted.
10451
10452       std::vector<const Type*> NewTypes;
10453       NewTypes.reserve(FTy->getNumParams()+1);
10454
10455       // Insert the chain's type into the list of parameter types, which may
10456       // mean appending it.
10457       {
10458         unsigned Idx = 1;
10459         FunctionType::param_iterator I = FTy->param_begin(),
10460           E = FTy->param_end();
10461
10462         do {
10463           if (Idx == NestIdx)
10464             // Add the chain's type.
10465             NewTypes.push_back(NestTy);
10466
10467           if (I == E)
10468             break;
10469
10470           // Add the original type.
10471           NewTypes.push_back(*I);
10472
10473           ++Idx, ++I;
10474         } while (1);
10475       }
10476
10477       // Replace the trampoline call with a direct call.  Let the generic
10478       // code sort out any function type mismatches.
10479       FunctionType *NewFTy =
10480                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10481                                                 FTy->isVarArg());
10482       Constant *NewCallee =
10483         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10484         NestF : Context->getConstantExprBitCast(NestF, 
10485                                          Context->getPointerTypeUnqual(NewFTy));
10486       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10487
10488       Instruction *NewCaller;
10489       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10490         NewCaller = InvokeInst::Create(NewCallee,
10491                                        II->getNormalDest(), II->getUnwindDest(),
10492                                        NewArgs.begin(), NewArgs.end(),
10493                                        Caller->getName(), Caller);
10494         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10495         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10496       } else {
10497         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10498                                      Caller->getName(), Caller);
10499         if (cast<CallInst>(Caller)->isTailCall())
10500           cast<CallInst>(NewCaller)->setTailCall();
10501         cast<CallInst>(NewCaller)->
10502           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10503         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10504       }
10505       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10506         Caller->replaceAllUsesWith(NewCaller);
10507       Caller->eraseFromParent();
10508       RemoveFromWorkList(Caller);
10509       return 0;
10510     }
10511   }
10512
10513   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10514   // parameter, there is no need to adjust the argument list.  Let the generic
10515   // code sort out any function type mismatches.
10516   Constant *NewCallee =
10517     NestF->getType() == PTy ? NestF : 
10518                               Context->getConstantExprBitCast(NestF, PTy);
10519   CS.setCalledFunction(NewCallee);
10520   return CS.getInstruction();
10521 }
10522
10523 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10524 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10525 /// and a single binop.
10526 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10527   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10528   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10529   unsigned Opc = FirstInst->getOpcode();
10530   Value *LHSVal = FirstInst->getOperand(0);
10531   Value *RHSVal = FirstInst->getOperand(1);
10532     
10533   const Type *LHSType = LHSVal->getType();
10534   const Type *RHSType = RHSVal->getType();
10535   
10536   // Scan to see if all operands are the same opcode, all have one use, and all
10537   // kill their operands (i.e. the operands have one use).
10538   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10539     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10540     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10541         // Verify type of the LHS matches so we don't fold cmp's of different
10542         // types or GEP's with different index types.
10543         I->getOperand(0)->getType() != LHSType ||
10544         I->getOperand(1)->getType() != RHSType)
10545       return 0;
10546
10547     // If they are CmpInst instructions, check their predicates
10548     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10549       if (cast<CmpInst>(I)->getPredicate() !=
10550           cast<CmpInst>(FirstInst)->getPredicate())
10551         return 0;
10552     
10553     // Keep track of which operand needs a phi node.
10554     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10555     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10556   }
10557   
10558   // Otherwise, this is safe to transform!
10559   
10560   Value *InLHS = FirstInst->getOperand(0);
10561   Value *InRHS = FirstInst->getOperand(1);
10562   PHINode *NewLHS = 0, *NewRHS = 0;
10563   if (LHSVal == 0) {
10564     NewLHS = PHINode::Create(LHSType,
10565                              FirstInst->getOperand(0)->getName() + ".pn");
10566     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10567     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10568     InsertNewInstBefore(NewLHS, PN);
10569     LHSVal = NewLHS;
10570   }
10571   
10572   if (RHSVal == 0) {
10573     NewRHS = PHINode::Create(RHSType,
10574                              FirstInst->getOperand(1)->getName() + ".pn");
10575     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10576     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10577     InsertNewInstBefore(NewRHS, PN);
10578     RHSVal = NewRHS;
10579   }
10580   
10581   // Add all operands to the new PHIs.
10582   if (NewLHS || NewRHS) {
10583     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10584       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10585       if (NewLHS) {
10586         Value *NewInLHS = InInst->getOperand(0);
10587         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10588       }
10589       if (NewRHS) {
10590         Value *NewInRHS = InInst->getOperand(1);
10591         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10592       }
10593     }
10594   }
10595     
10596   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10597     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10598   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10599   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10600                          LHSVal, RHSVal);
10601 }
10602
10603 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10604   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10605   
10606   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10607                                         FirstInst->op_end());
10608   // This is true if all GEP bases are allocas and if all indices into them are
10609   // constants.
10610   bool AllBasePointersAreAllocas = true;
10611   
10612   // Scan to see if all operands are the same opcode, all have one use, and all
10613   // kill their operands (i.e. the operands have one use).
10614   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10615     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10616     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10617       GEP->getNumOperands() != FirstInst->getNumOperands())
10618       return 0;
10619
10620     // Keep track of whether or not all GEPs are of alloca pointers.
10621     if (AllBasePointersAreAllocas &&
10622         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10623          !GEP->hasAllConstantIndices()))
10624       AllBasePointersAreAllocas = false;
10625     
10626     // Compare the operand lists.
10627     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10628       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10629         continue;
10630       
10631       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10632       // if one of the PHIs has a constant for the index.  The index may be
10633       // substantially cheaper to compute for the constants, so making it a
10634       // variable index could pessimize the path.  This also handles the case
10635       // for struct indices, which must always be constant.
10636       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10637           isa<ConstantInt>(GEP->getOperand(op)))
10638         return 0;
10639       
10640       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10641         return 0;
10642       FixedOperands[op] = 0;  // Needs a PHI.
10643     }
10644   }
10645   
10646   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10647   // bother doing this transformation.  At best, this will just save a bit of
10648   // offset calculation, but all the predecessors will have to materialize the
10649   // stack address into a register anyway.  We'd actually rather *clone* the
10650   // load up into the predecessors so that we have a load of a gep of an alloca,
10651   // which can usually all be folded into the load.
10652   if (AllBasePointersAreAllocas)
10653     return 0;
10654   
10655   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10656   // that is variable.
10657   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10658   
10659   bool HasAnyPHIs = false;
10660   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10661     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10662     Value *FirstOp = FirstInst->getOperand(i);
10663     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10664                                      FirstOp->getName()+".pn");
10665     InsertNewInstBefore(NewPN, PN);
10666     
10667     NewPN->reserveOperandSpace(e);
10668     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10669     OperandPhis[i] = NewPN;
10670     FixedOperands[i] = NewPN;
10671     HasAnyPHIs = true;
10672   }
10673
10674   
10675   // Add all operands to the new PHIs.
10676   if (HasAnyPHIs) {
10677     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10678       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10679       BasicBlock *InBB = PN.getIncomingBlock(i);
10680       
10681       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10682         if (PHINode *OpPhi = OperandPhis[op])
10683           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10684     }
10685   }
10686   
10687   Value *Base = FixedOperands[0];
10688   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10689                                    FixedOperands.end());
10690 }
10691
10692
10693 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10694 /// sink the load out of the block that defines it.  This means that it must be
10695 /// obvious the value of the load is not changed from the point of the load to
10696 /// the end of the block it is in.
10697 ///
10698 /// Finally, it is safe, but not profitable, to sink a load targetting a
10699 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10700 /// to a register.
10701 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10702   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10703   
10704   for (++BBI; BBI != E; ++BBI)
10705     if (BBI->mayWriteToMemory())
10706       return false;
10707   
10708   // Check for non-address taken alloca.  If not address-taken already, it isn't
10709   // profitable to do this xform.
10710   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10711     bool isAddressTaken = false;
10712     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10713          UI != E; ++UI) {
10714       if (isa<LoadInst>(UI)) continue;
10715       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10716         // If storing TO the alloca, then the address isn't taken.
10717         if (SI->getOperand(1) == AI) continue;
10718       }
10719       isAddressTaken = true;
10720       break;
10721     }
10722     
10723     if (!isAddressTaken && AI->isStaticAlloca())
10724       return false;
10725   }
10726   
10727   // If this load is a load from a GEP with a constant offset from an alloca,
10728   // then we don't want to sink it.  In its present form, it will be
10729   // load [constant stack offset].  Sinking it will cause us to have to
10730   // materialize the stack addresses in each predecessor in a register only to
10731   // do a shared load from register in the successor.
10732   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10733     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10734       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10735         return false;
10736   
10737   return true;
10738 }
10739
10740
10741 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10742 // operator and they all are only used by the PHI, PHI together their
10743 // inputs, and do the operation once, to the result of the PHI.
10744 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10745   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10746
10747   // Scan the instruction, looking for input operations that can be folded away.
10748   // If all input operands to the phi are the same instruction (e.g. a cast from
10749   // the same type or "+42") we can pull the operation through the PHI, reducing
10750   // code size and simplifying code.
10751   Constant *ConstantOp = 0;
10752   const Type *CastSrcTy = 0;
10753   bool isVolatile = false;
10754   if (isa<CastInst>(FirstInst)) {
10755     CastSrcTy = FirstInst->getOperand(0)->getType();
10756   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10757     // Can fold binop, compare or shift here if the RHS is a constant, 
10758     // otherwise call FoldPHIArgBinOpIntoPHI.
10759     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10760     if (ConstantOp == 0)
10761       return FoldPHIArgBinOpIntoPHI(PN);
10762   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10763     isVolatile = LI->isVolatile();
10764     // We can't sink the load if the loaded value could be modified between the
10765     // load and the PHI.
10766     if (LI->getParent() != PN.getIncomingBlock(0) ||
10767         !isSafeAndProfitableToSinkLoad(LI))
10768       return 0;
10769     
10770     // If the PHI is of volatile loads and the load block has multiple
10771     // successors, sinking it would remove a load of the volatile value from
10772     // the path through the other successor.
10773     if (isVolatile &&
10774         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10775       return 0;
10776     
10777   } else if (isa<GetElementPtrInst>(FirstInst)) {
10778     return FoldPHIArgGEPIntoPHI(PN);
10779   } else {
10780     return 0;  // Cannot fold this operation.
10781   }
10782
10783   // Check to see if all arguments are the same operation.
10784   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10785     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10786     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10787     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10788       return 0;
10789     if (CastSrcTy) {
10790       if (I->getOperand(0)->getType() != CastSrcTy)
10791         return 0;  // Cast operation must match.
10792     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10793       // We can't sink the load if the loaded value could be modified between 
10794       // the load and the PHI.
10795       if (LI->isVolatile() != isVolatile ||
10796           LI->getParent() != PN.getIncomingBlock(i) ||
10797           !isSafeAndProfitableToSinkLoad(LI))
10798         return 0;
10799       
10800       // If the PHI is of volatile loads and the load block has multiple
10801       // successors, sinking it would remove a load of the volatile value from
10802       // the path through the other successor.
10803       if (isVolatile &&
10804           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10805         return 0;
10806       
10807     } else if (I->getOperand(1) != ConstantOp) {
10808       return 0;
10809     }
10810   }
10811
10812   // Okay, they are all the same operation.  Create a new PHI node of the
10813   // correct type, and PHI together all of the LHS's of the instructions.
10814   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10815                                    PN.getName()+".in");
10816   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10817
10818   Value *InVal = FirstInst->getOperand(0);
10819   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10820
10821   // Add all operands to the new PHI.
10822   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10823     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10824     if (NewInVal != InVal)
10825       InVal = 0;
10826     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10827   }
10828
10829   Value *PhiVal;
10830   if (InVal) {
10831     // The new PHI unions all of the same values together.  This is really
10832     // common, so we handle it intelligently here for compile-time speed.
10833     PhiVal = InVal;
10834     delete NewPN;
10835   } else {
10836     InsertNewInstBefore(NewPN, PN);
10837     PhiVal = NewPN;
10838   }
10839
10840   // Insert and return the new operation.
10841   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10842     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10843   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10844     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10845   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10846     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10847                            PhiVal, ConstantOp);
10848   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10849   
10850   // If this was a volatile load that we are merging, make sure to loop through
10851   // and mark all the input loads as non-volatile.  If we don't do this, we will
10852   // insert a new volatile load and the old ones will not be deletable.
10853   if (isVolatile)
10854     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10855       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10856   
10857   return new LoadInst(PhiVal, "", isVolatile);
10858 }
10859
10860 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10861 /// that is dead.
10862 static bool DeadPHICycle(PHINode *PN,
10863                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10864   if (PN->use_empty()) return true;
10865   if (!PN->hasOneUse()) return false;
10866
10867   // Remember this node, and if we find the cycle, return.
10868   if (!PotentiallyDeadPHIs.insert(PN))
10869     return true;
10870   
10871   // Don't scan crazily complex things.
10872   if (PotentiallyDeadPHIs.size() == 16)
10873     return false;
10874
10875   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10876     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10877
10878   return false;
10879 }
10880
10881 /// PHIsEqualValue - Return true if this phi node is always equal to
10882 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10883 ///   z = some value; x = phi (y, z); y = phi (x, z)
10884 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10885                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10886   // See if we already saw this PHI node.
10887   if (!ValueEqualPHIs.insert(PN))
10888     return true;
10889   
10890   // Don't scan crazily complex things.
10891   if (ValueEqualPHIs.size() == 16)
10892     return false;
10893  
10894   // Scan the operands to see if they are either phi nodes or are equal to
10895   // the value.
10896   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10897     Value *Op = PN->getIncomingValue(i);
10898     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10899       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10900         return false;
10901     } else if (Op != NonPhiInVal)
10902       return false;
10903   }
10904   
10905   return true;
10906 }
10907
10908
10909 // PHINode simplification
10910 //
10911 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10912   // If LCSSA is around, don't mess with Phi nodes
10913   if (MustPreserveLCSSA) return 0;
10914   
10915   if (Value *V = PN.hasConstantValue())
10916     return ReplaceInstUsesWith(PN, V);
10917
10918   // If all PHI operands are the same operation, pull them through the PHI,
10919   // reducing code size.
10920   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10921       isa<Instruction>(PN.getIncomingValue(1)) &&
10922       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10923       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10924       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10925       // than themselves more than once.
10926       PN.getIncomingValue(0)->hasOneUse())
10927     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10928       return Result;
10929
10930   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10931   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10932   // PHI)... break the cycle.
10933   if (PN.hasOneUse()) {
10934     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10935     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10936       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10937       PotentiallyDeadPHIs.insert(&PN);
10938       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10939         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10940     }
10941    
10942     // If this phi has a single use, and if that use just computes a value for
10943     // the next iteration of a loop, delete the phi.  This occurs with unused
10944     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10945     // common case here is good because the only other things that catch this
10946     // are induction variable analysis (sometimes) and ADCE, which is only run
10947     // late.
10948     if (PHIUser->hasOneUse() &&
10949         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10950         PHIUser->use_back() == &PN) {
10951       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10952     }
10953   }
10954
10955   // We sometimes end up with phi cycles that non-obviously end up being the
10956   // same value, for example:
10957   //   z = some value; x = phi (y, z); y = phi (x, z)
10958   // where the phi nodes don't necessarily need to be in the same block.  Do a
10959   // quick check to see if the PHI node only contains a single non-phi value, if
10960   // so, scan to see if the phi cycle is actually equal to that value.
10961   {
10962     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10963     // Scan for the first non-phi operand.
10964     while (InValNo != NumOperandVals && 
10965            isa<PHINode>(PN.getIncomingValue(InValNo)))
10966       ++InValNo;
10967
10968     if (InValNo != NumOperandVals) {
10969       Value *NonPhiInVal = PN.getOperand(InValNo);
10970       
10971       // Scan the rest of the operands to see if there are any conflicts, if so
10972       // there is no need to recursively scan other phis.
10973       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10974         Value *OpVal = PN.getIncomingValue(InValNo);
10975         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10976           break;
10977       }
10978       
10979       // If we scanned over all operands, then we have one unique value plus
10980       // phi values.  Scan PHI nodes to see if they all merge in each other or
10981       // the value.
10982       if (InValNo == NumOperandVals) {
10983         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10984         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10985           return ReplaceInstUsesWith(PN, NonPhiInVal);
10986       }
10987     }
10988   }
10989   return 0;
10990 }
10991
10992 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10993                                    Instruction *InsertPoint,
10994                                    InstCombiner *IC) {
10995   unsigned PtrSize = DTy->getScalarSizeInBits();
10996   unsigned VTySize = V->getType()->getScalarSizeInBits();
10997   // We must cast correctly to the pointer type. Ensure that we
10998   // sign extend the integer value if it is smaller as this is
10999   // used for address computation.
11000   Instruction::CastOps opcode = 
11001      (VTySize < PtrSize ? Instruction::SExt :
11002       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11003   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11004 }
11005
11006
11007 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11008   Value *PtrOp = GEP.getOperand(0);
11009   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11010   // If so, eliminate the noop.
11011   if (GEP.getNumOperands() == 1)
11012     return ReplaceInstUsesWith(GEP, PtrOp);
11013
11014   if (isa<UndefValue>(GEP.getOperand(0)))
11015     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11016
11017   bool HasZeroPointerIndex = false;
11018   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11019     HasZeroPointerIndex = C->isNullValue();
11020
11021   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11022     return ReplaceInstUsesWith(GEP, PtrOp);
11023
11024   // Eliminate unneeded casts for indices.
11025   bool MadeChange = false;
11026   
11027   gep_type_iterator GTI = gep_type_begin(GEP);
11028   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11029        i != e; ++i, ++GTI) {
11030     if (isa<SequentialType>(*GTI)) {
11031       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11032         if (CI->getOpcode() == Instruction::ZExt ||
11033             CI->getOpcode() == Instruction::SExt) {
11034           const Type *SrcTy = CI->getOperand(0)->getType();
11035           // We can eliminate a cast from i32 to i64 iff the target 
11036           // is a 32-bit pointer target.
11037           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11038             MadeChange = true;
11039             *i = CI->getOperand(0);
11040           }
11041         }
11042       }
11043       // If we are using a wider index than needed for this platform, shrink it
11044       // to what we need.  If narrower, sign-extend it to what we need.
11045       // If the incoming value needs a cast instruction,
11046       // insert it.  This explicit cast can make subsequent optimizations more
11047       // obvious.
11048       Value *Op = *i;
11049       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11050         if (Constant *C = dyn_cast<Constant>(Op)) {
11051           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11052           MadeChange = true;
11053         } else {
11054           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11055                                 GEP);
11056           *i = Op;
11057           MadeChange = true;
11058         }
11059       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11060         if (Constant *C = dyn_cast<Constant>(Op)) {
11061           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11062           MadeChange = true;
11063         } else {
11064           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11065                                 GEP);
11066           *i = Op;
11067           MadeChange = true;
11068         }
11069       }
11070     }
11071   }
11072   if (MadeChange) return &GEP;
11073
11074   // Combine Indices - If the source pointer to this getelementptr instruction
11075   // is a getelementptr instruction, combine the indices of the two
11076   // getelementptr instructions into a single instruction.
11077   //
11078   SmallVector<Value*, 8> SrcGEPOperands;
11079   if (User *Src = dyn_castGetElementPtr(PtrOp))
11080     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11081
11082   if (!SrcGEPOperands.empty()) {
11083     // Note that if our source is a gep chain itself that we wait for that
11084     // chain to be resolved before we perform this transformation.  This
11085     // avoids us creating a TON of code in some cases.
11086     //
11087     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11088         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11089       return 0;   // Wait until our source is folded to completion.
11090
11091     SmallVector<Value*, 8> Indices;
11092
11093     // Find out whether the last index in the source GEP is a sequential idx.
11094     bool EndsWithSequential = false;
11095     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11096            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11097       EndsWithSequential = !isa<StructType>(*I);
11098
11099     // Can we combine the two pointer arithmetics offsets?
11100     if (EndsWithSequential) {
11101       // Replace: gep (gep %P, long B), long A, ...
11102       // With:    T = long A+B; gep %P, T, ...
11103       //
11104       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11105       if (SO1 == Context->getNullValue(SO1->getType())) {
11106         Sum = GO1;
11107       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11108         Sum = SO1;
11109       } else {
11110         // If they aren't the same type, convert both to an integer of the
11111         // target's pointer size.
11112         if (SO1->getType() != GO1->getType()) {
11113           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11114             SO1 =
11115                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11116           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11117             GO1 =
11118                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11119           } else {
11120             unsigned PS = TD->getPointerSizeInBits();
11121             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11122               // Convert GO1 to SO1's type.
11123               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11124
11125             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11126               // Convert SO1 to GO1's type.
11127               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11128             } else {
11129               const Type *PT = TD->getIntPtrType();
11130               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11131               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11132             }
11133           }
11134         }
11135         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11136           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11137                                             cast<Constant>(GO1));
11138         else {
11139           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11140           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11141         }
11142       }
11143
11144       // Recycle the GEP we already have if possible.
11145       if (SrcGEPOperands.size() == 2) {
11146         GEP.setOperand(0, SrcGEPOperands[0]);
11147         GEP.setOperand(1, Sum);
11148         return &GEP;
11149       } else {
11150         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11151                        SrcGEPOperands.end()-1);
11152         Indices.push_back(Sum);
11153         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11154       }
11155     } else if (isa<Constant>(*GEP.idx_begin()) &&
11156                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11157                SrcGEPOperands.size() != 1) {
11158       // Otherwise we can do the fold if the first index of the GEP is a zero
11159       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11160                      SrcGEPOperands.end());
11161       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11162     }
11163
11164     if (!Indices.empty())
11165       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11166                                        Indices.end(), GEP.getName());
11167
11168   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11169     // GEP of global variable.  If all of the indices for this GEP are
11170     // constants, we can promote this to a constexpr instead of an instruction.
11171
11172     // Scan for nonconstants...
11173     SmallVector<Constant*, 8> Indices;
11174     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11175     for (; I != E && isa<Constant>(*I); ++I)
11176       Indices.push_back(cast<Constant>(*I));
11177
11178     if (I == E) {  // If they are all constants...
11179       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11180                                                     &Indices[0],Indices.size());
11181
11182       // Replace all uses of the GEP with the new constexpr...
11183       return ReplaceInstUsesWith(GEP, CE);
11184     }
11185   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11186     if (!isa<PointerType>(X->getType())) {
11187       // Not interesting.  Source pointer must be a cast from pointer.
11188     } else if (HasZeroPointerIndex) {
11189       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11190       // into     : GEP [10 x i8]* X, i32 0, ...
11191       //
11192       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11193       //           into     : GEP i8* X, ...
11194       // 
11195       // This occurs when the program declares an array extern like "int X[];"
11196       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11197       const PointerType *XTy = cast<PointerType>(X->getType());
11198       if (const ArrayType *CATy =
11199           dyn_cast<ArrayType>(CPTy->getElementType())) {
11200         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11201         if (CATy->getElementType() == XTy->getElementType()) {
11202           // -> GEP i8* X, ...
11203           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11204           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11205                                            GEP.getName());
11206         } else if (const ArrayType *XATy =
11207                  dyn_cast<ArrayType>(XTy->getElementType())) {
11208           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11209           if (CATy->getElementType() == XATy->getElementType()) {
11210             // -> GEP [10 x i8]* X, i32 0, ...
11211             // At this point, we know that the cast source type is a pointer
11212             // to an array of the same type as the destination pointer
11213             // array.  Because the array type is never stepped over (there
11214             // is a leading zero) we can fold the cast into this GEP.
11215             GEP.setOperand(0, X);
11216             return &GEP;
11217           }
11218         }
11219       }
11220     } else if (GEP.getNumOperands() == 2) {
11221       // Transform things like:
11222       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11223       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11224       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11225       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11226       if (isa<ArrayType>(SrcElTy) &&
11227           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11228           TD->getTypeAllocSize(ResElTy)) {
11229         Value *Idx[2];
11230         Idx[0] = Context->getNullValue(Type::Int32Ty);
11231         Idx[1] = GEP.getOperand(1);
11232         Value *V = InsertNewInstBefore(
11233                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11234         // V and GEP are both pointer types --> BitCast
11235         return new BitCastInst(V, GEP.getType());
11236       }
11237       
11238       // Transform things like:
11239       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11240       //   (where tmp = 8*tmp2) into:
11241       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11242       
11243       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11244         uint64_t ArrayEltSize =
11245             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11246         
11247         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11248         // allow either a mul, shift, or constant here.
11249         Value *NewIdx = 0;
11250         ConstantInt *Scale = 0;
11251         if (ArrayEltSize == 1) {
11252           NewIdx = GEP.getOperand(1);
11253           Scale = 
11254                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11255         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11256           NewIdx = Context->getConstantInt(CI->getType(), 1);
11257           Scale = CI;
11258         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11259           if (Inst->getOpcode() == Instruction::Shl &&
11260               isa<ConstantInt>(Inst->getOperand(1))) {
11261             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11262             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11263             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11264                                      1ULL << ShAmtVal);
11265             NewIdx = Inst->getOperand(0);
11266           } else if (Inst->getOpcode() == Instruction::Mul &&
11267                      isa<ConstantInt>(Inst->getOperand(1))) {
11268             Scale = cast<ConstantInt>(Inst->getOperand(1));
11269             NewIdx = Inst->getOperand(0);
11270           }
11271         }
11272         
11273         // If the index will be to exactly the right offset with the scale taken
11274         // out, perform the transformation. Note, we don't know whether Scale is
11275         // signed or not. We'll use unsigned version of division/modulo
11276         // operation after making sure Scale doesn't have the sign bit set.
11277         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11278             Scale->getZExtValue() % ArrayEltSize == 0) {
11279           Scale = Context->getConstantInt(Scale->getType(),
11280                                    Scale->getZExtValue() / ArrayEltSize);
11281           if (Scale->getZExtValue() != 1) {
11282             Constant *C =
11283                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11284                                                        false /*ZExt*/);
11285             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11286             NewIdx = InsertNewInstBefore(Sc, GEP);
11287           }
11288
11289           // Insert the new GEP instruction.
11290           Value *Idx[2];
11291           Idx[0] = Context->getNullValue(Type::Int32Ty);
11292           Idx[1] = NewIdx;
11293           Instruction *NewGEP =
11294             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11295           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11296           // The NewGEP must be pointer typed, so must the old one -> BitCast
11297           return new BitCastInst(NewGEP, GEP.getType());
11298         }
11299       }
11300     }
11301   }
11302   
11303   /// See if we can simplify:
11304   ///   X = bitcast A to B*
11305   ///   Y = gep X, <...constant indices...>
11306   /// into a gep of the original struct.  This is important for SROA and alias
11307   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11308   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11309     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11310       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11311       // a constant back from EmitGEPOffset.
11312       ConstantInt *OffsetV =
11313                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11314       int64_t Offset = OffsetV->getSExtValue();
11315       
11316       // If this GEP instruction doesn't move the pointer, just replace the GEP
11317       // with a bitcast of the real input to the dest type.
11318       if (Offset == 0) {
11319         // If the bitcast is of an allocation, and the allocation will be
11320         // converted to match the type of the cast, don't touch this.
11321         if (isa<AllocationInst>(BCI->getOperand(0))) {
11322           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11323           if (Instruction *I = visitBitCast(*BCI)) {
11324             if (I != BCI) {
11325               I->takeName(BCI);
11326               BCI->getParent()->getInstList().insert(BCI, I);
11327               ReplaceInstUsesWith(*BCI, I);
11328             }
11329             return &GEP;
11330           }
11331         }
11332         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11333       }
11334       
11335       // Otherwise, if the offset is non-zero, we need to find out if there is a
11336       // field at Offset in 'A's type.  If so, we can pull the cast through the
11337       // GEP.
11338       SmallVector<Value*, 8> NewIndices;
11339       const Type *InTy =
11340         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11341       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11342         Instruction *NGEP =
11343            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11344                                      NewIndices.end());
11345         if (NGEP->getType() == GEP.getType()) return NGEP;
11346         InsertNewInstBefore(NGEP, GEP);
11347         NGEP->takeName(&GEP);
11348         return new BitCastInst(NGEP, GEP.getType());
11349       }
11350     }
11351   }    
11352     
11353   return 0;
11354 }
11355
11356 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11357   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11358   if (AI.isArrayAllocation()) {  // Check C != 1
11359     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11360       const Type *NewTy = 
11361         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11362       AllocationInst *New = 0;
11363
11364       // Create and insert the replacement instruction...
11365       if (isa<MallocInst>(AI))
11366         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11367       else {
11368         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11369         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11370       }
11371
11372       InsertNewInstBefore(New, AI);
11373
11374       // Scan to the end of the allocation instructions, to skip over a block of
11375       // allocas if possible...also skip interleaved debug info
11376       //
11377       BasicBlock::iterator It = New;
11378       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11379
11380       // Now that I is pointing to the first non-allocation-inst in the block,
11381       // insert our getelementptr instruction...
11382       //
11383       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11384       Value *Idx[2];
11385       Idx[0] = NullIdx;
11386       Idx[1] = NullIdx;
11387       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11388                                            New->getName()+".sub", It);
11389
11390       // Now make everything use the getelementptr instead of the original
11391       // allocation.
11392       return ReplaceInstUsesWith(AI, V);
11393     } else if (isa<UndefValue>(AI.getArraySize())) {
11394       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11395     }
11396   }
11397
11398   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11399     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11400     // Note that we only do this for alloca's, because malloc should allocate
11401     // and return a unique pointer, even for a zero byte allocation.
11402     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11403       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11404
11405     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11406     if (AI.getAlignment() == 0)
11407       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11408   }
11409
11410   return 0;
11411 }
11412
11413 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11414   Value *Op = FI.getOperand(0);
11415
11416   // free undef -> unreachable.
11417   if (isa<UndefValue>(Op)) {
11418     // Insert a new store to null because we cannot modify the CFG here.
11419     new StoreInst(Context->getConstantIntTrue(),
11420            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11421     return EraseInstFromFunction(FI);
11422   }
11423   
11424   // If we have 'free null' delete the instruction.  This can happen in stl code
11425   // when lots of inlining happens.
11426   if (isa<ConstantPointerNull>(Op))
11427     return EraseInstFromFunction(FI);
11428   
11429   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11430   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11431     FI.setOperand(0, CI->getOperand(0));
11432     return &FI;
11433   }
11434   
11435   // Change free (gep X, 0,0,0,0) into free(X)
11436   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11437     if (GEPI->hasAllZeroIndices()) {
11438       AddToWorkList(GEPI);
11439       FI.setOperand(0, GEPI->getOperand(0));
11440       return &FI;
11441     }
11442   }
11443   
11444   // Change free(malloc) into nothing, if the malloc has a single use.
11445   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11446     if (MI->hasOneUse()) {
11447       EraseInstFromFunction(FI);
11448       return EraseInstFromFunction(*MI);
11449     }
11450
11451   return 0;
11452 }
11453
11454
11455 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11456 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11457                                         const TargetData *TD) {
11458   User *CI = cast<User>(LI.getOperand(0));
11459   Value *CastOp = CI->getOperand(0);
11460   LLVMContext *Context = IC.getContext();
11461
11462   if (TD) {
11463     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11464       // Instead of loading constant c string, use corresponding integer value
11465       // directly if string length is small enough.
11466       std::string Str;
11467       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11468         unsigned len = Str.length();
11469         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11470         unsigned numBits = Ty->getPrimitiveSizeInBits();
11471         // Replace LI with immediate integer store.
11472         if ((numBits >> 3) == len + 1) {
11473           APInt StrVal(numBits, 0);
11474           APInt SingleChar(numBits, 0);
11475           if (TD->isLittleEndian()) {
11476             for (signed i = len-1; i >= 0; i--) {
11477               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11478               StrVal = (StrVal << 8) | SingleChar;
11479             }
11480           } else {
11481             for (unsigned i = 0; i < len; i++) {
11482               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11483               StrVal = (StrVal << 8) | SingleChar;
11484             }
11485             // Append NULL at the end.
11486             SingleChar = 0;
11487             StrVal = (StrVal << 8) | SingleChar;
11488           }
11489           Value *NL = Context->getConstantInt(StrVal);
11490           return IC.ReplaceInstUsesWith(LI, NL);
11491         }
11492       }
11493     }
11494   }
11495
11496   const PointerType *DestTy = cast<PointerType>(CI->getType());
11497   const Type *DestPTy = DestTy->getElementType();
11498   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11499
11500     // If the address spaces don't match, don't eliminate the cast.
11501     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11502       return 0;
11503
11504     const Type *SrcPTy = SrcTy->getElementType();
11505
11506     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11507          isa<VectorType>(DestPTy)) {
11508       // If the source is an array, the code below will not succeed.  Check to
11509       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11510       // constants.
11511       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11512         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11513           if (ASrcTy->getNumElements() != 0) {
11514             Value *Idxs[2];
11515             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11516             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11517             SrcTy = cast<PointerType>(CastOp->getType());
11518             SrcPTy = SrcTy->getElementType();
11519           }
11520
11521       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11522             isa<VectorType>(SrcPTy)) &&
11523           // Do not allow turning this into a load of an integer, which is then
11524           // casted to a pointer, this pessimizes pointer analysis a lot.
11525           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11526           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11527                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11528
11529         // Okay, we are casting from one integer or pointer type to another of
11530         // the same size.  Instead of casting the pointer before the load, cast
11531         // the result of the loaded value.
11532         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11533                                                              CI->getName(),
11534                                                          LI.isVolatile()),LI);
11535         // Now cast the result of the load.
11536         return new BitCastInst(NewLoad, LI.getType());
11537       }
11538     }
11539   }
11540   return 0;
11541 }
11542
11543 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11544   Value *Op = LI.getOperand(0);
11545
11546   // Attempt to improve the alignment.
11547   unsigned KnownAlign =
11548     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11549   if (KnownAlign >
11550       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11551                                 LI.getAlignment()))
11552     LI.setAlignment(KnownAlign);
11553
11554   // load (cast X) --> cast (load X) iff safe
11555   if (isa<CastInst>(Op))
11556     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11557       return Res;
11558
11559   // None of the following transforms are legal for volatile loads.
11560   if (LI.isVolatile()) return 0;
11561   
11562   // Do really simple store-to-load forwarding and load CSE, to catch cases
11563   // where there are several consequtive memory accesses to the same location,
11564   // separated by a few arithmetic operations.
11565   BasicBlock::iterator BBI = &LI;
11566   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11567     return ReplaceInstUsesWith(LI, AvailableVal);
11568
11569   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11570     const Value *GEPI0 = GEPI->getOperand(0);
11571     // TODO: Consider a target hook for valid address spaces for this xform.
11572     if (isa<ConstantPointerNull>(GEPI0) &&
11573         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11574       // Insert a new store to null instruction before the load to indicate
11575       // that this code is not reachable.  We do this instead of inserting
11576       // an unreachable instruction directly because we cannot modify the
11577       // CFG.
11578       new StoreInst(Context->getUndef(LI.getType()),
11579                     Context->getNullValue(Op->getType()), &LI);
11580       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11581     }
11582   } 
11583
11584   if (Constant *C = dyn_cast<Constant>(Op)) {
11585     // load null/undef -> undef
11586     // TODO: Consider a target hook for valid address spaces for this xform.
11587     if (isa<UndefValue>(C) || (C->isNullValue() && 
11588         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11589       // Insert a new store to null instruction before the load to indicate that
11590       // this code is not reachable.  We do this instead of inserting an
11591       // unreachable instruction directly because we cannot modify the CFG.
11592       new StoreInst(Context->getUndef(LI.getType()),
11593                     Context->getNullValue(Op->getType()), &LI);
11594       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11595     }
11596
11597     // Instcombine load (constant global) into the value loaded.
11598     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11599       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11600         return ReplaceInstUsesWith(LI, GV->getInitializer());
11601
11602     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11603     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11604       if (CE->getOpcode() == Instruction::GetElementPtr) {
11605         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11606           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11607             if (Constant *V = 
11608                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11609                                                       Context))
11610               return ReplaceInstUsesWith(LI, V);
11611         if (CE->getOperand(0)->isNullValue()) {
11612           // Insert a new store to null instruction before the load to indicate
11613           // that this code is not reachable.  We do this instead of inserting
11614           // an unreachable instruction directly because we cannot modify the
11615           // CFG.
11616           new StoreInst(Context->getUndef(LI.getType()),
11617                         Context->getNullValue(Op->getType()), &LI);
11618           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11619         }
11620
11621       } else if (CE->isCast()) {
11622         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11623           return Res;
11624       }
11625     }
11626   }
11627     
11628   // If this load comes from anywhere in a constant global, and if the global
11629   // is all undef or zero, we know what it loads.
11630   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11631     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11632       if (GV->getInitializer()->isNullValue())
11633         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11634       else if (isa<UndefValue>(GV->getInitializer()))
11635         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11636     }
11637   }
11638
11639   if (Op->hasOneUse()) {
11640     // Change select and PHI nodes to select values instead of addresses: this
11641     // helps alias analysis out a lot, allows many others simplifications, and
11642     // exposes redundancy in the code.
11643     //
11644     // Note that we cannot do the transformation unless we know that the
11645     // introduced loads cannot trap!  Something like this is valid as long as
11646     // the condition is always false: load (select bool %C, int* null, int* %G),
11647     // but it would not be valid if we transformed it to load from null
11648     // unconditionally.
11649     //
11650     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11651       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11652       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11653           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11654         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11655                                      SI->getOperand(1)->getName()+".val"), LI);
11656         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11657                                      SI->getOperand(2)->getName()+".val"), LI);
11658         return SelectInst::Create(SI->getCondition(), V1, V2);
11659       }
11660
11661       // load (select (cond, null, P)) -> load P
11662       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11663         if (C->isNullValue()) {
11664           LI.setOperand(0, SI->getOperand(2));
11665           return &LI;
11666         }
11667
11668       // load (select (cond, P, null)) -> load P
11669       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11670         if (C->isNullValue()) {
11671           LI.setOperand(0, SI->getOperand(1));
11672           return &LI;
11673         }
11674     }
11675   }
11676   return 0;
11677 }
11678
11679 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11680 /// when possible.  This makes it generally easy to do alias analysis and/or
11681 /// SROA/mem2reg of the memory object.
11682 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11683   User *CI = cast<User>(SI.getOperand(1));
11684   Value *CastOp = CI->getOperand(0);
11685   LLVMContext *Context = IC.getContext();
11686
11687   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11688   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11689   if (SrcTy == 0) return 0;
11690   
11691   const Type *SrcPTy = SrcTy->getElementType();
11692
11693   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11694     return 0;
11695   
11696   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11697   /// to its first element.  This allows us to handle things like:
11698   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11699   /// on 32-bit hosts.
11700   SmallVector<Value*, 4> NewGEPIndices;
11701   
11702   // If the source is an array, the code below will not succeed.  Check to
11703   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11704   // constants.
11705   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11706     // Index through pointer.
11707     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11708     NewGEPIndices.push_back(Zero);
11709     
11710     while (1) {
11711       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11712         if (!STy->getNumElements()) /* Struct can be empty {} */
11713           break;
11714         NewGEPIndices.push_back(Zero);
11715         SrcPTy = STy->getElementType(0);
11716       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11717         NewGEPIndices.push_back(Zero);
11718         SrcPTy = ATy->getElementType();
11719       } else {
11720         break;
11721       }
11722     }
11723     
11724     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11725   }
11726
11727   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11728     return 0;
11729   
11730   // If the pointers point into different address spaces or if they point to
11731   // values with different sizes, we can't do the transformation.
11732   if (SrcTy->getAddressSpace() != 
11733         cast<PointerType>(CI->getType())->getAddressSpace() ||
11734       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11735       IC.getTargetData().getTypeSizeInBits(DestPTy))
11736     return 0;
11737
11738   // Okay, we are casting from one integer or pointer type to another of
11739   // the same size.  Instead of casting the pointer before 
11740   // the store, cast the value to be stored.
11741   Value *NewCast;
11742   Value *SIOp0 = SI.getOperand(0);
11743   Instruction::CastOps opcode = Instruction::BitCast;
11744   const Type* CastSrcTy = SIOp0->getType();
11745   const Type* CastDstTy = SrcPTy;
11746   if (isa<PointerType>(CastDstTy)) {
11747     if (CastSrcTy->isInteger())
11748       opcode = Instruction::IntToPtr;
11749   } else if (isa<IntegerType>(CastDstTy)) {
11750     if (isa<PointerType>(SIOp0->getType()))
11751       opcode = Instruction::PtrToInt;
11752   }
11753   
11754   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11755   // emit a GEP to index into its first field.
11756   if (!NewGEPIndices.empty()) {
11757     if (Constant *C = dyn_cast<Constant>(CastOp))
11758       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11759                                               NewGEPIndices.size());
11760     else
11761       CastOp = IC.InsertNewInstBefore(
11762               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11763                                         NewGEPIndices.end()), SI);
11764   }
11765   
11766   if (Constant *C = dyn_cast<Constant>(SIOp0))
11767     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11768   else
11769     NewCast = IC.InsertNewInstBefore(
11770       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11771       SI);
11772   return new StoreInst(NewCast, CastOp);
11773 }
11774
11775 /// equivalentAddressValues - Test if A and B will obviously have the same
11776 /// value. This includes recognizing that %t0 and %t1 will have the same
11777 /// value in code like this:
11778 ///   %t0 = getelementptr \@a, 0, 3
11779 ///   store i32 0, i32* %t0
11780 ///   %t1 = getelementptr \@a, 0, 3
11781 ///   %t2 = load i32* %t1
11782 ///
11783 static bool equivalentAddressValues(Value *A, Value *B) {
11784   // Test if the values are trivially equivalent.
11785   if (A == B) return true;
11786   
11787   // Test if the values come form identical arithmetic instructions.
11788   if (isa<BinaryOperator>(A) ||
11789       isa<CastInst>(A) ||
11790       isa<PHINode>(A) ||
11791       isa<GetElementPtrInst>(A))
11792     if (Instruction *BI = dyn_cast<Instruction>(B))
11793       if (cast<Instruction>(A)->isIdenticalTo(BI))
11794         return true;
11795   
11796   // Otherwise they may not be equivalent.
11797   return false;
11798 }
11799
11800 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11801 // return the llvm.dbg.declare.
11802 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11803   if (!V->hasNUses(2))
11804     return 0;
11805   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11806        UI != E; ++UI) {
11807     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11808       return DI;
11809     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11810       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11811         return DI;
11812       }
11813   }
11814   return 0;
11815 }
11816
11817 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11818   Value *Val = SI.getOperand(0);
11819   Value *Ptr = SI.getOperand(1);
11820
11821   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11822     EraseInstFromFunction(SI);
11823     ++NumCombined;
11824     return 0;
11825   }
11826   
11827   // If the RHS is an alloca with a single use, zapify the store, making the
11828   // alloca dead.
11829   // If the RHS is an alloca with a two uses, the other one being a 
11830   // llvm.dbg.declare, zapify the store and the declare, making the
11831   // alloca dead.  We must do this to prevent declare's from affecting
11832   // codegen.
11833   if (!SI.isVolatile()) {
11834     if (Ptr->hasOneUse()) {
11835       if (isa<AllocaInst>(Ptr)) {
11836         EraseInstFromFunction(SI);
11837         ++NumCombined;
11838         return 0;
11839       }
11840       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11841         if (isa<AllocaInst>(GEP->getOperand(0))) {
11842           if (GEP->getOperand(0)->hasOneUse()) {
11843             EraseInstFromFunction(SI);
11844             ++NumCombined;
11845             return 0;
11846           }
11847           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11848             EraseInstFromFunction(*DI);
11849             EraseInstFromFunction(SI);
11850             ++NumCombined;
11851             return 0;
11852           }
11853         }
11854       }
11855     }
11856     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11857       EraseInstFromFunction(*DI);
11858       EraseInstFromFunction(SI);
11859       ++NumCombined;
11860       return 0;
11861     }
11862   }
11863
11864   // Attempt to improve the alignment.
11865   unsigned KnownAlign =
11866     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11867   if (KnownAlign >
11868       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11869                                 SI.getAlignment()))
11870     SI.setAlignment(KnownAlign);
11871
11872   // Do really simple DSE, to catch cases where there are several consecutive
11873   // stores to the same location, separated by a few arithmetic operations. This
11874   // situation often occurs with bitfield accesses.
11875   BasicBlock::iterator BBI = &SI;
11876   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11877        --ScanInsts) {
11878     --BBI;
11879     // Don't count debug info directives, lest they affect codegen,
11880     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11881     // It is necessary for correctness to skip those that feed into a
11882     // llvm.dbg.declare, as these are not present when debugging is off.
11883     if (isa<DbgInfoIntrinsic>(BBI) ||
11884         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11885       ScanInsts++;
11886       continue;
11887     }    
11888     
11889     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11890       // Prev store isn't volatile, and stores to the same location?
11891       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11892                                                           SI.getOperand(1))) {
11893         ++NumDeadStore;
11894         ++BBI;
11895         EraseInstFromFunction(*PrevSI);
11896         continue;
11897       }
11898       break;
11899     }
11900     
11901     // If this is a load, we have to stop.  However, if the loaded value is from
11902     // the pointer we're loading and is producing the pointer we're storing,
11903     // then *this* store is dead (X = load P; store X -> P).
11904     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11905       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11906           !SI.isVolatile()) {
11907         EraseInstFromFunction(SI);
11908         ++NumCombined;
11909         return 0;
11910       }
11911       // Otherwise, this is a load from some other location.  Stores before it
11912       // may not be dead.
11913       break;
11914     }
11915     
11916     // Don't skip over loads or things that can modify memory.
11917     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11918       break;
11919   }
11920   
11921   
11922   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11923
11924   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11925   if (isa<ConstantPointerNull>(Ptr) &&
11926       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11927     if (!isa<UndefValue>(Val)) {
11928       SI.setOperand(0, Context->getUndef(Val->getType()));
11929       if (Instruction *U = dyn_cast<Instruction>(Val))
11930         AddToWorkList(U);  // Dropped a use.
11931       ++NumCombined;
11932     }
11933     return 0;  // Do not modify these!
11934   }
11935
11936   // store undef, Ptr -> noop
11937   if (isa<UndefValue>(Val)) {
11938     EraseInstFromFunction(SI);
11939     ++NumCombined;
11940     return 0;
11941   }
11942
11943   // If the pointer destination is a cast, see if we can fold the cast into the
11944   // source instead.
11945   if (isa<CastInst>(Ptr))
11946     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11947       return Res;
11948   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11949     if (CE->isCast())
11950       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11951         return Res;
11952
11953   
11954   // If this store is the last instruction in the basic block (possibly
11955   // excepting debug info instructions and the pointer bitcasts that feed
11956   // into them), and if the block ends with an unconditional branch, try
11957   // to move it to the successor block.
11958   BBI = &SI; 
11959   do {
11960     ++BBI;
11961   } while (isa<DbgInfoIntrinsic>(BBI) ||
11962            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11963   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11964     if (BI->isUnconditional())
11965       if (SimplifyStoreAtEndOfBlock(SI))
11966         return 0;  // xform done!
11967   
11968   return 0;
11969 }
11970
11971 /// SimplifyStoreAtEndOfBlock - Turn things like:
11972 ///   if () { *P = v1; } else { *P = v2 }
11973 /// into a phi node with a store in the successor.
11974 ///
11975 /// Simplify things like:
11976 ///   *P = v1; if () { *P = v2; }
11977 /// into a phi node with a store in the successor.
11978 ///
11979 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11980   BasicBlock *StoreBB = SI.getParent();
11981   
11982   // Check to see if the successor block has exactly two incoming edges.  If
11983   // so, see if the other predecessor contains a store to the same location.
11984   // if so, insert a PHI node (if needed) and move the stores down.
11985   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11986   
11987   // Determine whether Dest has exactly two predecessors and, if so, compute
11988   // the other predecessor.
11989   pred_iterator PI = pred_begin(DestBB);
11990   BasicBlock *OtherBB = 0;
11991   if (*PI != StoreBB)
11992     OtherBB = *PI;
11993   ++PI;
11994   if (PI == pred_end(DestBB))
11995     return false;
11996   
11997   if (*PI != StoreBB) {
11998     if (OtherBB)
11999       return false;
12000     OtherBB = *PI;
12001   }
12002   if (++PI != pred_end(DestBB))
12003     return false;
12004
12005   // Bail out if all the relevant blocks aren't distinct (this can happen,
12006   // for example, if SI is in an infinite loop)
12007   if (StoreBB == DestBB || OtherBB == DestBB)
12008     return false;
12009
12010   // Verify that the other block ends in a branch and is not otherwise empty.
12011   BasicBlock::iterator BBI = OtherBB->getTerminator();
12012   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12013   if (!OtherBr || BBI == OtherBB->begin())
12014     return false;
12015   
12016   // If the other block ends in an unconditional branch, check for the 'if then
12017   // else' case.  there is an instruction before the branch.
12018   StoreInst *OtherStore = 0;
12019   if (OtherBr->isUnconditional()) {
12020     --BBI;
12021     // Skip over debugging info.
12022     while (isa<DbgInfoIntrinsic>(BBI) ||
12023            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12024       if (BBI==OtherBB->begin())
12025         return false;
12026       --BBI;
12027     }
12028     // If this isn't a store, or isn't a store to the same location, bail out.
12029     OtherStore = dyn_cast<StoreInst>(BBI);
12030     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12031       return false;
12032   } else {
12033     // Otherwise, the other block ended with a conditional branch. If one of the
12034     // destinations is StoreBB, then we have the if/then case.
12035     if (OtherBr->getSuccessor(0) != StoreBB && 
12036         OtherBr->getSuccessor(1) != StoreBB)
12037       return false;
12038     
12039     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12040     // if/then triangle.  See if there is a store to the same ptr as SI that
12041     // lives in OtherBB.
12042     for (;; --BBI) {
12043       // Check to see if we find the matching store.
12044       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12045         if (OtherStore->getOperand(1) != SI.getOperand(1))
12046           return false;
12047         break;
12048       }
12049       // If we find something that may be using or overwriting the stored
12050       // value, or if we run out of instructions, we can't do the xform.
12051       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12052           BBI == OtherBB->begin())
12053         return false;
12054     }
12055     
12056     // In order to eliminate the store in OtherBr, we have to
12057     // make sure nothing reads or overwrites the stored value in
12058     // StoreBB.
12059     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12060       // FIXME: This should really be AA driven.
12061       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12062         return false;
12063     }
12064   }
12065   
12066   // Insert a PHI node now if we need it.
12067   Value *MergedVal = OtherStore->getOperand(0);
12068   if (MergedVal != SI.getOperand(0)) {
12069     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12070     PN->reserveOperandSpace(2);
12071     PN->addIncoming(SI.getOperand(0), SI.getParent());
12072     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12073     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12074   }
12075   
12076   // Advance to a place where it is safe to insert the new store and
12077   // insert it.
12078   BBI = DestBB->getFirstNonPHI();
12079   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12080                                     OtherStore->isVolatile()), *BBI);
12081   
12082   // Nuke the old stores.
12083   EraseInstFromFunction(SI);
12084   EraseInstFromFunction(*OtherStore);
12085   ++NumCombined;
12086   return true;
12087 }
12088
12089
12090 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12091   // Change br (not X), label True, label False to: br X, label False, True
12092   Value *X = 0;
12093   BasicBlock *TrueDest;
12094   BasicBlock *FalseDest;
12095   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12096       !isa<Constant>(X)) {
12097     // Swap Destinations and condition...
12098     BI.setCondition(X);
12099     BI.setSuccessor(0, FalseDest);
12100     BI.setSuccessor(1, TrueDest);
12101     return &BI;
12102   }
12103
12104   // Cannonicalize fcmp_one -> fcmp_oeq
12105   FCmpInst::Predicate FPred; Value *Y;
12106   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12107                              TrueDest, FalseDest), *Context))
12108     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12109          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12110       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12111       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12112       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12113       NewSCC->takeName(I);
12114       // Swap Destinations and condition...
12115       BI.setCondition(NewSCC);
12116       BI.setSuccessor(0, FalseDest);
12117       BI.setSuccessor(1, TrueDest);
12118       RemoveFromWorkList(I);
12119       I->eraseFromParent();
12120       AddToWorkList(NewSCC);
12121       return &BI;
12122     }
12123
12124   // Cannonicalize icmp_ne -> icmp_eq
12125   ICmpInst::Predicate IPred;
12126   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12127                       TrueDest, FalseDest), *Context))
12128     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12129          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12130          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12131       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12132       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12133       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12134       NewSCC->takeName(I);
12135       // Swap Destinations and condition...
12136       BI.setCondition(NewSCC);
12137       BI.setSuccessor(0, FalseDest);
12138       BI.setSuccessor(1, TrueDest);
12139       RemoveFromWorkList(I);
12140       I->eraseFromParent();;
12141       AddToWorkList(NewSCC);
12142       return &BI;
12143     }
12144
12145   return 0;
12146 }
12147
12148 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12149   Value *Cond = SI.getCondition();
12150   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12151     if (I->getOpcode() == Instruction::Add)
12152       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12153         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12154         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12155           SI.setOperand(i,
12156                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12157                                                 AddRHS));
12158         SI.setOperand(0, I->getOperand(0));
12159         AddToWorkList(I);
12160         return &SI;
12161       }
12162   }
12163   return 0;
12164 }
12165
12166 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12167   Value *Agg = EV.getAggregateOperand();
12168
12169   if (!EV.hasIndices())
12170     return ReplaceInstUsesWith(EV, Agg);
12171
12172   if (Constant *C = dyn_cast<Constant>(Agg)) {
12173     if (isa<UndefValue>(C))
12174       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12175       
12176     if (isa<ConstantAggregateZero>(C))
12177       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12178
12179     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12180       // Extract the element indexed by the first index out of the constant
12181       Value *V = C->getOperand(*EV.idx_begin());
12182       if (EV.getNumIndices() > 1)
12183         // Extract the remaining indices out of the constant indexed by the
12184         // first index
12185         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12186       else
12187         return ReplaceInstUsesWith(EV, V);
12188     }
12189     return 0; // Can't handle other constants
12190   } 
12191   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12192     // We're extracting from an insertvalue instruction, compare the indices
12193     const unsigned *exti, *exte, *insi, *inse;
12194     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12195          exte = EV.idx_end(), inse = IV->idx_end();
12196          exti != exte && insi != inse;
12197          ++exti, ++insi) {
12198       if (*insi != *exti)
12199         // The insert and extract both reference distinctly different elements.
12200         // This means the extract is not influenced by the insert, and we can
12201         // replace the aggregate operand of the extract with the aggregate
12202         // operand of the insert. i.e., replace
12203         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12204         // %E = extractvalue { i32, { i32 } } %I, 0
12205         // with
12206         // %E = extractvalue { i32, { i32 } } %A, 0
12207         return ExtractValueInst::Create(IV->getAggregateOperand(),
12208                                         EV.idx_begin(), EV.idx_end());
12209     }
12210     if (exti == exte && insi == inse)
12211       // Both iterators are at the end: Index lists are identical. Replace
12212       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12213       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12214       // with "i32 42"
12215       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12216     if (exti == exte) {
12217       // The extract list is a prefix of the insert list. i.e. replace
12218       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12219       // %E = extractvalue { i32, { i32 } } %I, 1
12220       // with
12221       // %X = extractvalue { i32, { i32 } } %A, 1
12222       // %E = insertvalue { i32 } %X, i32 42, 0
12223       // by switching the order of the insert and extract (though the
12224       // insertvalue should be left in, since it may have other uses).
12225       Value *NewEV = InsertNewInstBefore(
12226         ExtractValueInst::Create(IV->getAggregateOperand(),
12227                                  EV.idx_begin(), EV.idx_end()),
12228         EV);
12229       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12230                                      insi, inse);
12231     }
12232     if (insi == inse)
12233       // The insert list is a prefix of the extract list
12234       // We can simply remove the common indices from the extract and make it
12235       // operate on the inserted value instead of the insertvalue result.
12236       // i.e., replace
12237       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12238       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12239       // with
12240       // %E extractvalue { i32 } { i32 42 }, 0
12241       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12242                                       exti, exte);
12243   }
12244   // Can't simplify extracts from other values. Note that nested extracts are
12245   // already simplified implicitely by the above (extract ( extract (insert) )
12246   // will be translated into extract ( insert ( extract ) ) first and then just
12247   // the value inserted, if appropriate).
12248   return 0;
12249 }
12250
12251 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12252 /// is to leave as a vector operation.
12253 static bool CheapToScalarize(Value *V, bool isConstant) {
12254   if (isa<ConstantAggregateZero>(V)) 
12255     return true;
12256   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12257     if (isConstant) return true;
12258     // If all elts are the same, we can extract.
12259     Constant *Op0 = C->getOperand(0);
12260     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12261       if (C->getOperand(i) != Op0)
12262         return false;
12263     return true;
12264   }
12265   Instruction *I = dyn_cast<Instruction>(V);
12266   if (!I) return false;
12267   
12268   // Insert element gets simplified to the inserted element or is deleted if
12269   // this is constant idx extract element and its a constant idx insertelt.
12270   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12271       isa<ConstantInt>(I->getOperand(2)))
12272     return true;
12273   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12274     return true;
12275   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12276     if (BO->hasOneUse() &&
12277         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12278          CheapToScalarize(BO->getOperand(1), isConstant)))
12279       return true;
12280   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12281     if (CI->hasOneUse() &&
12282         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12283          CheapToScalarize(CI->getOperand(1), isConstant)))
12284       return true;
12285   
12286   return false;
12287 }
12288
12289 /// Read and decode a shufflevector mask.
12290 ///
12291 /// It turns undef elements into values that are larger than the number of
12292 /// elements in the input.
12293 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12294   unsigned NElts = SVI->getType()->getNumElements();
12295   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12296     return std::vector<unsigned>(NElts, 0);
12297   if (isa<UndefValue>(SVI->getOperand(2)))
12298     return std::vector<unsigned>(NElts, 2*NElts);
12299
12300   std::vector<unsigned> Result;
12301   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12302   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12303     if (isa<UndefValue>(*i))
12304       Result.push_back(NElts*2);  // undef -> 8
12305     else
12306       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12307   return Result;
12308 }
12309
12310 /// FindScalarElement - Given a vector and an element number, see if the scalar
12311 /// value is already around as a register, for example if it were inserted then
12312 /// extracted from the vector.
12313 static Value *FindScalarElement(Value *V, unsigned EltNo,
12314                                 LLVMContext *Context) {
12315   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12316   const VectorType *PTy = cast<VectorType>(V->getType());
12317   unsigned Width = PTy->getNumElements();
12318   if (EltNo >= Width)  // Out of range access.
12319     return Context->getUndef(PTy->getElementType());
12320   
12321   if (isa<UndefValue>(V))
12322     return Context->getUndef(PTy->getElementType());
12323   else if (isa<ConstantAggregateZero>(V))
12324     return Context->getNullValue(PTy->getElementType());
12325   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12326     return CP->getOperand(EltNo);
12327   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12328     // If this is an insert to a variable element, we don't know what it is.
12329     if (!isa<ConstantInt>(III->getOperand(2))) 
12330       return 0;
12331     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12332     
12333     // If this is an insert to the element we are looking for, return the
12334     // inserted value.
12335     if (EltNo == IIElt) 
12336       return III->getOperand(1);
12337     
12338     // Otherwise, the insertelement doesn't modify the value, recurse on its
12339     // vector input.
12340     return FindScalarElement(III->getOperand(0), EltNo, Context);
12341   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12342     unsigned LHSWidth =
12343       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12344     unsigned InEl = getShuffleMask(SVI)[EltNo];
12345     if (InEl < LHSWidth)
12346       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12347     else if (InEl < LHSWidth*2)
12348       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12349     else
12350       return Context->getUndef(PTy->getElementType());
12351   }
12352   
12353   // Otherwise, we don't know.
12354   return 0;
12355 }
12356
12357 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12358   // If vector val is undef, replace extract with scalar undef.
12359   if (isa<UndefValue>(EI.getOperand(0)))
12360     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12361
12362   // If vector val is constant 0, replace extract with scalar 0.
12363   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12364     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12365   
12366   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12367     // If vector val is constant with all elements the same, replace EI with
12368     // that element. When the elements are not identical, we cannot replace yet
12369     // (we do that below, but only when the index is constant).
12370     Constant *op0 = C->getOperand(0);
12371     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12372       if (C->getOperand(i) != op0) {
12373         op0 = 0; 
12374         break;
12375       }
12376     if (op0)
12377       return ReplaceInstUsesWith(EI, op0);
12378   }
12379   
12380   // If extracting a specified index from the vector, see if we can recursively
12381   // find a previously computed scalar that was inserted into the vector.
12382   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12383     unsigned IndexVal = IdxC->getZExtValue();
12384     unsigned VectorWidth = 
12385       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12386       
12387     // If this is extracting an invalid index, turn this into undef, to avoid
12388     // crashing the code below.
12389     if (IndexVal >= VectorWidth)
12390       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12391     
12392     // This instruction only demands the single element from the input vector.
12393     // If the input vector has a single use, simplify it based on this use
12394     // property.
12395     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12396       APInt UndefElts(VectorWidth, 0);
12397       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12398       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12399                                                 DemandedMask, UndefElts)) {
12400         EI.setOperand(0, V);
12401         return &EI;
12402       }
12403     }
12404     
12405     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12406       return ReplaceInstUsesWith(EI, Elt);
12407     
12408     // If the this extractelement is directly using a bitcast from a vector of
12409     // the same number of elements, see if we can find the source element from
12410     // it.  In this case, we will end up needing to bitcast the scalars.
12411     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12412       if (const VectorType *VT = 
12413               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12414         if (VT->getNumElements() == VectorWidth)
12415           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12416                                              IndexVal, Context))
12417             return new BitCastInst(Elt, EI.getType());
12418     }
12419   }
12420   
12421   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12422     if (I->hasOneUse()) {
12423       // Push extractelement into predecessor operation if legal and
12424       // profitable to do so
12425       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12426         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12427         if (CheapToScalarize(BO, isConstantElt)) {
12428           ExtractElementInst *newEI0 = 
12429             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12430                                    EI.getName()+".lhs");
12431           ExtractElementInst *newEI1 =
12432             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12433                                    EI.getName()+".rhs");
12434           InsertNewInstBefore(newEI0, EI);
12435           InsertNewInstBefore(newEI1, EI);
12436           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12437         }
12438       } else if (isa<LoadInst>(I)) {
12439         unsigned AS = 
12440           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12441         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12442                                   Context->getPointerType(EI.getType(), AS),EI);
12443         GetElementPtrInst *GEP =
12444           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12445         InsertNewInstBefore(GEP, EI);
12446         return new LoadInst(GEP);
12447       }
12448     }
12449     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12450       // Extracting the inserted element?
12451       if (IE->getOperand(2) == EI.getOperand(1))
12452         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12453       // If the inserted and extracted elements are constants, they must not
12454       // be the same value, extract from the pre-inserted value instead.
12455       if (isa<Constant>(IE->getOperand(2)) &&
12456           isa<Constant>(EI.getOperand(1))) {
12457         AddUsesToWorkList(EI);
12458         EI.setOperand(0, IE->getOperand(0));
12459         return &EI;
12460       }
12461     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12462       // If this is extracting an element from a shufflevector, figure out where
12463       // it came from and extract from the appropriate input element instead.
12464       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12465         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12466         Value *Src;
12467         unsigned LHSWidth =
12468           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12469
12470         if (SrcIdx < LHSWidth)
12471           Src = SVI->getOperand(0);
12472         else if (SrcIdx < LHSWidth*2) {
12473           SrcIdx -= LHSWidth;
12474           Src = SVI->getOperand(1);
12475         } else {
12476           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12477         }
12478         return new ExtractElementInst(Src, SrcIdx);
12479       }
12480     }
12481   }
12482   return 0;
12483 }
12484
12485 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12486 /// elements from either LHS or RHS, return the shuffle mask and true. 
12487 /// Otherwise, return false.
12488 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12489                                          std::vector<Constant*> &Mask,
12490                                          LLVMContext *Context) {
12491   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12492          "Invalid CollectSingleShuffleElements");
12493   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12494
12495   if (isa<UndefValue>(V)) {
12496     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12497     return true;
12498   } else if (V == LHS) {
12499     for (unsigned i = 0; i != NumElts; ++i)
12500       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12501     return true;
12502   } else if (V == RHS) {
12503     for (unsigned i = 0; i != NumElts; ++i)
12504       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12505     return true;
12506   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12507     // If this is an insert of an extract from some other vector, include it.
12508     Value *VecOp    = IEI->getOperand(0);
12509     Value *ScalarOp = IEI->getOperand(1);
12510     Value *IdxOp    = IEI->getOperand(2);
12511     
12512     if (!isa<ConstantInt>(IdxOp))
12513       return false;
12514     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12515     
12516     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12517       // Okay, we can handle this if the vector we are insertinting into is
12518       // transitively ok.
12519       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12520         // If so, update the mask to reflect the inserted undef.
12521         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12522         return true;
12523       }      
12524     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12525       if (isa<ConstantInt>(EI->getOperand(1)) &&
12526           EI->getOperand(0)->getType() == V->getType()) {
12527         unsigned ExtractedIdx =
12528           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12529         
12530         // This must be extracting from either LHS or RHS.
12531         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12532           // Okay, we can handle this if the vector we are insertinting into is
12533           // transitively ok.
12534           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12535             // If so, update the mask to reflect the inserted value.
12536             if (EI->getOperand(0) == LHS) {
12537               Mask[InsertedIdx % NumElts] = 
12538                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12539             } else {
12540               assert(EI->getOperand(0) == RHS);
12541               Mask[InsertedIdx % NumElts] = 
12542                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12543               
12544             }
12545             return true;
12546           }
12547         }
12548       }
12549     }
12550   }
12551   // TODO: Handle shufflevector here!
12552   
12553   return false;
12554 }
12555
12556 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12557 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12558 /// that computes V and the LHS value of the shuffle.
12559 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12560                                      Value *&RHS, LLVMContext *Context) {
12561   assert(isa<VectorType>(V->getType()) && 
12562          (RHS == 0 || V->getType() == RHS->getType()) &&
12563          "Invalid shuffle!");
12564   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12565
12566   if (isa<UndefValue>(V)) {
12567     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12568     return V;
12569   } else if (isa<ConstantAggregateZero>(V)) {
12570     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12571     return V;
12572   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12573     // If this is an insert of an extract from some other vector, include it.
12574     Value *VecOp    = IEI->getOperand(0);
12575     Value *ScalarOp = IEI->getOperand(1);
12576     Value *IdxOp    = IEI->getOperand(2);
12577     
12578     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12579       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12580           EI->getOperand(0)->getType() == V->getType()) {
12581         unsigned ExtractedIdx =
12582           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12583         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12584         
12585         // Either the extracted from or inserted into vector must be RHSVec,
12586         // otherwise we'd end up with a shuffle of three inputs.
12587         if (EI->getOperand(0) == RHS || RHS == 0) {
12588           RHS = EI->getOperand(0);
12589           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12590           Mask[InsertedIdx % NumElts] = 
12591             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12592           return V;
12593         }
12594         
12595         if (VecOp == RHS) {
12596           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12597                                             RHS, Context);
12598           // Everything but the extracted element is replaced with the RHS.
12599           for (unsigned i = 0; i != NumElts; ++i) {
12600             if (i != InsertedIdx)
12601               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12602           }
12603           return V;
12604         }
12605         
12606         // If this insertelement is a chain that comes from exactly these two
12607         // vectors, return the vector and the effective shuffle.
12608         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12609                                          Context))
12610           return EI->getOperand(0);
12611         
12612       }
12613     }
12614   }
12615   // TODO: Handle shufflevector here!
12616   
12617   // Otherwise, can't do anything fancy.  Return an identity vector.
12618   for (unsigned i = 0; i != NumElts; ++i)
12619     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12620   return V;
12621 }
12622
12623 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12624   Value *VecOp    = IE.getOperand(0);
12625   Value *ScalarOp = IE.getOperand(1);
12626   Value *IdxOp    = IE.getOperand(2);
12627   
12628   // Inserting an undef or into an undefined place, remove this.
12629   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12630     ReplaceInstUsesWith(IE, VecOp);
12631   
12632   // If the inserted element was extracted from some other vector, and if the 
12633   // indexes are constant, try to turn this into a shufflevector operation.
12634   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12635     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12636         EI->getOperand(0)->getType() == IE.getType()) {
12637       unsigned NumVectorElts = IE.getType()->getNumElements();
12638       unsigned ExtractedIdx =
12639         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12640       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12641       
12642       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12643         return ReplaceInstUsesWith(IE, VecOp);
12644       
12645       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12646         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12647       
12648       // If we are extracting a value from a vector, then inserting it right
12649       // back into the same place, just use the input vector.
12650       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12651         return ReplaceInstUsesWith(IE, VecOp);      
12652       
12653       // We could theoretically do this for ANY input.  However, doing so could
12654       // turn chains of insertelement instructions into a chain of shufflevector
12655       // instructions, and right now we do not merge shufflevectors.  As such,
12656       // only do this in a situation where it is clear that there is benefit.
12657       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12658         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12659         // the values of VecOp, except then one read from EIOp0.
12660         // Build a new shuffle mask.
12661         std::vector<Constant*> Mask;
12662         if (isa<UndefValue>(VecOp))
12663           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12664         else {
12665           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12666           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12667                                                        NumVectorElts));
12668         } 
12669         Mask[InsertedIdx] = 
12670                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12671         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12672                                      Context->getConstantVector(Mask));
12673       }
12674       
12675       // If this insertelement isn't used by some other insertelement, turn it
12676       // (and any insertelements it points to), into one big shuffle.
12677       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12678         std::vector<Constant*> Mask;
12679         Value *RHS = 0;
12680         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12681         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12682         // We now have a shuffle of LHS, RHS, Mask.
12683         return new ShuffleVectorInst(LHS, RHS,
12684                                      Context->getConstantVector(Mask));
12685       }
12686     }
12687   }
12688
12689   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12690   APInt UndefElts(VWidth, 0);
12691   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12692   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12693     return &IE;
12694
12695   return 0;
12696 }
12697
12698
12699 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12700   Value *LHS = SVI.getOperand(0);
12701   Value *RHS = SVI.getOperand(1);
12702   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12703
12704   bool MadeChange = false;
12705
12706   // Undefined shuffle mask -> undefined value.
12707   if (isa<UndefValue>(SVI.getOperand(2)))
12708     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12709
12710   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12711
12712   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12713     return 0;
12714
12715   APInt UndefElts(VWidth, 0);
12716   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12717   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12718     LHS = SVI.getOperand(0);
12719     RHS = SVI.getOperand(1);
12720     MadeChange = true;
12721   }
12722   
12723   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12724   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12725   if (LHS == RHS || isa<UndefValue>(LHS)) {
12726     if (isa<UndefValue>(LHS) && LHS == RHS) {
12727       // shuffle(undef,undef,mask) -> undef.
12728       return ReplaceInstUsesWith(SVI, LHS);
12729     }
12730     
12731     // Remap any references to RHS to use LHS.
12732     std::vector<Constant*> Elts;
12733     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12734       if (Mask[i] >= 2*e)
12735         Elts.push_back(Context->getUndef(Type::Int32Ty));
12736       else {
12737         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12738             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12739           Mask[i] = 2*e;     // Turn into undef.
12740           Elts.push_back(Context->getUndef(Type::Int32Ty));
12741         } else {
12742           Mask[i] = Mask[i] % e;  // Force to LHS.
12743           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12744         }
12745       }
12746     }
12747     SVI.setOperand(0, SVI.getOperand(1));
12748     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12749     SVI.setOperand(2, Context->getConstantVector(Elts));
12750     LHS = SVI.getOperand(0);
12751     RHS = SVI.getOperand(1);
12752     MadeChange = true;
12753   }
12754   
12755   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12756   bool isLHSID = true, isRHSID = true;
12757     
12758   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12759     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12760     // Is this an identity shuffle of the LHS value?
12761     isLHSID &= (Mask[i] == i);
12762       
12763     // Is this an identity shuffle of the RHS value?
12764     isRHSID &= (Mask[i]-e == i);
12765   }
12766
12767   // Eliminate identity shuffles.
12768   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12769   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12770   
12771   // If the LHS is a shufflevector itself, see if we can combine it with this
12772   // one without producing an unusual shuffle.  Here we are really conservative:
12773   // we are absolutely afraid of producing a shuffle mask not in the input
12774   // program, because the code gen may not be smart enough to turn a merged
12775   // shuffle into two specific shuffles: it may produce worse code.  As such,
12776   // we only merge two shuffles if the result is one of the two input shuffle
12777   // masks.  In this case, merging the shuffles just removes one instruction,
12778   // which we know is safe.  This is good for things like turning:
12779   // (splat(splat)) -> splat.
12780   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12781     if (isa<UndefValue>(RHS)) {
12782       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12783
12784       std::vector<unsigned> NewMask;
12785       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12786         if (Mask[i] >= 2*e)
12787           NewMask.push_back(2*e);
12788         else
12789           NewMask.push_back(LHSMask[Mask[i]]);
12790       
12791       // If the result mask is equal to the src shuffle or this shuffle mask, do
12792       // the replacement.
12793       if (NewMask == LHSMask || NewMask == Mask) {
12794         unsigned LHSInNElts =
12795           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12796         std::vector<Constant*> Elts;
12797         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12798           if (NewMask[i] >= LHSInNElts*2) {
12799             Elts.push_back(Context->getUndef(Type::Int32Ty));
12800           } else {
12801             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12802           }
12803         }
12804         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12805                                      LHSSVI->getOperand(1),
12806                                      Context->getConstantVector(Elts));
12807       }
12808     }
12809   }
12810
12811   return MadeChange ? &SVI : 0;
12812 }
12813
12814
12815
12816
12817 /// TryToSinkInstruction - Try to move the specified instruction from its
12818 /// current block into the beginning of DestBlock, which can only happen if it's
12819 /// safe to move the instruction past all of the instructions between it and the
12820 /// end of its block.
12821 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12822   assert(I->hasOneUse() && "Invariants didn't hold!");
12823
12824   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12825   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12826     return false;
12827
12828   // Do not sink alloca instructions out of the entry block.
12829   if (isa<AllocaInst>(I) && I->getParent() ==
12830         &DestBlock->getParent()->getEntryBlock())
12831     return false;
12832
12833   // We can only sink load instructions if there is nothing between the load and
12834   // the end of block that could change the value.
12835   if (I->mayReadFromMemory()) {
12836     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12837          Scan != E; ++Scan)
12838       if (Scan->mayWriteToMemory())
12839         return false;
12840   }
12841
12842   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12843
12844   CopyPrecedingStopPoint(I, InsertPos);
12845   I->moveBefore(InsertPos);
12846   ++NumSunkInst;
12847   return true;
12848 }
12849
12850
12851 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12852 /// all reachable code to the worklist.
12853 ///
12854 /// This has a couple of tricks to make the code faster and more powerful.  In
12855 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12856 /// them to the worklist (this significantly speeds up instcombine on code where
12857 /// many instructions are dead or constant).  Additionally, if we find a branch
12858 /// whose condition is a known constant, we only visit the reachable successors.
12859 ///
12860 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12861                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12862                                        InstCombiner &IC,
12863                                        const TargetData *TD) {
12864   SmallVector<BasicBlock*, 256> Worklist;
12865   Worklist.push_back(BB);
12866
12867   while (!Worklist.empty()) {
12868     BB = Worklist.back();
12869     Worklist.pop_back();
12870     
12871     // We have now visited this block!  If we've already been here, ignore it.
12872     if (!Visited.insert(BB)) continue;
12873
12874     DbgInfoIntrinsic *DBI_Prev = NULL;
12875     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12876       Instruction *Inst = BBI++;
12877       
12878       // DCE instruction if trivially dead.
12879       if (isInstructionTriviallyDead(Inst)) {
12880         ++NumDeadInst;
12881         DOUT << "IC: DCE: " << *Inst;
12882         Inst->eraseFromParent();
12883         continue;
12884       }
12885       
12886       // ConstantProp instruction if trivially constant.
12887       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12888         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12889         Inst->replaceAllUsesWith(C);
12890         ++NumConstProp;
12891         Inst->eraseFromParent();
12892         continue;
12893       }
12894      
12895       // If there are two consecutive llvm.dbg.stoppoint calls then
12896       // it is likely that the optimizer deleted code in between these
12897       // two intrinsics. 
12898       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12899       if (DBI_Next) {
12900         if (DBI_Prev
12901             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12902             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12903           IC.RemoveFromWorkList(DBI_Prev);
12904           DBI_Prev->eraseFromParent();
12905         }
12906         DBI_Prev = DBI_Next;
12907       } else {
12908         DBI_Prev = 0;
12909       }
12910
12911       IC.AddToWorkList(Inst);
12912     }
12913
12914     // Recursively visit successors.  If this is a branch or switch on a
12915     // constant, only visit the reachable successor.
12916     TerminatorInst *TI = BB->getTerminator();
12917     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12918       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12919         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12920         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12921         Worklist.push_back(ReachableBB);
12922         continue;
12923       }
12924     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12925       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12926         // See if this is an explicit destination.
12927         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12928           if (SI->getCaseValue(i) == Cond) {
12929             BasicBlock *ReachableBB = SI->getSuccessor(i);
12930             Worklist.push_back(ReachableBB);
12931             continue;
12932           }
12933         
12934         // Otherwise it is the default destination.
12935         Worklist.push_back(SI->getSuccessor(0));
12936         continue;
12937       }
12938     }
12939     
12940     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12941       Worklist.push_back(TI->getSuccessor(i));
12942   }
12943 }
12944
12945 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12946   bool Changed = false;
12947   TD = &getAnalysis<TargetData>();
12948   
12949   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12950              << F.getNameStr() << "\n");
12951
12952   {
12953     // Do a depth-first traversal of the function, populate the worklist with
12954     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12955     // track of which blocks we visit.
12956     SmallPtrSet<BasicBlock*, 64> Visited;
12957     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12958
12959     // Do a quick scan over the function.  If we find any blocks that are
12960     // unreachable, remove any instructions inside of them.  This prevents
12961     // the instcombine code from having to deal with some bad special cases.
12962     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12963       if (!Visited.count(BB)) {
12964         Instruction *Term = BB->getTerminator();
12965         while (Term != BB->begin()) {   // Remove instrs bottom-up
12966           BasicBlock::iterator I = Term; --I;
12967
12968           DOUT << "IC: DCE: " << *I;
12969           // A debug intrinsic shouldn't force another iteration if we weren't
12970           // going to do one without it.
12971           if (!isa<DbgInfoIntrinsic>(I)) {
12972             ++NumDeadInst;
12973             Changed = true;
12974           }
12975           if (!I->use_empty())
12976             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12977           I->eraseFromParent();
12978         }
12979       }
12980   }
12981
12982   while (!Worklist.empty()) {
12983     Instruction *I = RemoveOneFromWorkList();
12984     if (I == 0) continue;  // skip null values.
12985
12986     // Check to see if we can DCE the instruction.
12987     if (isInstructionTriviallyDead(I)) {
12988       // Add operands to the worklist.
12989       if (I->getNumOperands() < 4)
12990         AddUsesToWorkList(*I);
12991       ++NumDeadInst;
12992
12993       DOUT << "IC: DCE: " << *I;
12994
12995       I->eraseFromParent();
12996       RemoveFromWorkList(I);
12997       Changed = true;
12998       continue;
12999     }
13000
13001     // Instruction isn't dead, see if we can constant propagate it.
13002     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13003       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13004
13005       // Add operands to the worklist.
13006       AddUsesToWorkList(*I);
13007       ReplaceInstUsesWith(*I, C);
13008
13009       ++NumConstProp;
13010       I->eraseFromParent();
13011       RemoveFromWorkList(I);
13012       Changed = true;
13013       continue;
13014     }
13015
13016     if (TD &&
13017         (I->getType()->getTypeID() == Type::VoidTyID ||
13018          I->isTrapping())) {
13019       // See if we can constant fold its operands.
13020       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13021         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13022           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13023                                   F.getContext(), TD))
13024             if (NewC != CE) {
13025               i->set(NewC);
13026               Changed = true;
13027             }
13028     }
13029
13030     // See if we can trivially sink this instruction to a successor basic block.
13031     if (I->hasOneUse()) {
13032       BasicBlock *BB = I->getParent();
13033       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13034       if (UserParent != BB) {
13035         bool UserIsSuccessor = false;
13036         // See if the user is one of our successors.
13037         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13038           if (*SI == UserParent) {
13039             UserIsSuccessor = true;
13040             break;
13041           }
13042
13043         // If the user is one of our immediate successors, and if that successor
13044         // only has us as a predecessors (we'd have to split the critical edge
13045         // otherwise), we can keep going.
13046         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13047             next(pred_begin(UserParent)) == pred_end(UserParent))
13048           // Okay, the CFG is simple enough, try to sink this instruction.
13049           Changed |= TryToSinkInstruction(I, UserParent);
13050       }
13051     }
13052
13053     // Now that we have an instruction, try combining it to simplify it...
13054 #ifndef NDEBUG
13055     std::string OrigI;
13056 #endif
13057     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13058     if (Instruction *Result = visit(*I)) {
13059       ++NumCombined;
13060       // Should we replace the old instruction with a new one?
13061       if (Result != I) {
13062         DOUT << "IC: Old = " << *I
13063              << "    New = " << *Result;
13064
13065         // Everything uses the new instruction now.
13066         I->replaceAllUsesWith(Result);
13067
13068         // Push the new instruction and any users onto the worklist.
13069         AddToWorkList(Result);
13070         AddUsersToWorkList(*Result);
13071
13072         // Move the name to the new instruction first.
13073         Result->takeName(I);
13074
13075         // Insert the new instruction into the basic block...
13076         BasicBlock *InstParent = I->getParent();
13077         BasicBlock::iterator InsertPos = I;
13078
13079         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13080           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13081             ++InsertPos;
13082
13083         InstParent->getInstList().insert(InsertPos, Result);
13084
13085         // Make sure that we reprocess all operands now that we reduced their
13086         // use counts.
13087         AddUsesToWorkList(*I);
13088
13089         // Instructions can end up on the worklist more than once.  Make sure
13090         // we do not process an instruction that has been deleted.
13091         RemoveFromWorkList(I);
13092
13093         // Erase the old instruction.
13094         InstParent->getInstList().erase(I);
13095       } else {
13096 #ifndef NDEBUG
13097         DOUT << "IC: Mod = " << OrigI
13098              << "    New = " << *I;
13099 #endif
13100
13101         // If the instruction was modified, it's possible that it is now dead.
13102         // if so, remove it.
13103         if (isInstructionTriviallyDead(I)) {
13104           // Make sure we process all operands now that we are reducing their
13105           // use counts.
13106           AddUsesToWorkList(*I);
13107
13108           // Instructions may end up in the worklist more than once.  Erase all
13109           // occurrences of this instruction.
13110           RemoveFromWorkList(I);
13111           I->eraseFromParent();
13112         } else {
13113           AddToWorkList(I);
13114           AddUsersToWorkList(*I);
13115         }
13116       }
13117       Changed = true;
13118     }
13119   }
13120
13121   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13122     
13123   // Do an explicit clear, this shrinks the map if needed.
13124   WorklistMap.clear();
13125   return Changed;
13126 }
13127
13128
13129 bool InstCombiner::runOnFunction(Function &F) {
13130   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13131   
13132   bool EverMadeChange = false;
13133
13134   // Iterate while there is work to do.
13135   unsigned Iteration = 0;
13136   while (DoOneIteration(F, Iteration++))
13137     EverMadeChange = true;
13138   return EverMadeChange;
13139 }
13140
13141 FunctionPass *llvm::createInstructionCombiningPass() {
13142   return new InstCombiner();
13143 }