e0dfe29e0fe605a3c3b5d95cb69c62146b7def1e
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/Statistic.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include <algorithm>
65 #include <climits>
66 #include <sstream>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   class VISIBILITY_HIDDEN InstCombiner
78     : public FunctionPass,
79       public InstVisitor<InstCombiner, Instruction*> {
80     // Worklist of all of the instructions that need to be simplified.
81     SmallVector<Instruction*, 256> Worklist;
82     DenseMap<Instruction*, unsigned> WorklistMap;
83     TargetData *TD;
84     bool MustPreserveLCSSA;
85   public:
86     static char ID; // Pass identification, replacement for typeid
87     InstCombiner() : FunctionPass(&ID) {}
88
89     LLVMContext *Context;
90     LLVMContext *getContext() const { return Context; }
91
92     /// AddToWorkList - Add the specified instruction to the worklist if it
93     /// isn't already in it.
94     void AddToWorkList(Instruction *I) {
95       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
96         Worklist.push_back(I);
97     }
98     
99     // RemoveFromWorkList - remove I from the worklist if it exists.
100     void RemoveFromWorkList(Instruction *I) {
101       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102       if (It == WorklistMap.end()) return; // Not in worklist.
103       
104       // Don't bother moving everything down, just null out the slot.
105       Worklist[It->second] = 0;
106       
107       WorklistMap.erase(It);
108     }
109     
110     Instruction *RemoveOneFromWorkList() {
111       Instruction *I = Worklist.back();
112       Worklist.pop_back();
113       WorklistMap.erase(I);
114       return I;
115     }
116
117     
118     /// AddUsersToWorkList - When an instruction is simplified, add all users of
119     /// the instruction to the work lists because they might get more simplified
120     /// now.
121     ///
122     void AddUsersToWorkList(Value &I) {
123       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124            UI != UE; ++UI)
125         AddToWorkList(cast<Instruction>(*UI));
126     }
127
128     /// AddUsesToWorkList - When an instruction is simplified, add operands to
129     /// the work lists because they might get more simplified now.
130     ///
131     void AddUsesToWorkList(Instruction &I) {
132       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133         if (Instruction *Op = dyn_cast<Instruction>(*i))
134           AddToWorkList(Op);
135     }
136     
137     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138     /// dead.  Add all of its operands to the worklist, turning them into
139     /// undef's to reduce the number of uses of those instructions.
140     ///
141     /// Return the specified operand before it is turned into an undef.
142     ///
143     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144       Value *R = I.getOperand(op);
145       
146       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
148           AddToWorkList(Op);
149           // Set the operand to undef to drop the use.
150           *i = UndefValue::get(Op->getType());
151         }
152       
153       return R;
154     }
155
156   public:
157     virtual bool runOnFunction(Function &F);
158     
159     bool DoOneIteration(Function &F, unsigned ItNum);
160
161     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162       AU.addPreservedID(LCSSAID);
163       AU.setPreservesCFG();
164     }
165
166     TargetData *getTargetData() const { return TD; }
167
168     // Visitation implementation - Implement instruction combining for different
169     // instruction types.  The semantics are as follows:
170     // Return Value:
171     //    null        - No change was made
172     //     I          - Change was made, I is still valid, I may be dead though
173     //   otherwise    - Change was made, replace I with returned instruction
174     //
175     Instruction *visitAdd(BinaryOperator &I);
176     Instruction *visitFAdd(BinaryOperator &I);
177     Instruction *visitSub(BinaryOperator &I);
178     Instruction *visitFSub(BinaryOperator &I);
179     Instruction *visitMul(BinaryOperator &I);
180     Instruction *visitFMul(BinaryOperator &I);
181     Instruction *visitURem(BinaryOperator &I);
182     Instruction *visitSRem(BinaryOperator &I);
183     Instruction *visitFRem(BinaryOperator &I);
184     bool SimplifyDivRemOfSelect(BinaryOperator &I);
185     Instruction *commonRemTransforms(BinaryOperator &I);
186     Instruction *commonIRemTransforms(BinaryOperator &I);
187     Instruction *commonDivTransforms(BinaryOperator &I);
188     Instruction *commonIDivTransforms(BinaryOperator &I);
189     Instruction *visitUDiv(BinaryOperator &I);
190     Instruction *visitSDiv(BinaryOperator &I);
191     Instruction *visitFDiv(BinaryOperator &I);
192     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
194     Instruction *visitAnd(BinaryOperator &I);
195     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
196     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
197     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
198                                      Value *A, Value *B, Value *C);
199     Instruction *visitOr (BinaryOperator &I);
200     Instruction *visitXor(BinaryOperator &I);
201     Instruction *visitShl(BinaryOperator &I);
202     Instruction *visitAShr(BinaryOperator &I);
203     Instruction *visitLShr(BinaryOperator &I);
204     Instruction *commonShiftTransforms(BinaryOperator &I);
205     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206                                       Constant *RHSC);
207     Instruction *visitFCmpInst(FCmpInst &I);
208     Instruction *visitICmpInst(ICmpInst &I);
209     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211                                                 Instruction *LHS,
212                                                 ConstantInt *RHS);
213     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214                                 ConstantInt *DivRHS);
215
216     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
217                              ICmpInst::Predicate Cond, Instruction &I);
218     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
219                                      BinaryOperator &I);
220     Instruction *commonCastTransforms(CastInst &CI);
221     Instruction *commonIntCastTransforms(CastInst &CI);
222     Instruction *commonPointerCastTransforms(CastInst &CI);
223     Instruction *visitTrunc(TruncInst &CI);
224     Instruction *visitZExt(ZExtInst &CI);
225     Instruction *visitSExt(SExtInst &CI);
226     Instruction *visitFPTrunc(FPTruncInst &CI);
227     Instruction *visitFPExt(CastInst &CI);
228     Instruction *visitFPToUI(FPToUIInst &FI);
229     Instruction *visitFPToSI(FPToSIInst &FI);
230     Instruction *visitUIToFP(CastInst &CI);
231     Instruction *visitSIToFP(CastInst &CI);
232     Instruction *visitPtrToInt(PtrToIntInst &CI);
233     Instruction *visitIntToPtr(IntToPtrInst &CI);
234     Instruction *visitBitCast(BitCastInst &CI);
235     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236                                 Instruction *FI);
237     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
238     Instruction *visitSelectInst(SelectInst &SI);
239     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
240     Instruction *visitCallInst(CallInst &CI);
241     Instruction *visitInvokeInst(InvokeInst &II);
242     Instruction *visitPHINode(PHINode &PN);
243     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244     Instruction *visitAllocationInst(AllocationInst &AI);
245     Instruction *visitFreeInst(FreeInst &FI);
246     Instruction *visitLoadInst(LoadInst &LI);
247     Instruction *visitStoreInst(StoreInst &SI);
248     Instruction *visitBranchInst(BranchInst &BI);
249     Instruction *visitSwitchInst(SwitchInst &SI);
250     Instruction *visitInsertElementInst(InsertElementInst &IE);
251     Instruction *visitExtractElementInst(ExtractElementInst &EI);
252     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
253     Instruction *visitExtractValueInst(ExtractValueInst &EV);
254
255     // visitInstruction - Specify what to return for unhandled instructions...
256     Instruction *visitInstruction(Instruction &I) { return 0; }
257
258   private:
259     Instruction *visitCallSite(CallSite CS);
260     bool transformConstExprCastCall(CallSite CS);
261     Instruction *transformCallThroughTrampoline(CallSite CS);
262     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263                                    bool DoXform = true);
264     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
265     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
267
268   public:
269     // InsertNewInstBefore - insert an instruction New before instruction Old
270     // in the program.  Add the new instruction to the worklist.
271     //
272     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273       assert(New && New->getParent() == 0 &&
274              "New instruction already inserted into a basic block!");
275       BasicBlock *BB = Old.getParent();
276       BB->getInstList().insert(&Old, New);  // Insert inst
277       AddToWorkList(New);
278       return New;
279     }
280
281     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282     /// This also adds the cast to the worklist.  Finally, this returns the
283     /// cast.
284     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285                             Instruction &Pos) {
286       if (V->getType() == Ty) return V;
287
288       if (Constant *CV = dyn_cast<Constant>(V))
289         return ConstantExpr::getCast(opc, CV, Ty);
290       
291       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
292       AddToWorkList(C);
293       return C;
294     }
295         
296     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298     }
299
300
301     // ReplaceInstUsesWith - This method is to be used when an instruction is
302     // found to be dead, replacable with another preexisting expression.  Here
303     // we add all uses of I to the worklist, replace all uses of I with the new
304     // value, then return I, so that the inst combiner will know that I was
305     // modified.
306     //
307     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308       AddUsersToWorkList(I);         // Add all modified instrs to worklist
309       if (&I != V) {
310         I.replaceAllUsesWith(V);
311         return &I;
312       } else {
313         // If we are replacing the instruction with itself, this must be in a
314         // segment of unreachable code, so just clobber the instruction.
315         I.replaceAllUsesWith(UndefValue::get(I.getType()));
316         return &I;
317       }
318     }
319
320     // EraseInstFromFunction - When dealing with an instruction that has side
321     // effects or produces a void value, we can't rely on DCE to delete the
322     // instruction.  Instead, visit methods should return the value returned by
323     // this function.
324     Instruction *EraseInstFromFunction(Instruction &I) {
325       assert(I.use_empty() && "Cannot erase instruction that is used!");
326       AddUsesToWorkList(I);
327       RemoveFromWorkList(&I);
328       I.eraseFromParent();
329       return 0;  // Don't do anything with FI
330     }
331         
332     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333                            APInt &KnownOne, unsigned Depth = 0) const {
334       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335     }
336     
337     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
338                            unsigned Depth = 0) const {
339       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340     }
341     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342       return llvm::ComputeNumSignBits(Op, TD, Depth);
343     }
344
345   private:
346
347     /// SimplifyCommutative - This performs a few simplifications for 
348     /// commutative operators.
349     bool SimplifyCommutative(BinaryOperator &I);
350
351     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352     /// most-complex to least-complex order.
353     bool SimplifyCompare(CmpInst &I);
354
355     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356     /// based on the demanded bits.
357     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
358                                    APInt& KnownZero, APInt& KnownOne,
359                                    unsigned Depth);
360     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
361                               APInt& KnownZero, APInt& KnownOne,
362                               unsigned Depth=0);
363         
364     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365     /// SimplifyDemandedBits knows about.  See if the instruction has any
366     /// properties that allow us to simplify its operands.
367     bool SimplifyDemandedInstructionBits(Instruction &Inst);
368         
369     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370                                       APInt& UndefElts, unsigned Depth = 0);
371       
372     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373     // PHI node as operand #0, see if we can fold the instruction into the PHI
374     // (which is only possible if all operands to the PHI are constants).
375     Instruction *FoldOpIntoPhi(Instruction &I);
376
377     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378     // operator and they all are only used by the PHI, PHI together their
379     // inputs, and do the operation once, to the result of the PHI.
380     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
382     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
384     
385     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
387     
388     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389                               bool isSub, Instruction &I);
390     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391                                  bool isSigned, bool Inside, Instruction &IB);
392     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393     Instruction *MatchBSwap(BinaryOperator &I);
394     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
395     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
396     Instruction *SimplifyMemSet(MemSetInst *MI);
397
398
399     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
400
401     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
402                                     unsigned CastOpc, int &NumCastsRemoved);
403     unsigned GetOrEnforceKnownAlignment(Value *V,
404                                         unsigned PrefAlign = 0);
405
406   };
407 }
408
409 char InstCombiner::ID = 0;
410 static RegisterPass<InstCombiner>
411 X("instcombine", "Combine redundant instructions");
412
413 // getComplexity:  Assign a complexity or rank value to LLVM Values...
414 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
415 static unsigned getComplexity(LLVMContext *Context, Value *V) {
416   if (isa<Instruction>(V)) {
417     if (BinaryOperator::isNeg(V) ||
418         BinaryOperator::isFNeg(V) ||
419         BinaryOperator::isNot(V))
420       return 3;
421     return 4;
422   }
423   if (isa<Argument>(V)) return 3;
424   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425 }
426
427 // isOnlyUse - Return true if this instruction will be deleted if we stop using
428 // it.
429 static bool isOnlyUse(Value *V) {
430   return V->hasOneUse() || isa<Constant>(V);
431 }
432
433 // getPromotedType - Return the specified type promoted as it would be to pass
434 // though a va_arg area...
435 static const Type *getPromotedType(const Type *Ty) {
436   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437     if (ITy->getBitWidth() < 32)
438       return Type::Int32Ty;
439   }
440   return Ty;
441 }
442
443 /// getBitCastOperand - If the specified operand is a CastInst, a constant
444 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445 /// operand value, otherwise return null.
446 static Value *getBitCastOperand(Value *V) {
447   if (Operator *O = dyn_cast<Operator>(V)) {
448     if (O->getOpcode() == Instruction::BitCast)
449       return O->getOperand(0);
450     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451       if (GEP->hasAllZeroIndices())
452         return GEP->getPointerOperand();
453   }
454   return 0;
455 }
456
457 /// This function is a wrapper around CastInst::isEliminableCastPair. It
458 /// simply extracts arguments and returns what that function returns.
459 static Instruction::CastOps 
460 isEliminableCastPair(
461   const CastInst *CI, ///< The first cast instruction
462   unsigned opcode,       ///< The opcode of the second cast instruction
463   const Type *DstTy,     ///< The target type for the second cast instruction
464   TargetData *TD         ///< The target data for pointer size
465 ) {
466
467   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
468   const Type *MidTy = CI->getType();                  // B from above
469
470   // Get the opcodes of the two Cast instructions
471   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
473
474   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
475                                                 DstTy,
476                                                 TD ? TD->getIntPtrType() : 0);
477   
478   // We don't want to form an inttoptr or ptrtoint that converts to an integer
479   // type that differs from the pointer size.
480   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482     Res = 0;
483   
484   return Instruction::CastOps(Res);
485 }
486
487 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488 /// in any code being generated.  It does not require codegen if V is simple
489 /// enough or if the cast can be folded into other casts.
490 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
491                               const Type *Ty, TargetData *TD) {
492   if (V->getType() == Ty || isa<Constant>(V)) return false;
493   
494   // If this is another cast that can be eliminated, it isn't codegen either.
495   if (const CastInst *CI = dyn_cast<CastInst>(V))
496     if (isEliminableCastPair(CI, opcode, Ty, TD))
497       return false;
498   return true;
499 }
500
501 // SimplifyCommutative - This performs a few simplifications for commutative
502 // operators:
503 //
504 //  1. Order operands such that they are listed from right (least complex) to
505 //     left (most complex).  This puts constants before unary operators before
506 //     binary operators.
507 //
508 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
510 //
511 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
512   bool Changed = false;
513   if (getComplexity(Context, I.getOperand(0)) < 
514       getComplexity(Context, I.getOperand(1)))
515     Changed = !I.swapOperands();
516
517   if (!I.isAssociative()) return Changed;
518   Instruction::BinaryOps Opcode = I.getOpcode();
519   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521       if (isa<Constant>(I.getOperand(1))) {
522         Constant *Folded = ConstantExpr::get(I.getOpcode(),
523                                              cast<Constant>(I.getOperand(1)),
524                                              cast<Constant>(Op->getOperand(1)));
525         I.setOperand(0, Op->getOperand(0));
526         I.setOperand(1, Folded);
527         return true;
528       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530             isOnlyUse(Op) && isOnlyUse(Op1)) {
531           Constant *C1 = cast<Constant>(Op->getOperand(1));
532           Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
535           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
536           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
537                                                     Op1->getOperand(0),
538                                                     Op1->getName(), &I);
539           AddToWorkList(New);
540           I.setOperand(0, New);
541           I.setOperand(1, Folded);
542           return true;
543         }
544     }
545   return Changed;
546 }
547
548 /// SimplifyCompare - For a CmpInst this function just orders the operands
549 /// so that theyare listed from right (least complex) to left (most complex).
550 /// This puts constants before unary operators before binary operators.
551 bool InstCombiner::SimplifyCompare(CmpInst &I) {
552   if (getComplexity(Context, I.getOperand(0)) >=
553       getComplexity(Context, I.getOperand(1)))
554     return false;
555   I.swapOperands();
556   // Compare instructions are not associative so there's nothing else we can do.
557   return true;
558 }
559
560 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561 // if the LHS is a constant zero (which is the 'negate' form).
562 //
563 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
564   if (BinaryOperator::isNeg(V))
565     return BinaryOperator::getNegArgument(V);
566
567   // Constants can be considered to be negated values if they can be folded.
568   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569     return ConstantExpr::getNeg(C);
570
571   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572     if (C->getType()->getElementType()->isInteger())
573       return ConstantExpr::getNeg(C);
574
575   return 0;
576 }
577
578 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579 // instruction if the LHS is a constant negative zero (which is the 'negate'
580 // form).
581 //
582 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
583   if (BinaryOperator::isFNeg(V))
584     return BinaryOperator::getFNegArgument(V);
585
586   // Constants can be considered to be negated values if they can be folded.
587   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
588     return ConstantExpr::getFNeg(C);
589
590   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591     if (C->getType()->getElementType()->isFloatingPoint())
592       return ConstantExpr::getFNeg(C);
593
594   return 0;
595 }
596
597 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
598   if (BinaryOperator::isNot(V))
599     return BinaryOperator::getNotArgument(V);
600
601   // Constants can be considered to be not'ed values...
602   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
603     return ConstantInt::get(*Context, ~C->getValue());
604   return 0;
605 }
606
607 // dyn_castFoldableMul - If this value is a multiply that can be folded into
608 // other computations (because it has a constant operand), return the
609 // non-constant operand of the multiply, and set CST to point to the multiplier.
610 // Otherwise, return null.
611 //
612 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
613                                          LLVMContext *Context) {
614   if (V->hasOneUse() && V->getType()->isInteger())
615     if (Instruction *I = dyn_cast<Instruction>(V)) {
616       if (I->getOpcode() == Instruction::Mul)
617         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
618           return I->getOperand(0);
619       if (I->getOpcode() == Instruction::Shl)
620         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
621           // The multiplier is really 1 << CST.
622           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
623           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
624           CST = ConstantInt::get(*Context, APInt(BitWidth, 1).shl(CSTVal));
625           return I->getOperand(0);
626         }
627     }
628   return 0;
629 }
630
631 /// AddOne - Add one to a ConstantInt
632 static Constant *AddOne(Constant *C, LLVMContext *Context) {
633   return ConstantExpr::getAdd(C, 
634     ConstantInt::get(C->getType(), 1));
635 }
636 /// SubOne - Subtract one from a ConstantInt
637 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
638   return ConstantExpr::getSub(C, 
639     ConstantInt::get(C->getType(), 1));
640 }
641 /// MultiplyOverflows - True if the multiply can not be expressed in an int
642 /// this size.
643 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
644                               LLVMContext *Context) {
645   uint32_t W = C1->getBitWidth();
646   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
647   if (sign) {
648     LHSExt.sext(W * 2);
649     RHSExt.sext(W * 2);
650   } else {
651     LHSExt.zext(W * 2);
652     RHSExt.zext(W * 2);
653   }
654
655   APInt MulExt = LHSExt * RHSExt;
656
657   if (sign) {
658     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
659     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
660     return MulExt.slt(Min) || MulExt.sgt(Max);
661   } else 
662     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
663 }
664
665
666 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
667 /// specified instruction is a constant integer.  If so, check to see if there
668 /// are any bits set in the constant that are not demanded.  If so, shrink the
669 /// constant and return true.
670 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
671                                    APInt Demanded, LLVMContext *Context) {
672   assert(I && "No instruction?");
673   assert(OpNo < I->getNumOperands() && "Operand index too large");
674
675   // If the operand is not a constant integer, nothing to do.
676   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
677   if (!OpC) return false;
678
679   // If there are no bits set that aren't demanded, nothing to do.
680   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
681   if ((~Demanded & OpC->getValue()) == 0)
682     return false;
683
684   // This instruction is producing bits that are not demanded. Shrink the RHS.
685   Demanded &= OpC->getValue();
686   I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
687   return true;
688 }
689
690 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
691 // set of known zero and one bits, compute the maximum and minimum values that
692 // could have the specified known zero and known one bits, returning them in
693 // min/max.
694 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
695                                                    const APInt& KnownOne,
696                                                    APInt& Min, APInt& Max) {
697   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
698          KnownZero.getBitWidth() == Min.getBitWidth() &&
699          KnownZero.getBitWidth() == Max.getBitWidth() &&
700          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
701   APInt UnknownBits = ~(KnownZero|KnownOne);
702
703   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
704   // bit if it is unknown.
705   Min = KnownOne;
706   Max = KnownOne|UnknownBits;
707   
708   if (UnknownBits.isNegative()) { // Sign bit is unknown
709     Min.set(Min.getBitWidth()-1);
710     Max.clear(Max.getBitWidth()-1);
711   }
712 }
713
714 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
715 // a set of known zero and one bits, compute the maximum and minimum values that
716 // could have the specified known zero and known one bits, returning them in
717 // min/max.
718 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
719                                                      const APInt &KnownOne,
720                                                      APInt &Min, APInt &Max) {
721   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
722          KnownZero.getBitWidth() == Min.getBitWidth() &&
723          KnownZero.getBitWidth() == Max.getBitWidth() &&
724          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
725   APInt UnknownBits = ~(KnownZero|KnownOne);
726   
727   // The minimum value is when the unknown bits are all zeros.
728   Min = KnownOne;
729   // The maximum value is when the unknown bits are all ones.
730   Max = KnownOne|UnknownBits;
731 }
732
733 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
734 /// SimplifyDemandedBits knows about.  See if the instruction has any
735 /// properties that allow us to simplify its operands.
736 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
737   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
738   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
739   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
740   
741   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
742                                      KnownZero, KnownOne, 0);
743   if (V == 0) return false;
744   if (V == &Inst) return true;
745   ReplaceInstUsesWith(Inst, V);
746   return true;
747 }
748
749 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
750 /// specified instruction operand if possible, updating it in place.  It returns
751 /// true if it made any change and false otherwise.
752 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
753                                         APInt &KnownZero, APInt &KnownOne,
754                                         unsigned Depth) {
755   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
756                                           KnownZero, KnownOne, Depth);
757   if (NewVal == 0) return false;
758   U.set(NewVal);
759   return true;
760 }
761
762
763 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
764 /// value based on the demanded bits.  When this function is called, it is known
765 /// that only the bits set in DemandedMask of the result of V are ever used
766 /// downstream. Consequently, depending on the mask and V, it may be possible
767 /// to replace V with a constant or one of its operands. In such cases, this
768 /// function does the replacement and returns true. In all other cases, it
769 /// returns false after analyzing the expression and setting KnownOne and known
770 /// to be one in the expression.  KnownZero contains all the bits that are known
771 /// to be zero in the expression. These are provided to potentially allow the
772 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773 /// the expression. KnownOne and KnownZero always follow the invariant that 
774 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
776 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777 /// and KnownOne must all be the same.
778 ///
779 /// This returns null if it did not change anything and it permits no
780 /// simplification.  This returns V itself if it did some simplification of V's
781 /// operands based on the information about what bits are demanded. This returns
782 /// some other non-null value if it found out that V is equal to another value
783 /// in the context where the specified bits are demanded, but not for all users.
784 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
785                                              APInt &KnownZero, APInt &KnownOne,
786                                              unsigned Depth) {
787   assert(V != 0 && "Null pointer of Value???");
788   assert(Depth <= 6 && "Limit Search Depth");
789   uint32_t BitWidth = DemandedMask.getBitWidth();
790   const Type *VTy = V->getType();
791   assert((TD || !isa<PointerType>(VTy)) &&
792          "SimplifyDemandedBits needs to know bit widths!");
793   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
794          (!VTy->isIntOrIntVector() ||
795           VTy->getScalarSizeInBits() == BitWidth) &&
796          KnownZero.getBitWidth() == BitWidth &&
797          KnownOne.getBitWidth() == BitWidth &&
798          "Value *V, DemandedMask, KnownZero and KnownOne "
799          "must have same BitWidth");
800   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
801     // We know all of the bits for a constant!
802     KnownOne = CI->getValue() & DemandedMask;
803     KnownZero = ~KnownOne & DemandedMask;
804     return 0;
805   }
806   if (isa<ConstantPointerNull>(V)) {
807     // We know all of the bits for a constant!
808     KnownOne.clear();
809     KnownZero = DemandedMask;
810     return 0;
811   }
812
813   KnownZero.clear();
814   KnownOne.clear();
815   if (DemandedMask == 0) {   // Not demanding any bits from V.
816     if (isa<UndefValue>(V))
817       return 0;
818     return UndefValue::get(VTy);
819   }
820   
821   if (Depth == 6)        // Limit search depth.
822     return 0;
823   
824   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
825   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
826
827   Instruction *I = dyn_cast<Instruction>(V);
828   if (!I) {
829     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
830     return 0;        // Only analyze instructions.
831   }
832
833   // If there are multiple uses of this value and we aren't at the root, then
834   // we can't do any simplifications of the operands, because DemandedMask
835   // only reflects the bits demanded by *one* of the users.
836   if (Depth != 0 && !I->hasOneUse()) {
837     // Despite the fact that we can't simplify this instruction in all User's
838     // context, we can at least compute the knownzero/knownone bits, and we can
839     // do simplifications that apply to *just* the one user if we know that
840     // this instruction has a simpler value in that context.
841     if (I->getOpcode() == Instruction::And) {
842       // If either the LHS or the RHS are Zero, the result is zero.
843       ComputeMaskedBits(I->getOperand(1), DemandedMask,
844                         RHSKnownZero, RHSKnownOne, Depth+1);
845       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
846                         LHSKnownZero, LHSKnownOne, Depth+1);
847       
848       // If all of the demanded bits are known 1 on one side, return the other.
849       // These bits cannot contribute to the result of the 'and' in this
850       // context.
851       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
852           (DemandedMask & ~LHSKnownZero))
853         return I->getOperand(0);
854       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
855           (DemandedMask & ~RHSKnownZero))
856         return I->getOperand(1);
857       
858       // If all of the demanded bits in the inputs are known zeros, return zero.
859       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
860         return Context->getNullValue(VTy);
861       
862     } else if (I->getOpcode() == Instruction::Or) {
863       // We can simplify (X|Y) -> X or Y in the user's context if we know that
864       // only bits from X or Y are demanded.
865       
866       // If either the LHS or the RHS are One, the result is One.
867       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
868                         RHSKnownZero, RHSKnownOne, Depth+1);
869       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
870                         LHSKnownZero, LHSKnownOne, Depth+1);
871       
872       // If all of the demanded bits are known zero on one side, return the
873       // other.  These bits cannot contribute to the result of the 'or' in this
874       // context.
875       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
876           (DemandedMask & ~LHSKnownOne))
877         return I->getOperand(0);
878       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
879           (DemandedMask & ~RHSKnownOne))
880         return I->getOperand(1);
881       
882       // If all of the potentially set bits on one side are known to be set on
883       // the other side, just use the 'other' side.
884       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
885           (DemandedMask & (~RHSKnownZero)))
886         return I->getOperand(0);
887       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
888           (DemandedMask & (~LHSKnownZero)))
889         return I->getOperand(1);
890     }
891     
892     // Compute the KnownZero/KnownOne bits to simplify things downstream.
893     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
894     return 0;
895   }
896   
897   // If this is the root being simplified, allow it to have multiple uses,
898   // just set the DemandedMask to all bits so that we can try to simplify the
899   // operands.  This allows visitTruncInst (for example) to simplify the
900   // operand of a trunc without duplicating all the logic below.
901   if (Depth == 0 && !V->hasOneUse())
902     DemandedMask = APInt::getAllOnesValue(BitWidth);
903   
904   switch (I->getOpcode()) {
905   default:
906     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
907     break;
908   case Instruction::And:
909     // If either the LHS or the RHS are Zero, the result is zero.
910     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
911                              RHSKnownZero, RHSKnownOne, Depth+1) ||
912         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
913                              LHSKnownZero, LHSKnownOne, Depth+1))
914       return I;
915     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
916     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
917
918     // If all of the demanded bits are known 1 on one side, return the other.
919     // These bits cannot contribute to the result of the 'and'.
920     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
921         (DemandedMask & ~LHSKnownZero))
922       return I->getOperand(0);
923     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
924         (DemandedMask & ~RHSKnownZero))
925       return I->getOperand(1);
926     
927     // If all of the demanded bits in the inputs are known zeros, return zero.
928     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
929       return Context->getNullValue(VTy);
930       
931     // If the RHS is a constant, see if we can simplify it.
932     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
933       return I;
934       
935     // Output known-1 bits are only known if set in both the LHS & RHS.
936     RHSKnownOne &= LHSKnownOne;
937     // Output known-0 are known to be clear if zero in either the LHS | RHS.
938     RHSKnownZero |= LHSKnownZero;
939     break;
940   case Instruction::Or:
941     // If either the LHS or the RHS are One, the result is One.
942     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
943                              RHSKnownZero, RHSKnownOne, Depth+1) ||
944         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
945                              LHSKnownZero, LHSKnownOne, Depth+1))
946       return I;
947     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
948     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
949     
950     // If all of the demanded bits are known zero on one side, return the other.
951     // These bits cannot contribute to the result of the 'or'.
952     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
953         (DemandedMask & ~LHSKnownOne))
954       return I->getOperand(0);
955     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
956         (DemandedMask & ~RHSKnownOne))
957       return I->getOperand(1);
958
959     // If all of the potentially set bits on one side are known to be set on
960     // the other side, just use the 'other' side.
961     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
962         (DemandedMask & (~RHSKnownZero)))
963       return I->getOperand(0);
964     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
965         (DemandedMask & (~LHSKnownZero)))
966       return I->getOperand(1);
967         
968     // If the RHS is a constant, see if we can simplify it.
969     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
970       return I;
971           
972     // Output known-0 bits are only known if clear in both the LHS & RHS.
973     RHSKnownZero &= LHSKnownZero;
974     // Output known-1 are known to be set if set in either the LHS | RHS.
975     RHSKnownOne |= LHSKnownOne;
976     break;
977   case Instruction::Xor: {
978     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979                              RHSKnownZero, RHSKnownOne, Depth+1) ||
980         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
981                              LHSKnownZero, LHSKnownOne, Depth+1))
982       return I;
983     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
984     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
985     
986     // If all of the demanded bits are known zero on one side, return the other.
987     // These bits cannot contribute to the result of the 'xor'.
988     if ((DemandedMask & RHSKnownZero) == DemandedMask)
989       return I->getOperand(0);
990     if ((DemandedMask & LHSKnownZero) == DemandedMask)
991       return I->getOperand(1);
992     
993     // Output known-0 bits are known if clear or set in both the LHS & RHS.
994     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
995                          (RHSKnownOne & LHSKnownOne);
996     // Output known-1 are known to be set if set in only one of the LHS, RHS.
997     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
998                         (RHSKnownOne & LHSKnownZero);
999     
1000     // If all of the demanded bits are known to be zero on one side or the
1001     // other, turn this into an *inclusive* or.
1002     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1003     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1004       Instruction *Or =
1005         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1006                                  I->getName());
1007       return InsertNewInstBefore(Or, *I);
1008     }
1009     
1010     // If all of the demanded bits on one side are known, and all of the set
1011     // bits on that side are also known to be set on the other side, turn this
1012     // into an AND, as we know the bits will be cleared.
1013     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1014     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1015       // all known
1016       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1017         Constant *AndC = ConstantInt::get(*Context, 
1018                                           ~RHSKnownOne & DemandedMask);
1019         Instruction *And = 
1020           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1021         return InsertNewInstBefore(And, *I);
1022       }
1023     }
1024     
1025     // If the RHS is a constant, see if we can simplify it.
1026     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1027     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1028       return I;
1029     
1030     RHSKnownZero = KnownZeroOut;
1031     RHSKnownOne  = KnownOneOut;
1032     break;
1033   }
1034   case Instruction::Select:
1035     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1036                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1037         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1038                              LHSKnownZero, LHSKnownOne, Depth+1))
1039       return I;
1040     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1041     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1042     
1043     // If the operands are constants, see if we can simplify them.
1044     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1045         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1046       return I;
1047     
1048     // Only known if known in both the LHS and RHS.
1049     RHSKnownOne &= LHSKnownOne;
1050     RHSKnownZero &= LHSKnownZero;
1051     break;
1052   case Instruction::Trunc: {
1053     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1054     DemandedMask.zext(truncBf);
1055     RHSKnownZero.zext(truncBf);
1056     RHSKnownOne.zext(truncBf);
1057     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1058                              RHSKnownZero, RHSKnownOne, Depth+1))
1059       return I;
1060     DemandedMask.trunc(BitWidth);
1061     RHSKnownZero.trunc(BitWidth);
1062     RHSKnownOne.trunc(BitWidth);
1063     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1064     break;
1065   }
1066   case Instruction::BitCast:
1067     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1068       return false;  // vector->int or fp->int?
1069
1070     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1071       if (const VectorType *SrcVTy =
1072             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1073         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1074           // Don't touch a bitcast between vectors of different element counts.
1075           return false;
1076       } else
1077         // Don't touch a scalar-to-vector bitcast.
1078         return false;
1079     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1080       // Don't touch a vector-to-scalar bitcast.
1081       return false;
1082
1083     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1084                              RHSKnownZero, RHSKnownOne, Depth+1))
1085       return I;
1086     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1087     break;
1088   case Instruction::ZExt: {
1089     // Compute the bits in the result that are not present in the input.
1090     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1091     
1092     DemandedMask.trunc(SrcBitWidth);
1093     RHSKnownZero.trunc(SrcBitWidth);
1094     RHSKnownOne.trunc(SrcBitWidth);
1095     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1096                              RHSKnownZero, RHSKnownOne, Depth+1))
1097       return I;
1098     DemandedMask.zext(BitWidth);
1099     RHSKnownZero.zext(BitWidth);
1100     RHSKnownOne.zext(BitWidth);
1101     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1102     // The top bits are known to be zero.
1103     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1104     break;
1105   }
1106   case Instruction::SExt: {
1107     // Compute the bits in the result that are not present in the input.
1108     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1109     
1110     APInt InputDemandedBits = DemandedMask & 
1111                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1112
1113     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1114     // If any of the sign extended bits are demanded, we know that the sign
1115     // bit is demanded.
1116     if ((NewBits & DemandedMask) != 0)
1117       InputDemandedBits.set(SrcBitWidth-1);
1118       
1119     InputDemandedBits.trunc(SrcBitWidth);
1120     RHSKnownZero.trunc(SrcBitWidth);
1121     RHSKnownOne.trunc(SrcBitWidth);
1122     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1123                              RHSKnownZero, RHSKnownOne, Depth+1))
1124       return I;
1125     InputDemandedBits.zext(BitWidth);
1126     RHSKnownZero.zext(BitWidth);
1127     RHSKnownOne.zext(BitWidth);
1128     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1129       
1130     // If the sign bit of the input is known set or clear, then we know the
1131     // top bits of the result.
1132
1133     // If the input sign bit is known zero, or if the NewBits are not demanded
1134     // convert this into a zero extension.
1135     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1136       // Convert to ZExt cast
1137       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1138       return InsertNewInstBefore(NewCast, *I);
1139     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1140       RHSKnownOne |= NewBits;
1141     }
1142     break;
1143   }
1144   case Instruction::Add: {
1145     // Figure out what the input bits are.  If the top bits of the and result
1146     // are not demanded, then the add doesn't demand them from its input
1147     // either.
1148     unsigned NLZ = DemandedMask.countLeadingZeros();
1149       
1150     // If there is a constant on the RHS, there are a variety of xformations
1151     // we can do.
1152     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1153       // If null, this should be simplified elsewhere.  Some of the xforms here
1154       // won't work if the RHS is zero.
1155       if (RHS->isZero())
1156         break;
1157       
1158       // If the top bit of the output is demanded, demand everything from the
1159       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1160       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1161
1162       // Find information about known zero/one bits in the input.
1163       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1164                                LHSKnownZero, LHSKnownOne, Depth+1))
1165         return I;
1166
1167       // If the RHS of the add has bits set that can't affect the input, reduce
1168       // the constant.
1169       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1170         return I;
1171       
1172       // Avoid excess work.
1173       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1174         break;
1175       
1176       // Turn it into OR if input bits are zero.
1177       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1178         Instruction *Or =
1179           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1180                                    I->getName());
1181         return InsertNewInstBefore(Or, *I);
1182       }
1183       
1184       // We can say something about the output known-zero and known-one bits,
1185       // depending on potential carries from the input constant and the
1186       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1187       // bits set and the RHS constant is 0x01001, then we know we have a known
1188       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1189       
1190       // To compute this, we first compute the potential carry bits.  These are
1191       // the bits which may be modified.  I'm not aware of a better way to do
1192       // this scan.
1193       const APInt &RHSVal = RHS->getValue();
1194       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1195       
1196       // Now that we know which bits have carries, compute the known-1/0 sets.
1197       
1198       // Bits are known one if they are known zero in one operand and one in the
1199       // other, and there is no input carry.
1200       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1201                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1202       
1203       // Bits are known zero if they are known zero in both operands and there
1204       // is no input carry.
1205       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1206     } else {
1207       // If the high-bits of this ADD are not demanded, then it does not demand
1208       // the high bits of its LHS or RHS.
1209       if (DemandedMask[BitWidth-1] == 0) {
1210         // Right fill the mask of bits for this ADD to demand the most
1211         // significant bit and all those below it.
1212         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1213         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1215             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1216                                  LHSKnownZero, LHSKnownOne, Depth+1))
1217           return I;
1218       }
1219     }
1220     break;
1221   }
1222   case Instruction::Sub:
1223     // If the high-bits of this SUB are not demanded, then it does not demand
1224     // the high bits of its LHS or RHS.
1225     if (DemandedMask[BitWidth-1] == 0) {
1226       // Right fill the mask of bits for this SUB to demand the most
1227       // significant bit and all those below it.
1228       uint32_t NLZ = DemandedMask.countLeadingZeros();
1229       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1230       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1231                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1232           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1233                                LHSKnownZero, LHSKnownOne, Depth+1))
1234         return I;
1235     }
1236     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1237     // the known zeros and ones.
1238     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1239     break;
1240   case Instruction::Shl:
1241     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1242       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1243       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1244       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1245                                RHSKnownZero, RHSKnownOne, Depth+1))
1246         return I;
1247       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1248       RHSKnownZero <<= ShiftAmt;
1249       RHSKnownOne  <<= ShiftAmt;
1250       // low bits known zero.
1251       if (ShiftAmt)
1252         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1253     }
1254     break;
1255   case Instruction::LShr:
1256     // For a logical shift right
1257     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1259       
1260       // Unsigned shift right.
1261       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1262       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1263                                RHSKnownZero, RHSKnownOne, Depth+1))
1264         return I;
1265       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1266       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1267       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1268       if (ShiftAmt) {
1269         // Compute the new bits that are at the top now.
1270         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1271         RHSKnownZero |= HighBits;  // high bits known zero.
1272       }
1273     }
1274     break;
1275   case Instruction::AShr:
1276     // If this is an arithmetic shift right and only the low-bit is set, we can
1277     // always convert this into a logical shr, even if the shift amount is
1278     // variable.  The low bit of the shift cannot be an input sign bit unless
1279     // the shift amount is >= the size of the datatype, which is undefined.
1280     if (DemandedMask == 1) {
1281       // Perform the logical shift right.
1282       Instruction *NewVal = BinaryOperator::CreateLShr(
1283                         I->getOperand(0), I->getOperand(1), I->getName());
1284       return InsertNewInstBefore(NewVal, *I);
1285     }    
1286
1287     // If the sign bit is the only bit demanded by this ashr, then there is no
1288     // need to do it, the shift doesn't change the high bit.
1289     if (DemandedMask.isSignBit())
1290       return I->getOperand(0);
1291     
1292     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1293       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1294       
1295       // Signed shift right.
1296       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1297       // If any of the "high bits" are demanded, we should set the sign bit as
1298       // demanded.
1299       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1300         DemandedMaskIn.set(BitWidth-1);
1301       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1302                                RHSKnownZero, RHSKnownOne, Depth+1))
1303         return I;
1304       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1305       // Compute the new bits that are at the top now.
1306       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1307       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1308       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1309         
1310       // Handle the sign bits.
1311       APInt SignBit(APInt::getSignBit(BitWidth));
1312       // Adjust to where it is now in the mask.
1313       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1314         
1315       // If the input sign bit is known to be zero, or if none of the top bits
1316       // are demanded, turn this into an unsigned shift right.
1317       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1318           (HighBits & ~DemandedMask) == HighBits) {
1319         // Perform the logical shift right.
1320         Instruction *NewVal = BinaryOperator::CreateLShr(
1321                           I->getOperand(0), SA, I->getName());
1322         return InsertNewInstBefore(NewVal, *I);
1323       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1324         RHSKnownOne |= HighBits;
1325       }
1326     }
1327     break;
1328   case Instruction::SRem:
1329     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1330       APInt RA = Rem->getValue().abs();
1331       if (RA.isPowerOf2()) {
1332         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1333           return I->getOperand(0);
1334
1335         APInt LowBits = RA - 1;
1336         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1337         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1338                                  LHSKnownZero, LHSKnownOne, Depth+1))
1339           return I;
1340
1341         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1342           LHSKnownZero |= ~LowBits;
1343
1344         KnownZero |= LHSKnownZero & DemandedMask;
1345
1346         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1347       }
1348     }
1349     break;
1350   case Instruction::URem: {
1351     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1352     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1353     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1354                              KnownZero2, KnownOne2, Depth+1) ||
1355         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1356                              KnownZero2, KnownOne2, Depth+1))
1357       return I;
1358
1359     unsigned Leaders = KnownZero2.countLeadingOnes();
1360     Leaders = std::max(Leaders,
1361                        KnownZero2.countLeadingOnes());
1362     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1363     break;
1364   }
1365   case Instruction::Call:
1366     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1367       switch (II->getIntrinsicID()) {
1368       default: break;
1369       case Intrinsic::bswap: {
1370         // If the only bits demanded come from one byte of the bswap result,
1371         // just shift the input byte into position to eliminate the bswap.
1372         unsigned NLZ = DemandedMask.countLeadingZeros();
1373         unsigned NTZ = DemandedMask.countTrailingZeros();
1374           
1375         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1376         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1377         // have 14 leading zeros, round to 8.
1378         NLZ &= ~7;
1379         NTZ &= ~7;
1380         // If we need exactly one byte, we can do this transformation.
1381         if (BitWidth-NLZ-NTZ == 8) {
1382           unsigned ResultBit = NTZ;
1383           unsigned InputBit = BitWidth-NTZ-8;
1384           
1385           // Replace this with either a left or right shift to get the byte into
1386           // the right place.
1387           Instruction *NewVal;
1388           if (InputBit > ResultBit)
1389             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1390                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1391           else
1392             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1393                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1394           NewVal->takeName(I);
1395           return InsertNewInstBefore(NewVal, *I);
1396         }
1397           
1398         // TODO: Could compute known zero/one bits based on the input.
1399         break;
1400       }
1401       }
1402     }
1403     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1404     break;
1405   }
1406   
1407   // If the client is only demanding bits that we know, return the known
1408   // constant.
1409   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1410     Constant *C = ConstantInt::get(*Context, RHSKnownOne);
1411     if (isa<PointerType>(V->getType()))
1412       C = ConstantExpr::getIntToPtr(C, V->getType());
1413     return C;
1414   }
1415   return false;
1416 }
1417
1418
1419 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1420 /// any number of elements. DemandedElts contains the set of elements that are
1421 /// actually used by the caller.  This method analyzes which elements of the
1422 /// operand are undef and returns that information in UndefElts.
1423 ///
1424 /// If the information about demanded elements can be used to simplify the
1425 /// operation, the operation is simplified, then the resultant value is
1426 /// returned.  This returns null if no change was made.
1427 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1428                                                 APInt& UndefElts,
1429                                                 unsigned Depth) {
1430   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1431   APInt EltMask(APInt::getAllOnesValue(VWidth));
1432   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1433
1434   if (isa<UndefValue>(V)) {
1435     // If the entire vector is undefined, just return this info.
1436     UndefElts = EltMask;
1437     return 0;
1438   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1439     UndefElts = EltMask;
1440     return UndefValue::get(V->getType());
1441   }
1442
1443   UndefElts = 0;
1444   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1445     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1446     Constant *Undef = UndefValue::get(EltTy);
1447
1448     std::vector<Constant*> Elts;
1449     for (unsigned i = 0; i != VWidth; ++i)
1450       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1451         Elts.push_back(Undef);
1452         UndefElts.set(i);
1453       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1454         Elts.push_back(Undef);
1455         UndefElts.set(i);
1456       } else {                               // Otherwise, defined.
1457         Elts.push_back(CP->getOperand(i));
1458       }
1459
1460     // If we changed the constant, return it.
1461     Constant *NewCP = ConstantVector::get(Elts);
1462     return NewCP != CP ? NewCP : 0;
1463   } else if (isa<ConstantAggregateZero>(V)) {
1464     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1465     // set to undef.
1466     
1467     // Check if this is identity. If so, return 0 since we are not simplifying
1468     // anything.
1469     if (DemandedElts == ((1ULL << VWidth) -1))
1470       return 0;
1471     
1472     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1473     Constant *Zero = Context->getNullValue(EltTy);
1474     Constant *Undef = UndefValue::get(EltTy);
1475     std::vector<Constant*> Elts;
1476     for (unsigned i = 0; i != VWidth; ++i) {
1477       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1478       Elts.push_back(Elt);
1479     }
1480     UndefElts = DemandedElts ^ EltMask;
1481     return ConstantVector::get(Elts);
1482   }
1483   
1484   // Limit search depth.
1485   if (Depth == 10)
1486     return 0;
1487
1488   // If multiple users are using the root value, procede with
1489   // simplification conservatively assuming that all elements
1490   // are needed.
1491   if (!V->hasOneUse()) {
1492     // Quit if we find multiple users of a non-root value though.
1493     // They'll be handled when it's their turn to be visited by
1494     // the main instcombine process.
1495     if (Depth != 0)
1496       // TODO: Just compute the UndefElts information recursively.
1497       return 0;
1498
1499     // Conservatively assume that all elements are needed.
1500     DemandedElts = EltMask;
1501   }
1502   
1503   Instruction *I = dyn_cast<Instruction>(V);
1504   if (!I) return 0;        // Only analyze instructions.
1505   
1506   bool MadeChange = false;
1507   APInt UndefElts2(VWidth, 0);
1508   Value *TmpV;
1509   switch (I->getOpcode()) {
1510   default: break;
1511     
1512   case Instruction::InsertElement: {
1513     // If this is a variable index, we don't know which element it overwrites.
1514     // demand exactly the same input as we produce.
1515     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1516     if (Idx == 0) {
1517       // Note that we can't propagate undef elt info, because we don't know
1518       // which elt is getting updated.
1519       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1520                                         UndefElts2, Depth+1);
1521       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1522       break;
1523     }
1524     
1525     // If this is inserting an element that isn't demanded, remove this
1526     // insertelement.
1527     unsigned IdxNo = Idx->getZExtValue();
1528     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1529       return AddSoonDeadInstToWorklist(*I, 0);
1530     
1531     // Otherwise, the element inserted overwrites whatever was there, so the
1532     // input demanded set is simpler than the output set.
1533     APInt DemandedElts2 = DemandedElts;
1534     DemandedElts2.clear(IdxNo);
1535     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1536                                       UndefElts, Depth+1);
1537     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1538
1539     // The inserted element is defined.
1540     UndefElts.clear(IdxNo);
1541     break;
1542   }
1543   case Instruction::ShuffleVector: {
1544     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1545     uint64_t LHSVWidth =
1546       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1547     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1548     for (unsigned i = 0; i < VWidth; i++) {
1549       if (DemandedElts[i]) {
1550         unsigned MaskVal = Shuffle->getMaskValue(i);
1551         if (MaskVal != -1u) {
1552           assert(MaskVal < LHSVWidth * 2 &&
1553                  "shufflevector mask index out of range!");
1554           if (MaskVal < LHSVWidth)
1555             LeftDemanded.set(MaskVal);
1556           else
1557             RightDemanded.set(MaskVal - LHSVWidth);
1558         }
1559       }
1560     }
1561
1562     APInt UndefElts4(LHSVWidth, 0);
1563     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1564                                       UndefElts4, Depth+1);
1565     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1566
1567     APInt UndefElts3(LHSVWidth, 0);
1568     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1569                                       UndefElts3, Depth+1);
1570     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1571
1572     bool NewUndefElts = false;
1573     for (unsigned i = 0; i < VWidth; i++) {
1574       unsigned MaskVal = Shuffle->getMaskValue(i);
1575       if (MaskVal == -1u) {
1576         UndefElts.set(i);
1577       } else if (MaskVal < LHSVWidth) {
1578         if (UndefElts4[MaskVal]) {
1579           NewUndefElts = true;
1580           UndefElts.set(i);
1581         }
1582       } else {
1583         if (UndefElts3[MaskVal - LHSVWidth]) {
1584           NewUndefElts = true;
1585           UndefElts.set(i);
1586         }
1587       }
1588     }
1589
1590     if (NewUndefElts) {
1591       // Add additional discovered undefs.
1592       std::vector<Constant*> Elts;
1593       for (unsigned i = 0; i < VWidth; ++i) {
1594         if (UndefElts[i])
1595           Elts.push_back(UndefValue::get(Type::Int32Ty));
1596         else
1597           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1598                                           Shuffle->getMaskValue(i)));
1599       }
1600       I->setOperand(2, ConstantVector::get(Elts));
1601       MadeChange = true;
1602     }
1603     break;
1604   }
1605   case Instruction::BitCast: {
1606     // Vector->vector casts only.
1607     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1608     if (!VTy) break;
1609     unsigned InVWidth = VTy->getNumElements();
1610     APInt InputDemandedElts(InVWidth, 0);
1611     unsigned Ratio;
1612
1613     if (VWidth == InVWidth) {
1614       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1615       // elements as are demanded of us.
1616       Ratio = 1;
1617       InputDemandedElts = DemandedElts;
1618     } else if (VWidth > InVWidth) {
1619       // Untested so far.
1620       break;
1621       
1622       // If there are more elements in the result than there are in the source,
1623       // then an input element is live if any of the corresponding output
1624       // elements are live.
1625       Ratio = VWidth/InVWidth;
1626       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1627         if (DemandedElts[OutIdx])
1628           InputDemandedElts.set(OutIdx/Ratio);
1629       }
1630     } else {
1631       // Untested so far.
1632       break;
1633       
1634       // If there are more elements in the source than there are in the result,
1635       // then an input element is live if the corresponding output element is
1636       // live.
1637       Ratio = InVWidth/VWidth;
1638       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1639         if (DemandedElts[InIdx/Ratio])
1640           InputDemandedElts.set(InIdx);
1641     }
1642     
1643     // div/rem demand all inputs, because they don't want divide by zero.
1644     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1645                                       UndefElts2, Depth+1);
1646     if (TmpV) {
1647       I->setOperand(0, TmpV);
1648       MadeChange = true;
1649     }
1650     
1651     UndefElts = UndefElts2;
1652     if (VWidth > InVWidth) {
1653       llvm_unreachable("Unimp");
1654       // If there are more elements in the result than there are in the source,
1655       // then an output element is undef if the corresponding input element is
1656       // undef.
1657       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1658         if (UndefElts2[OutIdx/Ratio])
1659           UndefElts.set(OutIdx);
1660     } else if (VWidth < InVWidth) {
1661       llvm_unreachable("Unimp");
1662       // If there are more elements in the source than there are in the result,
1663       // then a result element is undef if all of the corresponding input
1664       // elements are undef.
1665       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1666       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1667         if (!UndefElts2[InIdx])            // Not undef?
1668           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1669     }
1670     break;
1671   }
1672   case Instruction::And:
1673   case Instruction::Or:
1674   case Instruction::Xor:
1675   case Instruction::Add:
1676   case Instruction::Sub:
1677   case Instruction::Mul:
1678     // div/rem demand all inputs, because they don't want divide by zero.
1679     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1680                                       UndefElts, Depth+1);
1681     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1682     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1683                                       UndefElts2, Depth+1);
1684     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1685       
1686     // Output elements are undefined if both are undefined.  Consider things
1687     // like undef&0.  The result is known zero, not undef.
1688     UndefElts &= UndefElts2;
1689     break;
1690     
1691   case Instruction::Call: {
1692     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1693     if (!II) break;
1694     switch (II->getIntrinsicID()) {
1695     default: break;
1696       
1697     // Binary vector operations that work column-wise.  A dest element is a
1698     // function of the corresponding input elements from the two inputs.
1699     case Intrinsic::x86_sse_sub_ss:
1700     case Intrinsic::x86_sse_mul_ss:
1701     case Intrinsic::x86_sse_min_ss:
1702     case Intrinsic::x86_sse_max_ss:
1703     case Intrinsic::x86_sse2_sub_sd:
1704     case Intrinsic::x86_sse2_mul_sd:
1705     case Intrinsic::x86_sse2_min_sd:
1706     case Intrinsic::x86_sse2_max_sd:
1707       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1708                                         UndefElts, Depth+1);
1709       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1710       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1711                                         UndefElts2, Depth+1);
1712       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1713
1714       // If only the low elt is demanded and this is a scalarizable intrinsic,
1715       // scalarize it now.
1716       if (DemandedElts == 1) {
1717         switch (II->getIntrinsicID()) {
1718         default: break;
1719         case Intrinsic::x86_sse_sub_ss:
1720         case Intrinsic::x86_sse_mul_ss:
1721         case Intrinsic::x86_sse2_sub_sd:
1722         case Intrinsic::x86_sse2_mul_sd:
1723           // TODO: Lower MIN/MAX/ABS/etc
1724           Value *LHS = II->getOperand(1);
1725           Value *RHS = II->getOperand(2);
1726           // Extract the element as scalars.
1727           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1728             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1729           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1730             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1731           
1732           switch (II->getIntrinsicID()) {
1733           default: llvm_unreachable("Case stmts out of sync!");
1734           case Intrinsic::x86_sse_sub_ss:
1735           case Intrinsic::x86_sse2_sub_sd:
1736             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1737                                                         II->getName()), *II);
1738             break;
1739           case Intrinsic::x86_sse_mul_ss:
1740           case Intrinsic::x86_sse2_mul_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1742                                                          II->getName()), *II);
1743             break;
1744           }
1745           
1746           Instruction *New =
1747             InsertElementInst::Create(
1748               UndefValue::get(II->getType()), TmpV,
1749               ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
1750           InsertNewInstBefore(New, *II);
1751           AddSoonDeadInstToWorklist(*II, 0);
1752           return New;
1753         }            
1754       }
1755         
1756       // Output elements are undefined if both are undefined.  Consider things
1757       // like undef&0.  The result is known zero, not undef.
1758       UndefElts &= UndefElts2;
1759       break;
1760     }
1761     break;
1762   }
1763   }
1764   return MadeChange ? I : 0;
1765 }
1766
1767
1768 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1769 /// function is designed to check a chain of associative operators for a
1770 /// potential to apply a certain optimization.  Since the optimization may be
1771 /// applicable if the expression was reassociated, this checks the chain, then
1772 /// reassociates the expression as necessary to expose the optimization
1773 /// opportunity.  This makes use of a special Functor, which must define
1774 /// 'shouldApply' and 'apply' methods.
1775 ///
1776 template<typename Functor>
1777 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1778                                    LLVMContext *Context) {
1779   unsigned Opcode = Root.getOpcode();
1780   Value *LHS = Root.getOperand(0);
1781
1782   // Quick check, see if the immediate LHS matches...
1783   if (F.shouldApply(LHS))
1784     return F.apply(Root);
1785
1786   // Otherwise, if the LHS is not of the same opcode as the root, return.
1787   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1788   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1789     // Should we apply this transform to the RHS?
1790     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1791
1792     // If not to the RHS, check to see if we should apply to the LHS...
1793     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1794       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1795       ShouldApply = true;
1796     }
1797
1798     // If the functor wants to apply the optimization to the RHS of LHSI,
1799     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1800     if (ShouldApply) {
1801       // Now all of the instructions are in the current basic block, go ahead
1802       // and perform the reassociation.
1803       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1804
1805       // First move the selected RHS to the LHS of the root...
1806       Root.setOperand(0, LHSI->getOperand(1));
1807
1808       // Make what used to be the LHS of the root be the user of the root...
1809       Value *ExtraOperand = TmpLHSI->getOperand(1);
1810       if (&Root == TmpLHSI) {
1811         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1812         return 0;
1813       }
1814       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1815       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1816       BasicBlock::iterator ARI = &Root; ++ARI;
1817       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1818       ARI = Root;
1819
1820       // Now propagate the ExtraOperand down the chain of instructions until we
1821       // get to LHSI.
1822       while (TmpLHSI != LHSI) {
1823         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1824         // Move the instruction to immediately before the chain we are
1825         // constructing to avoid breaking dominance properties.
1826         NextLHSI->moveBefore(ARI);
1827         ARI = NextLHSI;
1828
1829         Value *NextOp = NextLHSI->getOperand(1);
1830         NextLHSI->setOperand(1, ExtraOperand);
1831         TmpLHSI = NextLHSI;
1832         ExtraOperand = NextOp;
1833       }
1834
1835       // Now that the instructions are reassociated, have the functor perform
1836       // the transformation...
1837       return F.apply(Root);
1838     }
1839
1840     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1841   }
1842   return 0;
1843 }
1844
1845 namespace {
1846
1847 // AddRHS - Implements: X + X --> X << 1
1848 struct AddRHS {
1849   Value *RHS;
1850   LLVMContext *Context;
1851   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1852   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1853   Instruction *apply(BinaryOperator &Add) const {
1854     return BinaryOperator::CreateShl(Add.getOperand(0),
1855                                      ConstantInt::get(Add.getType(), 1));
1856   }
1857 };
1858
1859 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1860 //                 iff C1&C2 == 0
1861 struct AddMaskingAnd {
1862   Constant *C2;
1863   LLVMContext *Context;
1864   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1865   bool shouldApply(Value *LHS) const {
1866     ConstantInt *C1;
1867     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1868            ConstantExpr::getAnd(C1, C2)->isNullValue();
1869   }
1870   Instruction *apply(BinaryOperator &Add) const {
1871     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1872   }
1873 };
1874
1875 }
1876
1877 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1878                                              InstCombiner *IC) {
1879   LLVMContext *Context = IC->getContext();
1880   
1881   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1882     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1883   }
1884
1885   // Figure out if the constant is the left or the right argument.
1886   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1887   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1888
1889   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1890     if (ConstIsRHS)
1891       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1892     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1893   }
1894
1895   Value *Op0 = SO, *Op1 = ConstOperand;
1896   if (!ConstIsRHS)
1897     std::swap(Op0, Op1);
1898   Instruction *New;
1899   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1900     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1901   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1902     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1903                           Op0, Op1, SO->getName()+".cmp");
1904   else {
1905     llvm_unreachable("Unknown binary instruction type!");
1906   }
1907   return IC->InsertNewInstBefore(New, I);
1908 }
1909
1910 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1911 // constant as the other operand, try to fold the binary operator into the
1912 // select arguments.  This also works for Cast instructions, which obviously do
1913 // not have a second operand.
1914 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1915                                      InstCombiner *IC) {
1916   // Don't modify shared select instructions
1917   if (!SI->hasOneUse()) return 0;
1918   Value *TV = SI->getOperand(1);
1919   Value *FV = SI->getOperand(2);
1920
1921   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1922     // Bool selects with constant operands can be folded to logical ops.
1923     if (SI->getType() == Type::Int1Ty) return 0;
1924
1925     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1926     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1927
1928     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1929                               SelectFalseVal);
1930   }
1931   return 0;
1932 }
1933
1934
1935 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1936 /// node as operand #0, see if we can fold the instruction into the PHI (which
1937 /// is only possible if all operands to the PHI are constants).
1938 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1939   PHINode *PN = cast<PHINode>(I.getOperand(0));
1940   unsigned NumPHIValues = PN->getNumIncomingValues();
1941   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1942
1943   // Check to see if all of the operands of the PHI are constants.  If there is
1944   // one non-constant value, remember the BB it is.  If there is more than one
1945   // or if *it* is a PHI, bail out.
1946   BasicBlock *NonConstBB = 0;
1947   for (unsigned i = 0; i != NumPHIValues; ++i)
1948     if (!isa<Constant>(PN->getIncomingValue(i))) {
1949       if (NonConstBB) return 0;  // More than one non-const value.
1950       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1951       NonConstBB = PN->getIncomingBlock(i);
1952       
1953       // If the incoming non-constant value is in I's block, we have an infinite
1954       // loop.
1955       if (NonConstBB == I.getParent())
1956         return 0;
1957     }
1958   
1959   // If there is exactly one non-constant value, we can insert a copy of the
1960   // operation in that block.  However, if this is a critical edge, we would be
1961   // inserting the computation one some other paths (e.g. inside a loop).  Only
1962   // do this if the pred block is unconditionally branching into the phi block.
1963   if (NonConstBB) {
1964     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1965     if (!BI || !BI->isUnconditional()) return 0;
1966   }
1967
1968   // Okay, we can do the transformation: create the new PHI node.
1969   PHINode *NewPN = PHINode::Create(I.getType(), "");
1970   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1971   InsertNewInstBefore(NewPN, *PN);
1972   NewPN->takeName(PN);
1973
1974   // Next, add all of the operands to the PHI.
1975   if (I.getNumOperands() == 2) {
1976     Constant *C = cast<Constant>(I.getOperand(1));
1977     for (unsigned i = 0; i != NumPHIValues; ++i) {
1978       Value *InV = 0;
1979       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1980         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1982         else
1983           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1984       } else {
1985         assert(PN->getIncomingBlock(i) == NonConstBB);
1986         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1987           InV = BinaryOperator::Create(BO->getOpcode(),
1988                                        PN->getIncomingValue(i), C, "phitmp",
1989                                        NonConstBB->getTerminator());
1990         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1991           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1992                                 CI->getPredicate(),
1993                                 PN->getIncomingValue(i), C, "phitmp",
1994                                 NonConstBB->getTerminator());
1995         else
1996           llvm_unreachable("Unknown binop!");
1997         
1998         AddToWorkList(cast<Instruction>(InV));
1999       }
2000       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2001     }
2002   } else { 
2003     CastInst *CI = cast<CastInst>(&I);
2004     const Type *RetTy = CI->getType();
2005     for (unsigned i = 0; i != NumPHIValues; ++i) {
2006       Value *InV;
2007       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2008         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2009       } else {
2010         assert(PN->getIncomingBlock(i) == NonConstBB);
2011         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2012                                I.getType(), "phitmp", 
2013                                NonConstBB->getTerminator());
2014         AddToWorkList(cast<Instruction>(InV));
2015       }
2016       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2017     }
2018   }
2019   return ReplaceInstUsesWith(I, NewPN);
2020 }
2021
2022
2023 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2024 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2025 /// This basically requires proving that the add in the original type would not
2026 /// overflow to change the sign bit or have a carry out.
2027 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2028   // There are different heuristics we can use for this.  Here are some simple
2029   // ones.
2030   
2031   // Add has the property that adding any two 2's complement numbers can only 
2032   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2033   // have at least two sign bits, we know that the addition of the two values will
2034   // sign extend fine.
2035   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2036     return true;
2037   
2038   
2039   // If one of the operands only has one non-zero bit, and if the other operand
2040   // has a known-zero bit in a more significant place than it (not including the
2041   // sign bit) the ripple may go up to and fill the zero, but won't change the
2042   // sign.  For example, (X & ~4) + 1.
2043   
2044   // TODO: Implement.
2045   
2046   return false;
2047 }
2048
2049
2050 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2051   bool Changed = SimplifyCommutative(I);
2052   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2053
2054   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2055     // X + undef -> undef
2056     if (isa<UndefValue>(RHS))
2057       return ReplaceInstUsesWith(I, RHS);
2058
2059     // X + 0 --> X
2060     if (RHSC->isNullValue())
2061       return ReplaceInstUsesWith(I, LHS);
2062
2063     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2064       // X + (signbit) --> X ^ signbit
2065       const APInt& Val = CI->getValue();
2066       uint32_t BitWidth = Val.getBitWidth();
2067       if (Val == APInt::getSignBit(BitWidth))
2068         return BinaryOperator::CreateXor(LHS, RHS);
2069       
2070       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2071       // (X & 254)+1 -> (X&254)|1
2072       if (SimplifyDemandedInstructionBits(I))
2073         return &I;
2074
2075       // zext(bool) + C -> bool ? C + 1 : C
2076       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2077         if (ZI->getSrcTy() == Type::Int1Ty)
2078           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2079     }
2080
2081     if (isa<PHINode>(LHS))
2082       if (Instruction *NV = FoldOpIntoPhi(I))
2083         return NV;
2084     
2085     ConstantInt *XorRHS = 0;
2086     Value *XorLHS = 0;
2087     if (isa<ConstantInt>(RHSC) &&
2088         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2089       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2090       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2091       
2092       uint32_t Size = TySizeBits / 2;
2093       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2094       APInt CFF80Val(-C0080Val);
2095       do {
2096         if (TySizeBits > Size) {
2097           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2098           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2099           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2100               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2101             // This is a sign extend if the top bits are known zero.
2102             if (!MaskedValueIsZero(XorLHS, 
2103                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2104               Size = 0;  // Not a sign ext, but can't be any others either.
2105             break;
2106           }
2107         }
2108         Size >>= 1;
2109         C0080Val = APIntOps::lshr(C0080Val, Size);
2110         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2111       } while (Size >= 1);
2112       
2113       // FIXME: This shouldn't be necessary. When the backends can handle types
2114       // with funny bit widths then this switch statement should be removed. It
2115       // is just here to get the size of the "middle" type back up to something
2116       // that the back ends can handle.
2117       const Type *MiddleType = 0;
2118       switch (Size) {
2119         default: break;
2120         case 32: MiddleType = Type::Int32Ty; break;
2121         case 16: MiddleType = Type::Int16Ty; break;
2122         case  8: MiddleType = Type::Int8Ty; break;
2123       }
2124       if (MiddleType) {
2125         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2126         InsertNewInstBefore(NewTrunc, I);
2127         return new SExtInst(NewTrunc, I.getType(), I.getName());
2128       }
2129     }
2130   }
2131
2132   if (I.getType() == Type::Int1Ty)
2133     return BinaryOperator::CreateXor(LHS, RHS);
2134
2135   // X + X --> X << 1
2136   if (I.getType()->isInteger()) {
2137     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2138       return Result;
2139
2140     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2141       if (RHSI->getOpcode() == Instruction::Sub)
2142         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2143           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2144     }
2145     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2146       if (LHSI->getOpcode() == Instruction::Sub)
2147         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2148           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2149     }
2150   }
2151
2152   // -A + B  -->  B - A
2153   // -A + -B  -->  -(A + B)
2154   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2155     if (LHS->getType()->isIntOrIntVector()) {
2156       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2157         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2158         InsertNewInstBefore(NewAdd, I);
2159         return BinaryOperator::CreateNeg(*Context, NewAdd);
2160       }
2161     }
2162     
2163     return BinaryOperator::CreateSub(RHS, LHSV);
2164   }
2165
2166   // A + -B  -->  A - B
2167   if (!isa<Constant>(RHS))
2168     if (Value *V = dyn_castNegVal(RHS, Context))
2169       return BinaryOperator::CreateSub(LHS, V);
2170
2171
2172   ConstantInt *C2;
2173   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2174     if (X == RHS)   // X*C + X --> X * (C+1)
2175       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2176
2177     // X*C1 + X*C2 --> X * (C1+C2)
2178     ConstantInt *C1;
2179     if (X == dyn_castFoldableMul(RHS, C1, Context))
2180       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2181   }
2182
2183   // X + X*C --> X * (C+1)
2184   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2185     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2186
2187   // X + ~X --> -1   since   ~X = -X-1
2188   if (dyn_castNotVal(LHS, Context) == RHS ||
2189       dyn_castNotVal(RHS, Context) == LHS)
2190     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2191   
2192
2193   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2194   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2195     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2196       return R;
2197   
2198   // A+B --> A|B iff A and B have no bits set in common.
2199   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2200     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2201     APInt LHSKnownOne(IT->getBitWidth(), 0);
2202     APInt LHSKnownZero(IT->getBitWidth(), 0);
2203     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2204     if (LHSKnownZero != 0) {
2205       APInt RHSKnownOne(IT->getBitWidth(), 0);
2206       APInt RHSKnownZero(IT->getBitWidth(), 0);
2207       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2208       
2209       // No bits in common -> bitwise or.
2210       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2211         return BinaryOperator::CreateOr(LHS, RHS);
2212     }
2213   }
2214
2215   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2216   if (I.getType()->isIntOrIntVector()) {
2217     Value *W, *X, *Y, *Z;
2218     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2219         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2220       if (W != Y) {
2221         if (W == Z) {
2222           std::swap(Y, Z);
2223         } else if (Y == X) {
2224           std::swap(W, X);
2225         } else if (X == Z) {
2226           std::swap(Y, Z);
2227           std::swap(W, X);
2228         }
2229       }
2230
2231       if (W == Y) {
2232         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2233                                                             LHS->getName()), I);
2234         return BinaryOperator::CreateMul(W, NewAdd);
2235       }
2236     }
2237   }
2238
2239   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2240     Value *X = 0;
2241     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2242       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2243
2244     // (X & FF00) + xx00  -> (X+xx00) & FF00
2245     if (LHS->hasOneUse() &&
2246         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2247       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2248       if (Anded == CRHS) {
2249         // See if all bits from the first bit set in the Add RHS up are included
2250         // in the mask.  First, get the rightmost bit.
2251         const APInt& AddRHSV = CRHS->getValue();
2252
2253         // Form a mask of all bits from the lowest bit added through the top.
2254         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2255
2256         // See if the and mask includes all of these bits.
2257         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2258
2259         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2260           // Okay, the xform is safe.  Insert the new add pronto.
2261           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2262                                                             LHS->getName()), I);
2263           return BinaryOperator::CreateAnd(NewAdd, C2);
2264         }
2265       }
2266     }
2267
2268     // Try to fold constant add into select arguments.
2269     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2270       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2271         return R;
2272   }
2273
2274   // add (select X 0 (sub n A)) A  -->  select X A n
2275   {
2276     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2277     Value *A = RHS;
2278     if (!SI) {
2279       SI = dyn_cast<SelectInst>(RHS);
2280       A = LHS;
2281     }
2282     if (SI && SI->hasOneUse()) {
2283       Value *TV = SI->getTrueValue();
2284       Value *FV = SI->getFalseValue();
2285       Value *N;
2286
2287       // Can we fold the add into the argument of the select?
2288       // We check both true and false select arguments for a matching subtract.
2289       if (match(FV, m_Zero(), *Context) &&
2290           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2291         // Fold the add into the true select value.
2292         return SelectInst::Create(SI->getCondition(), N, A);
2293       if (match(TV, m_Zero(), *Context) &&
2294           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2295         // Fold the add into the false select value.
2296         return SelectInst::Create(SI->getCondition(), A, N);
2297     }
2298   }
2299
2300   // Check for (add (sext x), y), see if we can merge this into an
2301   // integer add followed by a sext.
2302   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2303     // (add (sext x), cst) --> (sext (add x, cst'))
2304     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2305       Constant *CI = 
2306         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2307       if (LHSConv->hasOneUse() &&
2308           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2309           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2310         // Insert the new, smaller add.
2311         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2312                                                         CI, "addconv");
2313         InsertNewInstBefore(NewAdd, I);
2314         return new SExtInst(NewAdd, I.getType());
2315       }
2316     }
2317     
2318     // (add (sext x), (sext y)) --> (sext (add int x, y))
2319     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2320       // Only do this if x/y have the same type, if at last one of them has a
2321       // single use (so we don't increase the number of sexts), and if the
2322       // integer add will not overflow.
2323       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2324           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2325           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2326                                    RHSConv->getOperand(0))) {
2327         // Insert the new integer add.
2328         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2329                                                         RHSConv->getOperand(0),
2330                                                         "addconv");
2331         InsertNewInstBefore(NewAdd, I);
2332         return new SExtInst(NewAdd, I.getType());
2333       }
2334     }
2335   }
2336
2337   return Changed ? &I : 0;
2338 }
2339
2340 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2341   bool Changed = SimplifyCommutative(I);
2342   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2343
2344   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2345     // X + 0 --> X
2346     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2347       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2348                               (I.getType())->getValueAPF()))
2349         return ReplaceInstUsesWith(I, LHS);
2350     }
2351
2352     if (isa<PHINode>(LHS))
2353       if (Instruction *NV = FoldOpIntoPhi(I))
2354         return NV;
2355   }
2356
2357   // -A + B  -->  B - A
2358   // -A + -B  -->  -(A + B)
2359   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2360     return BinaryOperator::CreateFSub(RHS, LHSV);
2361
2362   // A + -B  -->  A - B
2363   if (!isa<Constant>(RHS))
2364     if (Value *V = dyn_castFNegVal(RHS, Context))
2365       return BinaryOperator::CreateFSub(LHS, V);
2366
2367   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2368   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2369     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2370       return ReplaceInstUsesWith(I, LHS);
2371
2372   // Check for (add double (sitofp x), y), see if we can merge this into an
2373   // integer add followed by a promotion.
2374   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2375     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2376     // ... if the constant fits in the integer value.  This is useful for things
2377     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2378     // requires a constant pool load, and generally allows the add to be better
2379     // instcombined.
2380     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2381       Constant *CI = 
2382       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2383       if (LHSConv->hasOneUse() &&
2384           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2385           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2386         // Insert the new integer add.
2387         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2388                                                         CI, "addconv");
2389         InsertNewInstBefore(NewAdd, I);
2390         return new SIToFPInst(NewAdd, I.getType());
2391       }
2392     }
2393     
2394     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2395     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2396       // Only do this if x/y have the same type, if at last one of them has a
2397       // single use (so we don't increase the number of int->fp conversions),
2398       // and if the integer add will not overflow.
2399       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2400           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2401           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2402                                    RHSConv->getOperand(0))) {
2403         // Insert the new integer add.
2404         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2405                                                         RHSConv->getOperand(0),
2406                                                         "addconv");
2407         InsertNewInstBefore(NewAdd, I);
2408         return new SIToFPInst(NewAdd, I.getType());
2409       }
2410     }
2411   }
2412   
2413   return Changed ? &I : 0;
2414 }
2415
2416 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2417   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2418
2419   if (Op0 == Op1)                        // sub X, X  -> 0
2420     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2421
2422   // If this is a 'B = x-(-A)', change to B = x+A...
2423   if (Value *V = dyn_castNegVal(Op1, Context))
2424     return BinaryOperator::CreateAdd(Op0, V);
2425
2426   if (isa<UndefValue>(Op0))
2427     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2428   if (isa<UndefValue>(Op1))
2429     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2430
2431   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2432     // Replace (-1 - A) with (~A)...
2433     if (C->isAllOnesValue())
2434       return BinaryOperator::CreateNot(*Context, Op1);
2435
2436     // C - ~X == X + (1+C)
2437     Value *X = 0;
2438     if (match(Op1, m_Not(m_Value(X)), *Context))
2439       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2440
2441     // -(X >>u 31) -> (X >>s 31)
2442     // -(X >>s 31) -> (X >>u 31)
2443     if (C->isZero()) {
2444       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2445         if (SI->getOpcode() == Instruction::LShr) {
2446           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2447             // Check to see if we are shifting out everything but the sign bit.
2448             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2449                 SI->getType()->getPrimitiveSizeInBits()-1) {
2450               // Ok, the transformation is safe.  Insert AShr.
2451               return BinaryOperator::Create(Instruction::AShr, 
2452                                           SI->getOperand(0), CU, SI->getName());
2453             }
2454           }
2455         }
2456         else if (SI->getOpcode() == Instruction::AShr) {
2457           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2458             // Check to see if we are shifting out everything but the sign bit.
2459             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2460                 SI->getType()->getPrimitiveSizeInBits()-1) {
2461               // Ok, the transformation is safe.  Insert LShr. 
2462               return BinaryOperator::CreateLShr(
2463                                           SI->getOperand(0), CU, SI->getName());
2464             }
2465           }
2466         }
2467       }
2468     }
2469
2470     // Try to fold constant sub into select arguments.
2471     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2472       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2473         return R;
2474
2475     // C - zext(bool) -> bool ? C - 1 : C
2476     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2477       if (ZI->getSrcTy() == Type::Int1Ty)
2478         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2479   }
2480
2481   if (I.getType() == Type::Int1Ty)
2482     return BinaryOperator::CreateXor(Op0, Op1);
2483
2484   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2485     if (Op1I->getOpcode() == Instruction::Add) {
2486       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2487         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2488                                          I.getName());
2489       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2490         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2491                                          I.getName());
2492       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2493         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2494           // C1-(X+C2) --> (C1-C2)-X
2495           return BinaryOperator::CreateSub(
2496             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2497       }
2498     }
2499
2500     if (Op1I->hasOneUse()) {
2501       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2502       // is not used by anyone else...
2503       //
2504       if (Op1I->getOpcode() == Instruction::Sub) {
2505         // Swap the two operands of the subexpr...
2506         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2507         Op1I->setOperand(0, IIOp1);
2508         Op1I->setOperand(1, IIOp0);
2509
2510         // Create the new top level add instruction...
2511         return BinaryOperator::CreateAdd(Op0, Op1);
2512       }
2513
2514       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2515       //
2516       if (Op1I->getOpcode() == Instruction::And &&
2517           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2518         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2519
2520         Value *NewNot =
2521           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2522                                                         OtherOp, "B.not"), I);
2523         return BinaryOperator::CreateAnd(Op0, NewNot);
2524       }
2525
2526       // 0 - (X sdiv C)  -> (X sdiv -C)
2527       if (Op1I->getOpcode() == Instruction::SDiv)
2528         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2529           if (CSI->isZero())
2530             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2531               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2532                                           ConstantExpr::getNeg(DivRHS));
2533
2534       // X - X*C --> X * (1-C)
2535       ConstantInt *C2 = 0;
2536       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2537         Constant *CP1 = 
2538           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2539                                              C2);
2540         return BinaryOperator::CreateMul(Op0, CP1);
2541       }
2542     }
2543   }
2544
2545   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2546     if (Op0I->getOpcode() == Instruction::Add) {
2547       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2548         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2549       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2550         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2551     } else if (Op0I->getOpcode() == Instruction::Sub) {
2552       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2553         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2554                                          I.getName());
2555     }
2556   }
2557
2558   ConstantInt *C1;
2559   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2560     if (X == Op1)  // X*C - X --> X * (C-1)
2561       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2562
2563     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2564     if (X == dyn_castFoldableMul(Op1, C2, Context))
2565       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2566   }
2567   return 0;
2568 }
2569
2570 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2571   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2572
2573   // If this is a 'B = x-(-A)', change to B = x+A...
2574   if (Value *V = dyn_castFNegVal(Op1, Context))
2575     return BinaryOperator::CreateFAdd(Op0, V);
2576
2577   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2578     if (Op1I->getOpcode() == Instruction::FAdd) {
2579       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2580         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2581                                           I.getName());
2582       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2583         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2584                                           I.getName());
2585     }
2586   }
2587
2588   return 0;
2589 }
2590
2591 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2592 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2593 /// TrueIfSigned if the result of the comparison is true when the input value is
2594 /// signed.
2595 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2596                            bool &TrueIfSigned) {
2597   switch (pred) {
2598   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2599     TrueIfSigned = true;
2600     return RHS->isZero();
2601   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2602     TrueIfSigned = true;
2603     return RHS->isAllOnesValue();
2604   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2605     TrueIfSigned = false;
2606     return RHS->isAllOnesValue();
2607   case ICmpInst::ICMP_UGT:
2608     // True if LHS u> RHS and RHS == high-bit-mask - 1
2609     TrueIfSigned = true;
2610     return RHS->getValue() ==
2611       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2612   case ICmpInst::ICMP_UGE: 
2613     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2614     TrueIfSigned = true;
2615     return RHS->getValue().isSignBit();
2616   default:
2617     return false;
2618   }
2619 }
2620
2621 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2622   bool Changed = SimplifyCommutative(I);
2623   Value *Op0 = I.getOperand(0);
2624
2625   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2626     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2627
2628   // Simplify mul instructions with a constant RHS...
2629   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2630     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2631
2632       // ((X << C1)*C2) == (X * (C2 << C1))
2633       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2634         if (SI->getOpcode() == Instruction::Shl)
2635           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2636             return BinaryOperator::CreateMul(SI->getOperand(0),
2637                                         ConstantExpr::getShl(CI, ShOp));
2638
2639       if (CI->isZero())
2640         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2641       if (CI->equalsInt(1))                  // X * 1  == X
2642         return ReplaceInstUsesWith(I, Op0);
2643       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2644         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2645
2646       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2647       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2648         return BinaryOperator::CreateShl(Op0,
2649                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2650       }
2651     } else if (isa<VectorType>(Op1->getType())) {
2652       if (Op1->isNullValue())
2653         return ReplaceInstUsesWith(I, Op1);
2654
2655       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2656         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2657           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2658
2659         // As above, vector X*splat(1.0) -> X in all defined cases.
2660         if (Constant *Splat = Op1V->getSplatValue()) {
2661           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2662             if (CI->equalsInt(1))
2663               return ReplaceInstUsesWith(I, Op0);
2664         }
2665       }
2666     }
2667     
2668     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2669       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2670           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2671         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2672         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2673                                                      Op1, "tmp");
2674         InsertNewInstBefore(Add, I);
2675         Value *C1C2 = ConstantExpr::getMul(Op1, 
2676                                            cast<Constant>(Op0I->getOperand(1)));
2677         return BinaryOperator::CreateAdd(Add, C1C2);
2678         
2679       }
2680
2681     // Try to fold constant mul into select arguments.
2682     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2683       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2684         return R;
2685
2686     if (isa<PHINode>(Op0))
2687       if (Instruction *NV = FoldOpIntoPhi(I))
2688         return NV;
2689   }
2690
2691   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2692     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2693       return BinaryOperator::CreateMul(Op0v, Op1v);
2694
2695   // (X / Y) *  Y = X - (X % Y)
2696   // (X / Y) * -Y = (X % Y) - X
2697   {
2698     Value *Op1 = I.getOperand(1);
2699     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2700     if (!BO ||
2701         (BO->getOpcode() != Instruction::UDiv && 
2702          BO->getOpcode() != Instruction::SDiv)) {
2703       Op1 = Op0;
2704       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2705     }
2706     Value *Neg = dyn_castNegVal(Op1, Context);
2707     if (BO && BO->hasOneUse() &&
2708         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2709         (BO->getOpcode() == Instruction::UDiv ||
2710          BO->getOpcode() == Instruction::SDiv)) {
2711       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2712
2713       Instruction *Rem;
2714       if (BO->getOpcode() == Instruction::UDiv)
2715         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2716       else
2717         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2718
2719       InsertNewInstBefore(Rem, I);
2720       Rem->takeName(BO);
2721
2722       if (Op1BO == Op1)
2723         return BinaryOperator::CreateSub(Op0BO, Rem);
2724       else
2725         return BinaryOperator::CreateSub(Rem, Op0BO);
2726     }
2727   }
2728
2729   if (I.getType() == Type::Int1Ty)
2730     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2731
2732   // If one of the operands of the multiply is a cast from a boolean value, then
2733   // we know the bool is either zero or one, so this is a 'masking' multiply.
2734   // See if we can simplify things based on how the boolean was originally
2735   // formed.
2736   CastInst *BoolCast = 0;
2737   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2738     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2739       BoolCast = CI;
2740   if (!BoolCast)
2741     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2742       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2743         BoolCast = CI;
2744   if (BoolCast) {
2745     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2746       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2747       const Type *SCOpTy = SCIOp0->getType();
2748       bool TIS = false;
2749       
2750       // If the icmp is true iff the sign bit of X is set, then convert this
2751       // multiply into a shift/and combination.
2752       if (isa<ConstantInt>(SCIOp1) &&
2753           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2754           TIS) {
2755         // Shift the X value right to turn it into "all signbits".
2756         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2757                                           SCOpTy->getPrimitiveSizeInBits()-1);
2758         Value *V =
2759           InsertNewInstBefore(
2760             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2761                                             BoolCast->getOperand(0)->getName()+
2762                                             ".mask"), I);
2763
2764         // If the multiply type is not the same as the source type, sign extend
2765         // or truncate to the multiply type.
2766         if (I.getType() != V->getType()) {
2767           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2768           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2769           Instruction::CastOps opcode = 
2770             (SrcBits == DstBits ? Instruction::BitCast : 
2771              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2772           V = InsertCastBefore(opcode, V, I.getType(), I);
2773         }
2774
2775         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2776         return BinaryOperator::CreateAnd(V, OtherOp);
2777       }
2778     }
2779   }
2780
2781   return Changed ? &I : 0;
2782 }
2783
2784 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2785   bool Changed = SimplifyCommutative(I);
2786   Value *Op0 = I.getOperand(0);
2787
2788   // Simplify mul instructions with a constant RHS...
2789   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2790     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2791       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2792       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2793       if (Op1F->isExactlyValue(1.0))
2794         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2795     } else if (isa<VectorType>(Op1->getType())) {
2796       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2797         // As above, vector X*splat(1.0) -> X in all defined cases.
2798         if (Constant *Splat = Op1V->getSplatValue()) {
2799           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2800             if (F->isExactlyValue(1.0))
2801               return ReplaceInstUsesWith(I, Op0);
2802         }
2803       }
2804     }
2805
2806     // Try to fold constant mul into select arguments.
2807     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2808       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2809         return R;
2810
2811     if (isa<PHINode>(Op0))
2812       if (Instruction *NV = FoldOpIntoPhi(I))
2813         return NV;
2814   }
2815
2816   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2817     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2818       return BinaryOperator::CreateFMul(Op0v, Op1v);
2819
2820   return Changed ? &I : 0;
2821 }
2822
2823 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2824 /// instruction.
2825 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2826   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2827   
2828   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2829   int NonNullOperand = -1;
2830   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2831     if (ST->isNullValue())
2832       NonNullOperand = 2;
2833   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2834   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2835     if (ST->isNullValue())
2836       NonNullOperand = 1;
2837   
2838   if (NonNullOperand == -1)
2839     return false;
2840   
2841   Value *SelectCond = SI->getOperand(0);
2842   
2843   // Change the div/rem to use 'Y' instead of the select.
2844   I.setOperand(1, SI->getOperand(NonNullOperand));
2845   
2846   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2847   // problem.  However, the select, or the condition of the select may have
2848   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2849   // propagate the known value for the select into other uses of it, and
2850   // propagate a known value of the condition into its other users.
2851   
2852   // If the select and condition only have a single use, don't bother with this,
2853   // early exit.
2854   if (SI->use_empty() && SelectCond->hasOneUse())
2855     return true;
2856   
2857   // Scan the current block backward, looking for other uses of SI.
2858   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2859   
2860   while (BBI != BBFront) {
2861     --BBI;
2862     // If we found a call to a function, we can't assume it will return, so
2863     // information from below it cannot be propagated above it.
2864     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2865       break;
2866     
2867     // Replace uses of the select or its condition with the known values.
2868     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2869          I != E; ++I) {
2870       if (*I == SI) {
2871         *I = SI->getOperand(NonNullOperand);
2872         AddToWorkList(BBI);
2873       } else if (*I == SelectCond) {
2874         *I = NonNullOperand == 1 ? Context->getTrue() :
2875                                    Context->getFalse();
2876         AddToWorkList(BBI);
2877       }
2878     }
2879     
2880     // If we past the instruction, quit looking for it.
2881     if (&*BBI == SI)
2882       SI = 0;
2883     if (&*BBI == SelectCond)
2884       SelectCond = 0;
2885     
2886     // If we ran out of things to eliminate, break out of the loop.
2887     if (SelectCond == 0 && SI == 0)
2888       break;
2889     
2890   }
2891   return true;
2892 }
2893
2894
2895 /// This function implements the transforms on div instructions that work
2896 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2897 /// used by the visitors to those instructions.
2898 /// @brief Transforms common to all three div instructions
2899 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2900   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2901
2902   // undef / X -> 0        for integer.
2903   // undef / X -> undef    for FP (the undef could be a snan).
2904   if (isa<UndefValue>(Op0)) {
2905     if (Op0->getType()->isFPOrFPVector())
2906       return ReplaceInstUsesWith(I, Op0);
2907     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2908   }
2909
2910   // X / undef -> undef
2911   if (isa<UndefValue>(Op1))
2912     return ReplaceInstUsesWith(I, Op1);
2913
2914   return 0;
2915 }
2916
2917 /// This function implements the transforms common to both integer division
2918 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2919 /// division instructions.
2920 /// @brief Common integer divide transforms
2921 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2922   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2923
2924   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2925   if (Op0 == Op1) {
2926     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2927       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2928       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2929       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2930     }
2931
2932     Constant *CI = ConstantInt::get(I.getType(), 1);
2933     return ReplaceInstUsesWith(I, CI);
2934   }
2935   
2936   if (Instruction *Common = commonDivTransforms(I))
2937     return Common;
2938   
2939   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2940   // This does not apply for fdiv.
2941   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2942     return &I;
2943
2944   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2945     // div X, 1 == X
2946     if (RHS->equalsInt(1))
2947       return ReplaceInstUsesWith(I, Op0);
2948
2949     // (X / C1) / C2  -> X / (C1*C2)
2950     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2951       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2952         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2953           if (MultiplyOverflows(RHS, LHSRHS,
2954                                 I.getOpcode()==Instruction::SDiv, Context))
2955             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2956           else 
2957             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2958                                       ConstantExpr::getMul(RHS, LHSRHS));
2959         }
2960
2961     if (!RHS->isZero()) { // avoid X udiv 0
2962       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2963         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2964           return R;
2965       if (isa<PHINode>(Op0))
2966         if (Instruction *NV = FoldOpIntoPhi(I))
2967           return NV;
2968     }
2969   }
2970
2971   // 0 / X == 0, we don't need to preserve faults!
2972   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2973     if (LHS->equalsInt(0))
2974       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2975
2976   // It can't be division by zero, hence it must be division by one.
2977   if (I.getType() == Type::Int1Ty)
2978     return ReplaceInstUsesWith(I, Op0);
2979
2980   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2981     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2982       // div X, 1 == X
2983       if (X->isOne())
2984         return ReplaceInstUsesWith(I, Op0);
2985   }
2986
2987   return 0;
2988 }
2989
2990 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2991   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2992
2993   // Handle the integer div common cases
2994   if (Instruction *Common = commonIDivTransforms(I))
2995     return Common;
2996
2997   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2998     // X udiv C^2 -> X >> C
2999     // Check to see if this is an unsigned division with an exact power of 2,
3000     // if so, convert to a right shift.
3001     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3002       return BinaryOperator::CreateLShr(Op0, 
3003             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3004
3005     // X udiv C, where C >= signbit
3006     if (C->getValue().isNegative()) {
3007       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3008                                                     ICmpInst::ICMP_ULT, Op0, C),
3009                                       I);
3010       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3011                                 ConstantInt::get(I.getType(), 1));
3012     }
3013   }
3014
3015   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3016   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3017     if (RHSI->getOpcode() == Instruction::Shl &&
3018         isa<ConstantInt>(RHSI->getOperand(0))) {
3019       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3020       if (C1.isPowerOf2()) {
3021         Value *N = RHSI->getOperand(1);
3022         const Type *NTy = N->getType();
3023         if (uint32_t C2 = C1.logBase2()) {
3024           Constant *C2V = ConstantInt::get(NTy, C2);
3025           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3026         }
3027         return BinaryOperator::CreateLShr(Op0, N);
3028       }
3029     }
3030   }
3031   
3032   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3033   // where C1&C2 are powers of two.
3034   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3035     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3036       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3037         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3038         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3039           // Compute the shift amounts
3040           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3041           // Construct the "on true" case of the select
3042           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3043           Instruction *TSI = BinaryOperator::CreateLShr(
3044                                                  Op0, TC, SI->getName()+".t");
3045           TSI = InsertNewInstBefore(TSI, I);
3046   
3047           // Construct the "on false" case of the select
3048           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3049           Instruction *FSI = BinaryOperator::CreateLShr(
3050                                                  Op0, FC, SI->getName()+".f");
3051           FSI = InsertNewInstBefore(FSI, I);
3052
3053           // construct the select instruction and return it.
3054           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3055         }
3056       }
3057   return 0;
3058 }
3059
3060 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3061   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3062
3063   // Handle the integer div common cases
3064   if (Instruction *Common = commonIDivTransforms(I))
3065     return Common;
3066
3067   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3068     // sdiv X, -1 == -X
3069     if (RHS->isAllOnesValue())
3070       return BinaryOperator::CreateNeg(*Context, Op0);
3071   }
3072
3073   // If the sign bits of both operands are zero (i.e. we can prove they are
3074   // unsigned inputs), turn this into a udiv.
3075   if (I.getType()->isInteger()) {
3076     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3077     if (MaskedValueIsZero(Op0, Mask)) {
3078       if (MaskedValueIsZero(Op1, Mask)) {
3079         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3080         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3081       }
3082       ConstantInt *ShiftedInt;
3083       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3084           ShiftedInt->getValue().isPowerOf2()) {
3085         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3086         // Safe because the only negative value (1 << Y) can take on is
3087         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3088         // the sign bit set.
3089         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3090       }
3091     }
3092   }
3093   
3094   return 0;
3095 }
3096
3097 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3098   return commonDivTransforms(I);
3099 }
3100
3101 /// This function implements the transforms on rem instructions that work
3102 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3103 /// is used by the visitors to those instructions.
3104 /// @brief Transforms common to all three rem instructions
3105 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3106   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3107
3108   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3109     if (I.getType()->isFPOrFPVector())
3110       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3111     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3112   }
3113   if (isa<UndefValue>(Op1))
3114     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3115
3116   // Handle cases involving: rem X, (select Cond, Y, Z)
3117   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3118     return &I;
3119
3120   return 0;
3121 }
3122
3123 /// This function implements the transforms common to both integer remainder
3124 /// instructions (urem and srem). It is called by the visitors to those integer
3125 /// remainder instructions.
3126 /// @brief Common integer remainder transforms
3127 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3128   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3129
3130   if (Instruction *common = commonRemTransforms(I))
3131     return common;
3132
3133   // 0 % X == 0 for integer, we don't need to preserve faults!
3134   if (Constant *LHS = dyn_cast<Constant>(Op0))
3135     if (LHS->isNullValue())
3136       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3137
3138   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3139     // X % 0 == undef, we don't need to preserve faults!
3140     if (RHS->equalsInt(0))
3141       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3142     
3143     if (RHS->equalsInt(1))  // X % 1 == 0
3144       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3145
3146     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3147       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3148         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3149           return R;
3150       } else if (isa<PHINode>(Op0I)) {
3151         if (Instruction *NV = FoldOpIntoPhi(I))
3152           return NV;
3153       }
3154
3155       // See if we can fold away this rem instruction.
3156       if (SimplifyDemandedInstructionBits(I))
3157         return &I;
3158     }
3159   }
3160
3161   return 0;
3162 }
3163
3164 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3165   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
3167   if (Instruction *common = commonIRemTransforms(I))
3168     return common;
3169   
3170   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3171     // X urem C^2 -> X and C
3172     // Check to see if this is an unsigned remainder with an exact power of 2,
3173     // if so, convert to a bitwise and.
3174     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3175       if (C->getValue().isPowerOf2())
3176         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3177   }
3178
3179   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3180     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3181     if (RHSI->getOpcode() == Instruction::Shl &&
3182         isa<ConstantInt>(RHSI->getOperand(0))) {
3183       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3184         Constant *N1 = Context->getAllOnesValue(I.getType());
3185         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3186                                                                    "tmp"), I);
3187         return BinaryOperator::CreateAnd(Op0, Add);
3188       }
3189     }
3190   }
3191
3192   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3193   // where C1&C2 are powers of two.
3194   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3195     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3196       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3197         // STO == 0 and SFO == 0 handled above.
3198         if ((STO->getValue().isPowerOf2()) && 
3199             (SFO->getValue().isPowerOf2())) {
3200           Value *TrueAnd = InsertNewInstBefore(
3201             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3202                                       SI->getName()+".t"), I);
3203           Value *FalseAnd = InsertNewInstBefore(
3204             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3205                                       SI->getName()+".f"), I);
3206           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3207         }
3208       }
3209   }
3210   
3211   return 0;
3212 }
3213
3214 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3215   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3216
3217   // Handle the integer rem common cases
3218   if (Instruction *common = commonIRemTransforms(I))
3219     return common;
3220   
3221   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3222     if (!isa<Constant>(RHSNeg) ||
3223         (isa<ConstantInt>(RHSNeg) &&
3224          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3225       // X % -Y -> X % Y
3226       AddUsesToWorkList(I);
3227       I.setOperand(1, RHSNeg);
3228       return &I;
3229     }
3230
3231   // If the sign bits of both operands are zero (i.e. we can prove they are
3232   // unsigned inputs), turn this into a urem.
3233   if (I.getType()->isInteger()) {
3234     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3235     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3236       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3237       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3238     }
3239   }
3240
3241   // If it's a constant vector, flip any negative values positive.
3242   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3243     unsigned VWidth = RHSV->getNumOperands();
3244
3245     bool hasNegative = false;
3246     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3247       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3248         if (RHS->getValue().isNegative())
3249           hasNegative = true;
3250
3251     if (hasNegative) {
3252       std::vector<Constant *> Elts(VWidth);
3253       for (unsigned i = 0; i != VWidth; ++i) {
3254         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3255           if (RHS->getValue().isNegative())
3256             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3257           else
3258             Elts[i] = RHS;
3259         }
3260       }
3261
3262       Constant *NewRHSV = ConstantVector::get(Elts);
3263       if (NewRHSV != RHSV) {
3264         AddUsesToWorkList(I);
3265         I.setOperand(1, NewRHSV);
3266         return &I;
3267       }
3268     }
3269   }
3270
3271   return 0;
3272 }
3273
3274 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3275   return commonRemTransforms(I);
3276 }
3277
3278 // isOneBitSet - Return true if there is exactly one bit set in the specified
3279 // constant.
3280 static bool isOneBitSet(const ConstantInt *CI) {
3281   return CI->getValue().isPowerOf2();
3282 }
3283
3284 // isHighOnes - Return true if the constant is of the form 1+0+.
3285 // This is the same as lowones(~X).
3286 static bool isHighOnes(const ConstantInt *CI) {
3287   return (~CI->getValue() + 1).isPowerOf2();
3288 }
3289
3290 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3291 /// are carefully arranged to allow folding of expressions such as:
3292 ///
3293 ///      (A < B) | (A > B) --> (A != B)
3294 ///
3295 /// Note that this is only valid if the first and second predicates have the
3296 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3297 ///
3298 /// Three bits are used to represent the condition, as follows:
3299 ///   0  A > B
3300 ///   1  A == B
3301 ///   2  A < B
3302 ///
3303 /// <=>  Value  Definition
3304 /// 000     0   Always false
3305 /// 001     1   A >  B
3306 /// 010     2   A == B
3307 /// 011     3   A >= B
3308 /// 100     4   A <  B
3309 /// 101     5   A != B
3310 /// 110     6   A <= B
3311 /// 111     7   Always true
3312 ///  
3313 static unsigned getICmpCode(const ICmpInst *ICI) {
3314   switch (ICI->getPredicate()) {
3315     // False -> 0
3316   case ICmpInst::ICMP_UGT: return 1;  // 001
3317   case ICmpInst::ICMP_SGT: return 1;  // 001
3318   case ICmpInst::ICMP_EQ:  return 2;  // 010
3319   case ICmpInst::ICMP_UGE: return 3;  // 011
3320   case ICmpInst::ICMP_SGE: return 3;  // 011
3321   case ICmpInst::ICMP_ULT: return 4;  // 100
3322   case ICmpInst::ICMP_SLT: return 4;  // 100
3323   case ICmpInst::ICMP_NE:  return 5;  // 101
3324   case ICmpInst::ICMP_ULE: return 6;  // 110
3325   case ICmpInst::ICMP_SLE: return 6;  // 110
3326     // True -> 7
3327   default:
3328     llvm_unreachable("Invalid ICmp predicate!");
3329     return 0;
3330   }
3331 }
3332
3333 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3334 /// predicate into a three bit mask. It also returns whether it is an ordered
3335 /// predicate by reference.
3336 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3337   isOrdered = false;
3338   switch (CC) {
3339   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3340   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3341   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3342   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3343   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3344   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3345   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3346   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3347   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3348   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3349   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3350   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3351   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3352   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3353     // True -> 7
3354   default:
3355     // Not expecting FCMP_FALSE and FCMP_TRUE;
3356     llvm_unreachable("Unexpected FCmp predicate!");
3357     return 0;
3358   }
3359 }
3360
3361 /// getICmpValue - This is the complement of getICmpCode, which turns an
3362 /// opcode and two operands into either a constant true or false, or a brand 
3363 /// new ICmp instruction. The sign is passed in to determine which kind
3364 /// of predicate to use in the new icmp instruction.
3365 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3366                            LLVMContext *Context) {
3367   switch (code) {
3368   default: llvm_unreachable("Illegal ICmp code!");
3369   case  0: return Context->getFalse();
3370   case  1: 
3371     if (sign)
3372       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3373     else
3374       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3375   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3376   case  3: 
3377     if (sign)
3378       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3379     else
3380       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3381   case  4: 
3382     if (sign)
3383       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3384     else
3385       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3386   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3387   case  6: 
3388     if (sign)
3389       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3390     else
3391       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3392   case  7: return Context->getTrue();
3393   }
3394 }
3395
3396 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3397 /// opcode and two operands into either a FCmp instruction. isordered is passed
3398 /// in to determine which kind of predicate to use in the new fcmp instruction.
3399 static Value *getFCmpValue(bool isordered, unsigned code,
3400                            Value *LHS, Value *RHS, LLVMContext *Context) {
3401   switch (code) {
3402   default: llvm_unreachable("Illegal FCmp code!");
3403   case  0:
3404     if (isordered)
3405       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3406     else
3407       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3408   case  1: 
3409     if (isordered)
3410       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3411     else
3412       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3413   case  2: 
3414     if (isordered)
3415       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3416     else
3417       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3418   case  3: 
3419     if (isordered)
3420       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3421     else
3422       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3423   case  4: 
3424     if (isordered)
3425       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3426     else
3427       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3428   case  5: 
3429     if (isordered)
3430       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3431     else
3432       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3433   case  6: 
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3438   case  7: return Context->getTrue();
3439   }
3440 }
3441
3442 /// PredicatesFoldable - Return true if both predicates match sign or if at
3443 /// least one of them is an equality comparison (which is signless).
3444 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3445   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3446          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3447          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3448 }
3449
3450 namespace { 
3451 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3452 struct FoldICmpLogical {
3453   InstCombiner &IC;
3454   Value *LHS, *RHS;
3455   ICmpInst::Predicate pred;
3456   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3457     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3458       pred(ICI->getPredicate()) {}
3459   bool shouldApply(Value *V) const {
3460     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3461       if (PredicatesFoldable(pred, ICI->getPredicate()))
3462         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3463                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3464     return false;
3465   }
3466   Instruction *apply(Instruction &Log) const {
3467     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3468     if (ICI->getOperand(0) != LHS) {
3469       assert(ICI->getOperand(1) == LHS);
3470       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3471     }
3472
3473     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3474     unsigned LHSCode = getICmpCode(ICI);
3475     unsigned RHSCode = getICmpCode(RHSICI);
3476     unsigned Code;
3477     switch (Log.getOpcode()) {
3478     case Instruction::And: Code = LHSCode & RHSCode; break;
3479     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3480     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3481     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3482     }
3483
3484     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3485                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3486       
3487     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3488     if (Instruction *I = dyn_cast<Instruction>(RV))
3489       return I;
3490     // Otherwise, it's a constant boolean value...
3491     return IC.ReplaceInstUsesWith(Log, RV);
3492   }
3493 };
3494 } // end anonymous namespace
3495
3496 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3497 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3498 // guaranteed to be a binary operator.
3499 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3500                                     ConstantInt *OpRHS,
3501                                     ConstantInt *AndRHS,
3502                                     BinaryOperator &TheAnd) {
3503   Value *X = Op->getOperand(0);
3504   Constant *Together = 0;
3505   if (!Op->isShift())
3506     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3507
3508   switch (Op->getOpcode()) {
3509   case Instruction::Xor:
3510     if (Op->hasOneUse()) {
3511       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3512       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3513       InsertNewInstBefore(And, TheAnd);
3514       And->takeName(Op);
3515       return BinaryOperator::CreateXor(And, Together);
3516     }
3517     break;
3518   case Instruction::Or:
3519     if (Together == AndRHS) // (X | C) & C --> C
3520       return ReplaceInstUsesWith(TheAnd, AndRHS);
3521
3522     if (Op->hasOneUse() && Together != OpRHS) {
3523       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3524       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3525       InsertNewInstBefore(Or, TheAnd);
3526       Or->takeName(Op);
3527       return BinaryOperator::CreateAnd(Or, AndRHS);
3528     }
3529     break;
3530   case Instruction::Add:
3531     if (Op->hasOneUse()) {
3532       // Adding a one to a single bit bit-field should be turned into an XOR
3533       // of the bit.  First thing to check is to see if this AND is with a
3534       // single bit constant.
3535       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3536
3537       // If there is only one bit set...
3538       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3539         // Ok, at this point, we know that we are masking the result of the
3540         // ADD down to exactly one bit.  If the constant we are adding has
3541         // no bits set below this bit, then we can eliminate the ADD.
3542         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3543
3544         // Check to see if any bits below the one bit set in AndRHSV are set.
3545         if ((AddRHS & (AndRHSV-1)) == 0) {
3546           // If not, the only thing that can effect the output of the AND is
3547           // the bit specified by AndRHSV.  If that bit is set, the effect of
3548           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3549           // no effect.
3550           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3551             TheAnd.setOperand(0, X);
3552             return &TheAnd;
3553           } else {
3554             // Pull the XOR out of the AND.
3555             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3556             InsertNewInstBefore(NewAnd, TheAnd);
3557             NewAnd->takeName(Op);
3558             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3559           }
3560         }
3561       }
3562     }
3563     break;
3564
3565   case Instruction::Shl: {
3566     // We know that the AND will not produce any of the bits shifted in, so if
3567     // the anded constant includes them, clear them now!
3568     //
3569     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3570     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3571     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3572     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3573
3574     if (CI->getValue() == ShlMask) { 
3575     // Masking out bits that the shift already masks
3576       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3577     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3578       TheAnd.setOperand(1, CI);
3579       return &TheAnd;
3580     }
3581     break;
3582   }
3583   case Instruction::LShr:
3584   {
3585     // We know that the AND will not produce any of the bits shifted in, so if
3586     // the anded constant includes them, clear them now!  This only applies to
3587     // unsigned shifts, because a signed shr may bring in set bits!
3588     //
3589     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3590     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3591     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3592     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3593
3594     if (CI->getValue() == ShrMask) {   
3595     // Masking out bits that the shift already masks.
3596       return ReplaceInstUsesWith(TheAnd, Op);
3597     } else if (CI != AndRHS) {
3598       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3599       return &TheAnd;
3600     }
3601     break;
3602   }
3603   case Instruction::AShr:
3604     // Signed shr.
3605     // See if this is shifting in some sign extension, then masking it out
3606     // with an and.
3607     if (Op->hasOneUse()) {
3608       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3611       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3612       if (C == AndRHS) {          // Masking out bits shifted in.
3613         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3614         // Make the argument unsigned.
3615         Value *ShVal = Op->getOperand(0);
3616         ShVal = InsertNewInstBefore(
3617             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3618                                    Op->getName()), TheAnd);
3619         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3620       }
3621     }
3622     break;
3623   }
3624   return 0;
3625 }
3626
3627
3628 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3629 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3630 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3631 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3632 /// insert new instructions.
3633 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3634                                            bool isSigned, bool Inside, 
3635                                            Instruction &IB) {
3636   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3637             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3638          "Lo is not <= Hi in range emission code!");
3639     
3640   if (Inside) {
3641     if (Lo == Hi)  // Trivially false.
3642       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3643
3644     // V >= Min && V < Hi --> V < Hi
3645     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3646       ICmpInst::Predicate pred = (isSigned ? 
3647         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3648       return new ICmpInst(*Context, pred, V, Hi);
3649     }
3650
3651     // Emit V-Lo <u Hi-Lo
3652     Constant *NegLo = ConstantExpr::getNeg(Lo);
3653     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3654     InsertNewInstBefore(Add, IB);
3655     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3656     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3657   }
3658
3659   if (Lo == Hi)  // Trivially true.
3660     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3661
3662   // V < Min || V >= Hi -> V > Hi-1
3663   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3664   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3665     ICmpInst::Predicate pred = (isSigned ? 
3666         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3667     return new ICmpInst(*Context, pred, V, Hi);
3668   }
3669
3670   // Emit V-Lo >u Hi-1-Lo
3671   // Note that Hi has already had one subtracted from it, above.
3672   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3673   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3674   InsertNewInstBefore(Add, IB);
3675   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3676   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3677 }
3678
3679 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3680 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3681 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3682 // not, since all 1s are not contiguous.
3683 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3684   const APInt& V = Val->getValue();
3685   uint32_t BitWidth = Val->getType()->getBitWidth();
3686   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3687
3688   // look for the first zero bit after the run of ones
3689   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3690   // look for the first non-zero bit
3691   ME = V.getActiveBits(); 
3692   return true;
3693 }
3694
3695 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3696 /// where isSub determines whether the operator is a sub.  If we can fold one of
3697 /// the following xforms:
3698 /// 
3699 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3700 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3702 ///
3703 /// return (A +/- B).
3704 ///
3705 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3706                                         ConstantInt *Mask, bool isSub,
3707                                         Instruction &I) {
3708   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3709   if (!LHSI || LHSI->getNumOperands() != 2 ||
3710       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3711
3712   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3713
3714   switch (LHSI->getOpcode()) {
3715   default: return 0;
3716   case Instruction::And:
3717     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3718       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3719       if ((Mask->getValue().countLeadingZeros() + 
3720            Mask->getValue().countPopulation()) == 
3721           Mask->getValue().getBitWidth())
3722         break;
3723
3724       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3725       // part, we don't need any explicit masks to take them out of A.  If that
3726       // is all N is, ignore it.
3727       uint32_t MB = 0, ME = 0;
3728       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3729         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3730         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3731         if (MaskedValueIsZero(RHS, Mask))
3732           break;
3733       }
3734     }
3735     return 0;
3736   case Instruction::Or:
3737   case Instruction::Xor:
3738     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3739     if ((Mask->getValue().countLeadingZeros() + 
3740          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3741         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3742       break;
3743     return 0;
3744   }
3745   
3746   Instruction *New;
3747   if (isSub)
3748     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3749   else
3750     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3751   return InsertNewInstBefore(New, I);
3752 }
3753
3754 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3755 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3756                                           ICmpInst *LHS, ICmpInst *RHS) {
3757   Value *Val, *Val2;
3758   ConstantInt *LHSCst, *RHSCst;
3759   ICmpInst::Predicate LHSCC, RHSCC;
3760   
3761   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3762   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3763                          m_ConstantInt(LHSCst)), *Context) ||
3764       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3765                          m_ConstantInt(RHSCst)), *Context))
3766     return 0;
3767   
3768   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3769   // where C is a power of 2
3770   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3771       LHSCst->getValue().isPowerOf2()) {
3772     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3773     InsertNewInstBefore(NewOr, I);
3774     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3775   }
3776   
3777   // From here on, we only handle:
3778   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3779   if (Val != Val2) return 0;
3780   
3781   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3782   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3783       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3784       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3785       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3786     return 0;
3787   
3788   // We can't fold (ugt x, C) & (sgt x, C2).
3789   if (!PredicatesFoldable(LHSCC, RHSCC))
3790     return 0;
3791     
3792   // Ensure that the larger constant is on the RHS.
3793   bool ShouldSwap;
3794   if (ICmpInst::isSignedPredicate(LHSCC) ||
3795       (ICmpInst::isEquality(LHSCC) && 
3796        ICmpInst::isSignedPredicate(RHSCC)))
3797     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3798   else
3799     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3800     
3801   if (ShouldSwap) {
3802     std::swap(LHS, RHS);
3803     std::swap(LHSCst, RHSCst);
3804     std::swap(LHSCC, RHSCC);
3805   }
3806
3807   // At this point, we know we have have two icmp instructions
3808   // comparing a value against two constants and and'ing the result
3809   // together.  Because of the above check, we know that we only have
3810   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3811   // (from the FoldICmpLogical check above), that the two constants 
3812   // are not equal and that the larger constant is on the RHS
3813   assert(LHSCst != RHSCst && "Compares not folded above?");
3814
3815   switch (LHSCC) {
3816   default: llvm_unreachable("Unknown integer condition code!");
3817   case ICmpInst::ICMP_EQ:
3818     switch (RHSCC) {
3819     default: llvm_unreachable("Unknown integer condition code!");
3820     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3821     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3822     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3823       return ReplaceInstUsesWith(I, Context->getFalse());
3824     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3825     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3826     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3827       return ReplaceInstUsesWith(I, LHS);
3828     }
3829   case ICmpInst::ICMP_NE:
3830     switch (RHSCC) {
3831     default: llvm_unreachable("Unknown integer condition code!");
3832     case ICmpInst::ICMP_ULT:
3833       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3834         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3835       break;                        // (X != 13 & X u< 15) -> no change
3836     case ICmpInst::ICMP_SLT:
3837       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3838         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3839       break;                        // (X != 13 & X s< 15) -> no change
3840     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3841     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3842     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3843       return ReplaceInstUsesWith(I, RHS);
3844     case ICmpInst::ICMP_NE:
3845       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3846         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3847         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3848                                                      Val->getName()+".off");
3849         InsertNewInstBefore(Add, I);
3850         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3851                             ConstantInt::get(Add->getType(), 1));
3852       }
3853       break;                        // (X != 13 & X != 15) -> no change
3854     }
3855     break;
3856   case ICmpInst::ICMP_ULT:
3857     switch (RHSCC) {
3858     default: llvm_unreachable("Unknown integer condition code!");
3859     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3860     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3861       return ReplaceInstUsesWith(I, Context->getFalse());
3862     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3863       break;
3864     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3865     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3866       return ReplaceInstUsesWith(I, LHS);
3867     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3868       break;
3869     }
3870     break;
3871   case ICmpInst::ICMP_SLT:
3872     switch (RHSCC) {
3873     default: llvm_unreachable("Unknown integer condition code!");
3874     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3875     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3876       return ReplaceInstUsesWith(I, Context->getFalse());
3877     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3878       break;
3879     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3880     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3881       return ReplaceInstUsesWith(I, LHS);
3882     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3883       break;
3884     }
3885     break;
3886   case ICmpInst::ICMP_UGT:
3887     switch (RHSCC) {
3888     default: llvm_unreachable("Unknown integer condition code!");
3889     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3890     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3891       return ReplaceInstUsesWith(I, RHS);
3892     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3893       break;
3894     case ICmpInst::ICMP_NE:
3895       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3896         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3897       break;                        // (X u> 13 & X != 15) -> no change
3898     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3899       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3900                              RHSCst, false, true, I);
3901     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3902       break;
3903     }
3904     break;
3905   case ICmpInst::ICMP_SGT:
3906     switch (RHSCC) {
3907     default: llvm_unreachable("Unknown integer condition code!");
3908     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3909     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3910       return ReplaceInstUsesWith(I, RHS);
3911     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3912       break;
3913     case ICmpInst::ICMP_NE:
3914       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3915         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3916       break;                        // (X s> 13 & X != 15) -> no change
3917     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3918       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3919                              RHSCst, true, true, I);
3920     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3921       break;
3922     }
3923     break;
3924   }
3925  
3926   return 0;
3927 }
3928
3929 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3930                                           FCmpInst *RHS) {
3931   
3932   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3933       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3934     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3935     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3936       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3937         // If either of the constants are nans, then the whole thing returns
3938         // false.
3939         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3940           return ReplaceInstUsesWith(I, Context->getFalse());
3941         return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3942                             LHS->getOperand(0), RHS->getOperand(0));
3943       }
3944     
3945     // Handle vector zeros.  This occurs because the canonical form of
3946     // "fcmp ord x,x" is "fcmp ord x, 0".
3947     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3948         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3949       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3950                           LHS->getOperand(0), RHS->getOperand(0));
3951     return 0;
3952   }
3953   
3954   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3955   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3956   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3957   
3958   
3959   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3960     // Swap RHS operands to match LHS.
3961     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3962     std::swap(Op1LHS, Op1RHS);
3963   }
3964   
3965   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3966     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3967     if (Op0CC == Op1CC)
3968       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3969     
3970     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3971       return ReplaceInstUsesWith(I, Context->getFalse());
3972     if (Op0CC == FCmpInst::FCMP_TRUE)
3973       return ReplaceInstUsesWith(I, RHS);
3974     if (Op1CC == FCmpInst::FCMP_TRUE)
3975       return ReplaceInstUsesWith(I, LHS);
3976     
3977     bool Op0Ordered;
3978     bool Op1Ordered;
3979     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3980     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3981     if (Op1Pred == 0) {
3982       std::swap(LHS, RHS);
3983       std::swap(Op0Pred, Op1Pred);
3984       std::swap(Op0Ordered, Op1Ordered);
3985     }
3986     if (Op0Pred == 0) {
3987       // uno && ueq -> uno && (uno || eq) -> ueq
3988       // ord && olt -> ord && (ord && lt) -> olt
3989       if (Op0Ordered == Op1Ordered)
3990         return ReplaceInstUsesWith(I, RHS);
3991       
3992       // uno && oeq -> uno && (ord && eq) -> false
3993       // uno && ord -> false
3994       if (!Op0Ordered)
3995         return ReplaceInstUsesWith(I, Context->getFalse());
3996       // ord && ueq -> ord && (uno || eq) -> oeq
3997       return cast<Instruction>(getFCmpValue(true, Op1Pred,
3998                                             Op0LHS, Op0RHS, Context));
3999     }
4000   }
4001
4002   return 0;
4003 }
4004
4005
4006 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4007   bool Changed = SimplifyCommutative(I);
4008   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4009
4010   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4011     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4012
4013   // and X, X = X
4014   if (Op0 == Op1)
4015     return ReplaceInstUsesWith(I, Op1);
4016
4017   // See if we can simplify any instructions used by the instruction whose sole 
4018   // purpose is to compute bits we don't care about.
4019   if (SimplifyDemandedInstructionBits(I))
4020     return &I;
4021   if (isa<VectorType>(I.getType())) {
4022     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4023       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4024         return ReplaceInstUsesWith(I, I.getOperand(0));
4025     } else if (isa<ConstantAggregateZero>(Op1)) {
4026       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4027     }
4028   }
4029
4030   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4031     const APInt& AndRHSMask = AndRHS->getValue();
4032     APInt NotAndRHS(~AndRHSMask);
4033
4034     // Optimize a variety of ((val OP C1) & C2) combinations...
4035     if (isa<BinaryOperator>(Op0)) {
4036       Instruction *Op0I = cast<Instruction>(Op0);
4037       Value *Op0LHS = Op0I->getOperand(0);
4038       Value *Op0RHS = Op0I->getOperand(1);
4039       switch (Op0I->getOpcode()) {
4040       case Instruction::Xor:
4041       case Instruction::Or:
4042         // If the mask is only needed on one incoming arm, push it up.
4043         if (Op0I->hasOneUse()) {
4044           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4045             // Not masking anything out for the LHS, move to RHS.
4046             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4047                                                    Op0RHS->getName()+".masked");
4048             InsertNewInstBefore(NewRHS, I);
4049             return BinaryOperator::Create(
4050                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4051           }
4052           if (!isa<Constant>(Op0RHS) &&
4053               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4054             // Not masking anything out for the RHS, move to LHS.
4055             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4056                                                    Op0LHS->getName()+".masked");
4057             InsertNewInstBefore(NewLHS, I);
4058             return BinaryOperator::Create(
4059                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4060           }
4061         }
4062
4063         break;
4064       case Instruction::Add:
4065         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4066         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4067         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4068         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4069           return BinaryOperator::CreateAnd(V, AndRHS);
4070         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4071           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4072         break;
4073
4074       case Instruction::Sub:
4075         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4076         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4077         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4078         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4079           return BinaryOperator::CreateAnd(V, AndRHS);
4080
4081         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4082         // has 1's for all bits that the subtraction with A might affect.
4083         if (Op0I->hasOneUse()) {
4084           uint32_t BitWidth = AndRHSMask.getBitWidth();
4085           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4086           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4087
4088           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4089           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4090               MaskedValueIsZero(Op0LHS, Mask)) {
4091             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4092             InsertNewInstBefore(NewNeg, I);
4093             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4094           }
4095         }
4096         break;
4097
4098       case Instruction::Shl:
4099       case Instruction::LShr:
4100         // (1 << x) & 1 --> zext(x == 0)
4101         // (1 >> x) & 1 --> zext(x == 0)
4102         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4103           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4104                                     Op0RHS, Context->getNullValue(I.getType()));
4105           InsertNewInstBefore(NewICmp, I);
4106           return new ZExtInst(NewICmp, I.getType());
4107         }
4108         break;
4109       }
4110
4111       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4112         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4113           return Res;
4114     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4115       // If this is an integer truncation or change from signed-to-unsigned, and
4116       // if the source is an and/or with immediate, transform it.  This
4117       // frequently occurs for bitfield accesses.
4118       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4119         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4120             CastOp->getNumOperands() == 2)
4121           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4122             if (CastOp->getOpcode() == Instruction::And) {
4123               // Change: and (cast (and X, C1) to T), C2
4124               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4125               // This will fold the two constants together, which may allow 
4126               // other simplifications.
4127               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4128                 CastOp->getOperand(0), I.getType(), 
4129                 CastOp->getName()+".shrunk");
4130               NewCast = InsertNewInstBefore(NewCast, I);
4131               // trunc_or_bitcast(C1)&C2
4132               Constant *C3 =
4133                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4134               C3 = ConstantExpr::getAnd(C3, AndRHS);
4135               return BinaryOperator::CreateAnd(NewCast, C3);
4136             } else if (CastOp->getOpcode() == Instruction::Or) {
4137               // Change: and (cast (or X, C1) to T), C2
4138               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4139               Constant *C3 =
4140                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4141               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4142                 // trunc(C1)&C2
4143                 return ReplaceInstUsesWith(I, AndRHS);
4144             }
4145           }
4146       }
4147     }
4148
4149     // Try to fold constant and into select arguments.
4150     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4151       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4152         return R;
4153     if (isa<PHINode>(Op0))
4154       if (Instruction *NV = FoldOpIntoPhi(I))
4155         return NV;
4156   }
4157
4158   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4159   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4160
4161   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4162     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4163
4164   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4165   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4166     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4167                                                I.getName()+".demorgan");
4168     InsertNewInstBefore(Or, I);
4169     return BinaryOperator::CreateNot(*Context, Or);
4170   }
4171   
4172   {
4173     Value *A = 0, *B = 0, *C = 0, *D = 0;
4174     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4175       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4176         return ReplaceInstUsesWith(I, Op1);
4177     
4178       // (A|B) & ~(A&B) -> A^B
4179       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4180         if ((A == C && B == D) || (A == D && B == C))
4181           return BinaryOperator::CreateXor(A, B);
4182       }
4183     }
4184     
4185     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4186       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4187         return ReplaceInstUsesWith(I, Op0);
4188
4189       // ~(A&B) & (A|B) -> A^B
4190       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4191         if ((A == C && B == D) || (A == D && B == C))
4192           return BinaryOperator::CreateXor(A, B);
4193       }
4194     }
4195     
4196     if (Op0->hasOneUse() &&
4197         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4198       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4199         I.swapOperands();     // Simplify below
4200         std::swap(Op0, Op1);
4201       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4202         cast<BinaryOperator>(Op0)->swapOperands();
4203         I.swapOperands();     // Simplify below
4204         std::swap(Op0, Op1);
4205       }
4206     }
4207
4208     if (Op1->hasOneUse() &&
4209         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4210       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4211         cast<BinaryOperator>(Op1)->swapOperands();
4212         std::swap(A, B);
4213       }
4214       if (A == Op0) {                                // A&(A^B) -> A & ~B
4215         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4216         InsertNewInstBefore(NotB, I);
4217         return BinaryOperator::CreateAnd(A, NotB);
4218       }
4219     }
4220
4221     // (A&((~A)|B)) -> A&B
4222     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4223         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4224       return BinaryOperator::CreateAnd(A, Op1);
4225     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4226         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4227       return BinaryOperator::CreateAnd(A, Op0);
4228   }
4229   
4230   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4231     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4232     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4233       return R;
4234
4235     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4236       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4237         return Res;
4238   }
4239
4240   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4241   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4242     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4244         const Type *SrcTy = Op0C->getOperand(0)->getType();
4245         if (SrcTy == Op1C->getOperand(0)->getType() &&
4246             SrcTy->isIntOrIntVector() &&
4247             // Only do this if the casts both really cause code to be generated.
4248             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4249                               I.getType(), TD) &&
4250             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4251                               I.getType(), TD)) {
4252           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4253                                                          Op1C->getOperand(0),
4254                                                          I.getName());
4255           InsertNewInstBefore(NewOp, I);
4256           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4257         }
4258       }
4259     
4260   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4261   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4262     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4263       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4264           SI0->getOperand(1) == SI1->getOperand(1) &&
4265           (SI0->hasOneUse() || SI1->hasOneUse())) {
4266         Instruction *NewOp =
4267           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4268                                                         SI1->getOperand(0),
4269                                                         SI0->getName()), I);
4270         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4271                                       SI1->getOperand(1));
4272       }
4273   }
4274
4275   // If and'ing two fcmp, try combine them into one.
4276   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4277     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4278       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4279         return Res;
4280   }
4281
4282   return Changed ? &I : 0;
4283 }
4284
4285 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4286 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4287 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4288 /// the expression came from the corresponding "byte swapped" byte in some other
4289 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4290 /// we know that the expression deposits the low byte of %X into the high byte
4291 /// of the bswap result and that all other bytes are zero.  This expression is
4292 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4293 /// match.
4294 ///
4295 /// This function returns true if the match was unsuccessful and false if so.
4296 /// On entry to the function the "OverallLeftShift" is a signed integer value
4297 /// indicating the number of bytes that the subexpression is later shifted.  For
4298 /// example, if the expression is later right shifted by 16 bits, the
4299 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4300 /// byte of ByteValues is actually being set.
4301 ///
4302 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4303 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4304 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4305 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4306 /// always in the local (OverallLeftShift) coordinate space.
4307 ///
4308 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4309                               SmallVector<Value*, 8> &ByteValues) {
4310   if (Instruction *I = dyn_cast<Instruction>(V)) {
4311     // If this is an or instruction, it may be an inner node of the bswap.
4312     if (I->getOpcode() == Instruction::Or) {
4313       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4314                                ByteValues) ||
4315              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4316                                ByteValues);
4317     }
4318   
4319     // If this is a logical shift by a constant multiple of 8, recurse with
4320     // OverallLeftShift and ByteMask adjusted.
4321     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4322       unsigned ShAmt = 
4323         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4324       // Ensure the shift amount is defined and of a byte value.
4325       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4326         return true;
4327
4328       unsigned ByteShift = ShAmt >> 3;
4329       if (I->getOpcode() == Instruction::Shl) {
4330         // X << 2 -> collect(X, +2)
4331         OverallLeftShift += ByteShift;
4332         ByteMask >>= ByteShift;
4333       } else {
4334         // X >>u 2 -> collect(X, -2)
4335         OverallLeftShift -= ByteShift;
4336         ByteMask <<= ByteShift;
4337         ByteMask &= (~0U >> (32-ByteValues.size()));
4338       }
4339
4340       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4341       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4342
4343       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4344                                ByteValues);
4345     }
4346
4347     // If this is a logical 'and' with a mask that clears bytes, clear the
4348     // corresponding bytes in ByteMask.
4349     if (I->getOpcode() == Instruction::And &&
4350         isa<ConstantInt>(I->getOperand(1))) {
4351       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4352       unsigned NumBytes = ByteValues.size();
4353       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4354       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4355       
4356       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4357         // If this byte is masked out by a later operation, we don't care what
4358         // the and mask is.
4359         if ((ByteMask & (1 << i)) == 0)
4360           continue;
4361         
4362         // If the AndMask is all zeros for this byte, clear the bit.
4363         APInt MaskB = AndMask & Byte;
4364         if (MaskB == 0) {
4365           ByteMask &= ~(1U << i);
4366           continue;
4367         }
4368         
4369         // If the AndMask is not all ones for this byte, it's not a bytezap.
4370         if (MaskB != Byte)
4371           return true;
4372
4373         // Otherwise, this byte is kept.
4374       }
4375
4376       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4377                                ByteValues);
4378     }
4379   }
4380   
4381   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4382   // the input value to the bswap.  Some observations: 1) if more than one byte
4383   // is demanded from this input, then it could not be successfully assembled
4384   // into a byteswap.  At least one of the two bytes would not be aligned with
4385   // their ultimate destination.
4386   if (!isPowerOf2_32(ByteMask)) return true;
4387   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4388   
4389   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4390   // is demanded, it needs to go into byte 0 of the result.  This means that the
4391   // byte needs to be shifted until it lands in the right byte bucket.  The
4392   // shift amount depends on the position: if the byte is coming from the high
4393   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4394   // low part, it must be shifted left.
4395   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4396   if (InputByteNo < ByteValues.size()/2) {
4397     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4398       return true;
4399   } else {
4400     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4401       return true;
4402   }
4403   
4404   // If the destination byte value is already defined, the values are or'd
4405   // together, which isn't a bswap (unless it's an or of the same bits).
4406   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4407     return true;
4408   ByteValues[DestByteNo] = V;
4409   return false;
4410 }
4411
4412 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4413 /// If so, insert the new bswap intrinsic and return it.
4414 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4415   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4416   if (!ITy || ITy->getBitWidth() % 16 || 
4417       // ByteMask only allows up to 32-byte values.
4418       ITy->getBitWidth() > 32*8) 
4419     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4420   
4421   /// ByteValues - For each byte of the result, we keep track of which value
4422   /// defines each byte.
4423   SmallVector<Value*, 8> ByteValues;
4424   ByteValues.resize(ITy->getBitWidth()/8);
4425     
4426   // Try to find all the pieces corresponding to the bswap.
4427   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4428   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4429     return 0;
4430   
4431   // Check to see if all of the bytes come from the same value.
4432   Value *V = ByteValues[0];
4433   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4434   
4435   // Check to make sure that all of the bytes come from the same value.
4436   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4437     if (ByteValues[i] != V)
4438       return 0;
4439   const Type *Tys[] = { ITy };
4440   Module *M = I.getParent()->getParent()->getParent();
4441   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4442   return CallInst::Create(F, V);
4443 }
4444
4445 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4446 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4447 /// we can simplify this expression to "cond ? C : D or B".
4448 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4449                                          Value *C, Value *D,
4450                                          LLVMContext *Context) {
4451   // If A is not a select of -1/0, this cannot match.
4452   Value *Cond = 0;
4453   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4454     return 0;
4455
4456   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4457   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4458     return SelectInst::Create(Cond, C, B);
4459   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4460     return SelectInst::Create(Cond, C, B);
4461   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4462   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4463     return SelectInst::Create(Cond, C, D);
4464   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4465     return SelectInst::Create(Cond, C, D);
4466   return 0;
4467 }
4468
4469 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4470 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4471                                          ICmpInst *LHS, ICmpInst *RHS) {
4472   Value *Val, *Val2;
4473   ConstantInt *LHSCst, *RHSCst;
4474   ICmpInst::Predicate LHSCC, RHSCC;
4475   
4476   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4477   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4478              m_ConstantInt(LHSCst)), *Context) ||
4479       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4480              m_ConstantInt(RHSCst)), *Context))
4481     return 0;
4482   
4483   // From here on, we only handle:
4484   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4485   if (Val != Val2) return 0;
4486   
4487   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4488   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4489       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4490       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4491       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4492     return 0;
4493   
4494   // We can't fold (ugt x, C) | (sgt x, C2).
4495   if (!PredicatesFoldable(LHSCC, RHSCC))
4496     return 0;
4497   
4498   // Ensure that the larger constant is on the RHS.
4499   bool ShouldSwap;
4500   if (ICmpInst::isSignedPredicate(LHSCC) ||
4501       (ICmpInst::isEquality(LHSCC) && 
4502        ICmpInst::isSignedPredicate(RHSCC)))
4503     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4504   else
4505     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4506   
4507   if (ShouldSwap) {
4508     std::swap(LHS, RHS);
4509     std::swap(LHSCst, RHSCst);
4510     std::swap(LHSCC, RHSCC);
4511   }
4512   
4513   // At this point, we know we have have two icmp instructions
4514   // comparing a value against two constants and or'ing the result
4515   // together.  Because of the above check, we know that we only have
4516   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4517   // FoldICmpLogical check above), that the two constants are not
4518   // equal.
4519   assert(LHSCst != RHSCst && "Compares not folded above?");
4520
4521   switch (LHSCC) {
4522   default: llvm_unreachable("Unknown integer condition code!");
4523   case ICmpInst::ICMP_EQ:
4524     switch (RHSCC) {
4525     default: llvm_unreachable("Unknown integer condition code!");
4526     case ICmpInst::ICMP_EQ:
4527       if (LHSCst == SubOne(RHSCst, Context)) {
4528         // (X == 13 | X == 14) -> X-13 <u 2
4529         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4530         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4531                                                      Val->getName()+".off");
4532         InsertNewInstBefore(Add, I);
4533         AddCST = ConstantExpr::getSub(AddOne(RHSCst, Context), LHSCst);
4534         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4535       }
4536       break;                         // (X == 13 | X == 15) -> no change
4537     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4538     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4539       break;
4540     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4541     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4542     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4543       return ReplaceInstUsesWith(I, RHS);
4544     }
4545     break;
4546   case ICmpInst::ICMP_NE:
4547     switch (RHSCC) {
4548     default: llvm_unreachable("Unknown integer condition code!");
4549     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4550     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4551     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4552       return ReplaceInstUsesWith(I, LHS);
4553     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4554     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4555     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4556       return ReplaceInstUsesWith(I, Context->getTrue());
4557     }
4558     break;
4559   case ICmpInst::ICMP_ULT:
4560     switch (RHSCC) {
4561     default: llvm_unreachable("Unknown integer condition code!");
4562     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4563       break;
4564     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4565       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4566       // this can cause overflow.
4567       if (RHSCst->isMaxValue(false))
4568         return ReplaceInstUsesWith(I, LHS);
4569       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4570                              false, false, I);
4571     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4572       break;
4573     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4574     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4575       return ReplaceInstUsesWith(I, RHS);
4576     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4577       break;
4578     }
4579     break;
4580   case ICmpInst::ICMP_SLT:
4581     switch (RHSCC) {
4582     default: llvm_unreachable("Unknown integer condition code!");
4583     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4584       break;
4585     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4586       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4587       // this can cause overflow.
4588       if (RHSCst->isMaxValue(true))
4589         return ReplaceInstUsesWith(I, LHS);
4590       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4591                              true, false, I);
4592     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4593       break;
4594     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4595     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4596       return ReplaceInstUsesWith(I, RHS);
4597     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4598       break;
4599     }
4600     break;
4601   case ICmpInst::ICMP_UGT:
4602     switch (RHSCC) {
4603     default: llvm_unreachable("Unknown integer condition code!");
4604     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4605     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4606       return ReplaceInstUsesWith(I, LHS);
4607     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4608       break;
4609     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4610     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4611       return ReplaceInstUsesWith(I, Context->getTrue());
4612     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4613       break;
4614     }
4615     break;
4616   case ICmpInst::ICMP_SGT:
4617     switch (RHSCC) {
4618     default: llvm_unreachable("Unknown integer condition code!");
4619     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4620     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4621       return ReplaceInstUsesWith(I, LHS);
4622     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4623       break;
4624     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4625     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4626       return ReplaceInstUsesWith(I, Context->getTrue());
4627     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4628       break;
4629     }
4630     break;
4631   }
4632   return 0;
4633 }
4634
4635 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4636                                          FCmpInst *RHS) {
4637   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4638       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4639       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4640     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4641       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4642         // If either of the constants are nans, then the whole thing returns
4643         // true.
4644         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4645           return ReplaceInstUsesWith(I, Context->getTrue());
4646         
4647         // Otherwise, no need to compare the two constants, compare the
4648         // rest.
4649         return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4650                             LHS->getOperand(0), RHS->getOperand(0));
4651       }
4652     
4653     // Handle vector zeros.  This occurs because the canonical form of
4654     // "fcmp uno x,x" is "fcmp uno x, 0".
4655     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4656         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4657       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4658                           LHS->getOperand(0), RHS->getOperand(0));
4659     
4660     return 0;
4661   }
4662   
4663   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4664   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4665   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4666   
4667   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4668     // Swap RHS operands to match LHS.
4669     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4670     std::swap(Op1LHS, Op1RHS);
4671   }
4672   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4673     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4674     if (Op0CC == Op1CC)
4675       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4676                           Op0LHS, Op0RHS);
4677     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4678       return ReplaceInstUsesWith(I, Context->getTrue());
4679     if (Op0CC == FCmpInst::FCMP_FALSE)
4680       return ReplaceInstUsesWith(I, RHS);
4681     if (Op1CC == FCmpInst::FCMP_FALSE)
4682       return ReplaceInstUsesWith(I, LHS);
4683     bool Op0Ordered;
4684     bool Op1Ordered;
4685     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4686     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4687     if (Op0Ordered == Op1Ordered) {
4688       // If both are ordered or unordered, return a new fcmp with
4689       // or'ed predicates.
4690       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4691                                Op0LHS, Op0RHS, Context);
4692       if (Instruction *I = dyn_cast<Instruction>(RV))
4693         return I;
4694       // Otherwise, it's a constant boolean value...
4695       return ReplaceInstUsesWith(I, RV);
4696     }
4697   }
4698   return 0;
4699 }
4700
4701 /// FoldOrWithConstants - This helper function folds:
4702 ///
4703 ///     ((A | B) & C1) | (B & C2)
4704 ///
4705 /// into:
4706 /// 
4707 ///     (A & C1) | B
4708 ///
4709 /// when the XOR of the two constants is "all ones" (-1).
4710 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4711                                                Value *A, Value *B, Value *C) {
4712   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4713   if (!CI1) return 0;
4714
4715   Value *V1 = 0;
4716   ConstantInt *CI2 = 0;
4717   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4718
4719   APInt Xor = CI1->getValue() ^ CI2->getValue();
4720   if (!Xor.isAllOnesValue()) return 0;
4721
4722   if (V1 == A || V1 == B) {
4723     Instruction *NewOp =
4724       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4725     return BinaryOperator::CreateOr(NewOp, V1);
4726   }
4727
4728   return 0;
4729 }
4730
4731 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4732   bool Changed = SimplifyCommutative(I);
4733   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4734
4735   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4736     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4737
4738   // or X, X = X
4739   if (Op0 == Op1)
4740     return ReplaceInstUsesWith(I, Op0);
4741
4742   // See if we can simplify any instructions used by the instruction whose sole 
4743   // purpose is to compute bits we don't care about.
4744   if (SimplifyDemandedInstructionBits(I))
4745     return &I;
4746   if (isa<VectorType>(I.getType())) {
4747     if (isa<ConstantAggregateZero>(Op1)) {
4748       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4749     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4750       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4751         return ReplaceInstUsesWith(I, I.getOperand(1));
4752     }
4753   }
4754
4755   // or X, -1 == -1
4756   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4757     ConstantInt *C1 = 0; Value *X = 0;
4758     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4759     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4760         isOnlyUse(Op0)) {
4761       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4762       InsertNewInstBefore(Or, I);
4763       Or->takeName(Op0);
4764       return BinaryOperator::CreateAnd(Or, 
4765                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4766     }
4767
4768     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4769     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4770         isOnlyUse(Op0)) {
4771       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4772       InsertNewInstBefore(Or, I);
4773       Or->takeName(Op0);
4774       return BinaryOperator::CreateXor(Or,
4775                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4776     }
4777
4778     // Try to fold constant and into select arguments.
4779     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4780       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4781         return R;
4782     if (isa<PHINode>(Op0))
4783       if (Instruction *NV = FoldOpIntoPhi(I))
4784         return NV;
4785   }
4786
4787   Value *A = 0, *B = 0;
4788   ConstantInt *C1 = 0, *C2 = 0;
4789
4790   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4791     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4792       return ReplaceInstUsesWith(I, Op1);
4793   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4794     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4795       return ReplaceInstUsesWith(I, Op0);
4796
4797   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4798   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4799   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4800       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4801       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4802        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4803     if (Instruction *BSwap = MatchBSwap(I))
4804       return BSwap;
4805   }
4806   
4807   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4808   if (Op0->hasOneUse() &&
4809       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4810       MaskedValueIsZero(Op1, C1->getValue())) {
4811     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4812     InsertNewInstBefore(NOr, I);
4813     NOr->takeName(Op0);
4814     return BinaryOperator::CreateXor(NOr, C1);
4815   }
4816
4817   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4818   if (Op1->hasOneUse() &&
4819       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4820       MaskedValueIsZero(Op0, C1->getValue())) {
4821     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4822     InsertNewInstBefore(NOr, I);
4823     NOr->takeName(Op0);
4824     return BinaryOperator::CreateXor(NOr, C1);
4825   }
4826
4827   // (A & C)|(B & D)
4828   Value *C = 0, *D = 0;
4829   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4830       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4831     Value *V1 = 0, *V2 = 0, *V3 = 0;
4832     C1 = dyn_cast<ConstantInt>(C);
4833     C2 = dyn_cast<ConstantInt>(D);
4834     if (C1 && C2) {  // (A & C1)|(B & C2)
4835       // If we have: ((V + N) & C1) | (V & C2)
4836       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4837       // replace with V+N.
4838       if (C1->getValue() == ~C2->getValue()) {
4839         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4840             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4841           // Add commutes, try both ways.
4842           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4843             return ReplaceInstUsesWith(I, A);
4844           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4845             return ReplaceInstUsesWith(I, A);
4846         }
4847         // Or commutes, try both ways.
4848         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4849             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4850           // Add commutes, try both ways.
4851           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4852             return ReplaceInstUsesWith(I, B);
4853           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4854             return ReplaceInstUsesWith(I, B);
4855         }
4856       }
4857       V1 = 0; V2 = 0; V3 = 0;
4858     }
4859     
4860     // Check to see if we have any common things being and'ed.  If so, find the
4861     // terms for V1 & (V2|V3).
4862     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4863       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4864         V1 = A, V2 = C, V3 = D;
4865       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4866         V1 = A, V2 = B, V3 = C;
4867       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4868         V1 = C, V2 = A, V3 = D;
4869       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4870         V1 = C, V2 = A, V3 = B;
4871       
4872       if (V1) {
4873         Value *Or =
4874           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4875         return BinaryOperator::CreateAnd(V1, Or);
4876       }
4877     }
4878
4879     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4880     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4881       return Match;
4882     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4883       return Match;
4884     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4885       return Match;
4886     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4887       return Match;
4888
4889     // ((A&~B)|(~A&B)) -> A^B
4890     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4891          match(B, m_Not(m_Specific(A)), *Context)))
4892       return BinaryOperator::CreateXor(A, D);
4893     // ((~B&A)|(~A&B)) -> A^B
4894     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4895          match(B, m_Not(m_Specific(C)), *Context)))
4896       return BinaryOperator::CreateXor(C, D);
4897     // ((A&~B)|(B&~A)) -> A^B
4898     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4899          match(D, m_Not(m_Specific(A)), *Context)))
4900       return BinaryOperator::CreateXor(A, B);
4901     // ((~B&A)|(B&~A)) -> A^B
4902     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4903          match(D, m_Not(m_Specific(C)), *Context)))
4904       return BinaryOperator::CreateXor(C, B);
4905   }
4906   
4907   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4908   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4909     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4910       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4911           SI0->getOperand(1) == SI1->getOperand(1) &&
4912           (SI0->hasOneUse() || SI1->hasOneUse())) {
4913         Instruction *NewOp =
4914         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4915                                                      SI1->getOperand(0),
4916                                                      SI0->getName()), I);
4917         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4918                                       SI1->getOperand(1));
4919       }
4920   }
4921
4922   // ((A|B)&1)|(B&-2) -> (A&1) | B
4923   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4924       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4925     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4926     if (Ret) return Ret;
4927   }
4928   // (B&-2)|((A|B)&1) -> (A&1) | B
4929   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4930       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4931     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4932     if (Ret) return Ret;
4933   }
4934
4935   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4936     if (A == Op1)   // ~A | A == -1
4937       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4938   } else {
4939     A = 0;
4940   }
4941   // Note, A is still live here!
4942   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4943     if (Op0 == B)
4944       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4945
4946     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4947     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4948       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4949                                               I.getName()+".demorgan"), I);
4950       return BinaryOperator::CreateNot(*Context, And);
4951     }
4952   }
4953
4954   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4955   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4956     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4957       return R;
4958
4959     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4960       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4961         return Res;
4962   }
4963     
4964   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4965   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4966     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4967       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4968         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4969             !isa<ICmpInst>(Op1C->getOperand(0))) {
4970           const Type *SrcTy = Op0C->getOperand(0)->getType();
4971           if (SrcTy == Op1C->getOperand(0)->getType() &&
4972               SrcTy->isIntOrIntVector() &&
4973               // Only do this if the casts both really cause code to be
4974               // generated.
4975               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4976                                 I.getType(), TD) &&
4977               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4978                                 I.getType(), TD)) {
4979             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4980                                                           Op1C->getOperand(0),
4981                                                           I.getName());
4982             InsertNewInstBefore(NewOp, I);
4983             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4984           }
4985         }
4986       }
4987   }
4988   
4989     
4990   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4991   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4992     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4993       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4994         return Res;
4995   }
4996
4997   return Changed ? &I : 0;
4998 }
4999
5000 namespace {
5001
5002 // XorSelf - Implements: X ^ X --> 0
5003 struct XorSelf {
5004   Value *RHS;
5005   XorSelf(Value *rhs) : RHS(rhs) {}
5006   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5007   Instruction *apply(BinaryOperator &Xor) const {
5008     return &Xor;
5009   }
5010 };
5011
5012 }
5013
5014 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5015   bool Changed = SimplifyCommutative(I);
5016   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5017
5018   if (isa<UndefValue>(Op1)) {
5019     if (isa<UndefValue>(Op0))
5020       // Handle undef ^ undef -> 0 special case. This is a common
5021       // idiom (misuse).
5022       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5023     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5024   }
5025
5026   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5027   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5028     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5029     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5030   }
5031   
5032   // See if we can simplify any instructions used by the instruction whose sole 
5033   // purpose is to compute bits we don't care about.
5034   if (SimplifyDemandedInstructionBits(I))
5035     return &I;
5036   if (isa<VectorType>(I.getType()))
5037     if (isa<ConstantAggregateZero>(Op1))
5038       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5039
5040   // Is this a ~ operation?
5041   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5042     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5043     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5044     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5045       if (Op0I->getOpcode() == Instruction::And || 
5046           Op0I->getOpcode() == Instruction::Or) {
5047         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5048         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5049           Instruction *NotY =
5050             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5051                                       Op0I->getOperand(1)->getName()+".not");
5052           InsertNewInstBefore(NotY, I);
5053           if (Op0I->getOpcode() == Instruction::And)
5054             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5055           else
5056             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5057         }
5058       }
5059     }
5060   }
5061   
5062   
5063   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5064     if (RHS == Context->getTrue() && Op0->hasOneUse()) {
5065       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5066       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5067         return new ICmpInst(*Context, ICI->getInversePredicate(),
5068                             ICI->getOperand(0), ICI->getOperand(1));
5069
5070       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5071         return new FCmpInst(*Context, FCI->getInversePredicate(),
5072                             FCI->getOperand(0), FCI->getOperand(1));
5073     }
5074
5075     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5076     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5077       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5078         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5079           Instruction::CastOps Opcode = Op0C->getOpcode();
5080           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5081             if (RHS == ConstantExpr::getCast(Opcode, 
5082                                              Context->getTrue(),
5083                                              Op0C->getDestTy())) {
5084               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5085                                      *Context,
5086                                      CI->getOpcode(), CI->getInversePredicate(),
5087                                      CI->getOperand(0), CI->getOperand(1)), I);
5088               NewCI->takeName(CI);
5089               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5090             }
5091           }
5092         }
5093       }
5094     }
5095
5096     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5097       // ~(c-X) == X-c-1 == X+(-c-1)
5098       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5099         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5100           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5101           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5102                                       ConstantInt::get(I.getType(), 1));
5103           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5104         }
5105           
5106       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5107         if (Op0I->getOpcode() == Instruction::Add) {
5108           // ~(X-c) --> (-c-1)-X
5109           if (RHS->isAllOnesValue()) {
5110             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5111             return BinaryOperator::CreateSub(
5112                            ConstantExpr::getSub(NegOp0CI,
5113                                       ConstantInt::get(I.getType(), 1)),
5114                                       Op0I->getOperand(0));
5115           } else if (RHS->getValue().isSignBit()) {
5116             // (X + C) ^ signbit -> (X + C + signbit)
5117             Constant *C = ConstantInt::get(*Context,
5118                                            RHS->getValue() + Op0CI->getValue());
5119             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5120
5121           }
5122         } else if (Op0I->getOpcode() == Instruction::Or) {
5123           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5124           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5125             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5126             // Anything in both C1 and C2 is known to be zero, remove it from
5127             // NewRHS.
5128             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5129             NewRHS = ConstantExpr::getAnd(NewRHS, 
5130                                        ConstantExpr::getNot(CommonBits));
5131             AddToWorkList(Op0I);
5132             I.setOperand(0, Op0I->getOperand(0));
5133             I.setOperand(1, NewRHS);
5134             return &I;
5135           }
5136         }
5137       }
5138     }
5139
5140     // Try to fold constant and into select arguments.
5141     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5142       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5143         return R;
5144     if (isa<PHINode>(Op0))
5145       if (Instruction *NV = FoldOpIntoPhi(I))
5146         return NV;
5147   }
5148
5149   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5150     if (X == Op1)
5151       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5152
5153   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5154     if (X == Op0)
5155       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5156
5157   
5158   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5159   if (Op1I) {
5160     Value *A, *B;
5161     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5162       if (A == Op0) {              // B^(B|A) == (A|B)^B
5163         Op1I->swapOperands();
5164         I.swapOperands();
5165         std::swap(Op0, Op1);
5166       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5167         I.swapOperands();     // Simplified below.
5168         std::swap(Op0, Op1);
5169       }
5170     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5171       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5172     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5173       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5174     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5175                Op1I->hasOneUse()){
5176       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5177         Op1I->swapOperands();
5178         std::swap(A, B);
5179       }
5180       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5181         I.swapOperands();     // Simplified below.
5182         std::swap(Op0, Op1);
5183       }
5184     }
5185   }
5186   
5187   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5188   if (Op0I) {
5189     Value *A, *B;
5190     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5191         Op0I->hasOneUse()) {
5192       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5193         std::swap(A, B);
5194       if (B == Op1) {                                // (A|B)^B == A & ~B
5195         Instruction *NotB =
5196           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5197                                                         Op1, "tmp"), I);
5198         return BinaryOperator::CreateAnd(A, NotB);
5199       }
5200     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5201       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5202     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5203       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5204     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5205                Op0I->hasOneUse()){
5206       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5207         std::swap(A, B);
5208       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5209           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5210         Instruction *N =
5211           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5212         return BinaryOperator::CreateAnd(N, Op1);
5213       }
5214     }
5215   }
5216   
5217   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5218   if (Op0I && Op1I && Op0I->isShift() && 
5219       Op0I->getOpcode() == Op1I->getOpcode() && 
5220       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5221       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5222     Instruction *NewOp =
5223       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5224                                                     Op1I->getOperand(0),
5225                                                     Op0I->getName()), I);
5226     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5227                                   Op1I->getOperand(1));
5228   }
5229     
5230   if (Op0I && Op1I) {
5231     Value *A, *B, *C, *D;
5232     // (A & B)^(A | B) -> A ^ B
5233     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5234         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5235       if ((A == C && B == D) || (A == D && B == C)) 
5236         return BinaryOperator::CreateXor(A, B);
5237     }
5238     // (A | B)^(A & B) -> A ^ B
5239     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5240         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5241       if ((A == C && B == D) || (A == D && B == C)) 
5242         return BinaryOperator::CreateXor(A, B);
5243     }
5244     
5245     // (A & B)^(C & D)
5246     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5247         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5248         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5249       // (X & Y)^(X & Y) -> (Y^Z) & X
5250       Value *X = 0, *Y = 0, *Z = 0;
5251       if (A == C)
5252         X = A, Y = B, Z = D;
5253       else if (A == D)
5254         X = A, Y = B, Z = C;
5255       else if (B == C)
5256         X = B, Y = A, Z = D;
5257       else if (B == D)
5258         X = B, Y = A, Z = C;
5259       
5260       if (X) {
5261         Instruction *NewOp =
5262         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5263         return BinaryOperator::CreateAnd(NewOp, X);
5264       }
5265     }
5266   }
5267     
5268   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5269   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5270     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5271       return R;
5272
5273   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5274   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5275     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5276       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5277         const Type *SrcTy = Op0C->getOperand(0)->getType();
5278         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5279             // Only do this if the casts both really cause code to be generated.
5280             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5281                               I.getType(), TD) &&
5282             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5283                               I.getType(), TD)) {
5284           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5285                                                          Op1C->getOperand(0),
5286                                                          I.getName());
5287           InsertNewInstBefore(NewOp, I);
5288           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5289         }
5290       }
5291   }
5292
5293   return Changed ? &I : 0;
5294 }
5295
5296 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5297                                    LLVMContext *Context) {
5298   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5299 }
5300
5301 static bool HasAddOverflow(ConstantInt *Result,
5302                            ConstantInt *In1, ConstantInt *In2,
5303                            bool IsSigned) {
5304   if (IsSigned)
5305     if (In2->getValue().isNegative())
5306       return Result->getValue().sgt(In1->getValue());
5307     else
5308       return Result->getValue().slt(In1->getValue());
5309   else
5310     return Result->getValue().ult(In1->getValue());
5311 }
5312
5313 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5314 /// overflowed for this type.
5315 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5316                             Constant *In2, LLVMContext *Context,
5317                             bool IsSigned = false) {
5318   Result = ConstantExpr::getAdd(In1, In2);
5319
5320   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5321     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5322       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5323       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5324                          ExtractElement(In1, Idx, Context),
5325                          ExtractElement(In2, Idx, Context),
5326                          IsSigned))
5327         return true;
5328     }
5329     return false;
5330   }
5331
5332   return HasAddOverflow(cast<ConstantInt>(Result),
5333                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5334                         IsSigned);
5335 }
5336
5337 static bool HasSubOverflow(ConstantInt *Result,
5338                            ConstantInt *In1, ConstantInt *In2,
5339                            bool IsSigned) {
5340   if (IsSigned)
5341     if (In2->getValue().isNegative())
5342       return Result->getValue().slt(In1->getValue());
5343     else
5344       return Result->getValue().sgt(In1->getValue());
5345   else
5346     return Result->getValue().ugt(In1->getValue());
5347 }
5348
5349 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5350 /// overflowed for this type.
5351 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5352                             Constant *In2, LLVMContext *Context,
5353                             bool IsSigned = false) {
5354   Result = ConstantExpr::getSub(In1, In2);
5355
5356   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5357     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5358       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5359       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5360                          ExtractElement(In1, Idx, Context),
5361                          ExtractElement(In2, Idx, Context),
5362                          IsSigned))
5363         return true;
5364     }
5365     return false;
5366   }
5367
5368   return HasSubOverflow(cast<ConstantInt>(Result),
5369                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5370                         IsSigned);
5371 }
5372
5373 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5374 /// code necessary to compute the offset from the base pointer (without adding
5375 /// in the base pointer).  Return the result as a signed integer of intptr size.
5376 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5377   TargetData &TD = *IC.getTargetData();
5378   gep_type_iterator GTI = gep_type_begin(GEP);
5379   const Type *IntPtrTy = TD.getIntPtrType();
5380   LLVMContext *Context = IC.getContext();
5381   Value *Result = Context->getNullValue(IntPtrTy);
5382
5383   // Build a mask for high order bits.
5384   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5385   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5386
5387   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5388        ++i, ++GTI) {
5389     Value *Op = *i;
5390     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5391     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5392       if (OpC->isZero()) continue;
5393       
5394       // Handle a struct index, which adds its field offset to the pointer.
5395       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5396         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5397         
5398         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5399           Result = 
5400              ConstantInt::get(*Context, 
5401                               RC->getValue() + APInt(IntPtrWidth, Size));
5402         else
5403           Result = IC.InsertNewInstBefore(
5404                    BinaryOperator::CreateAdd(Result,
5405                                         ConstantInt::get(IntPtrTy, Size),
5406                                              GEP->getName()+".offs"), I);
5407         continue;
5408       }
5409       
5410       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5411       Constant *OC =
5412               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5413       Scale = ConstantExpr::getMul(OC, Scale);
5414       if (Constant *RC = dyn_cast<Constant>(Result))
5415         Result = ConstantExpr::getAdd(RC, Scale);
5416       else {
5417         // Emit an add instruction.
5418         Result = IC.InsertNewInstBefore(
5419            BinaryOperator::CreateAdd(Result, Scale,
5420                                      GEP->getName()+".offs"), I);
5421       }
5422       continue;
5423     }
5424     // Convert to correct type.
5425     if (Op->getType() != IntPtrTy) {
5426       if (Constant *OpC = dyn_cast<Constant>(Op))
5427         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5428       else
5429         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5430                                                                 true,
5431                                                       Op->getName()+".c"), I);
5432     }
5433     if (Size != 1) {
5434       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5435       if (Constant *OpC = dyn_cast<Constant>(Op))
5436         Op = ConstantExpr::getMul(OpC, Scale);
5437       else    // We'll let instcombine(mul) convert this to a shl if possible.
5438         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5439                                                   GEP->getName()+".idx"), I);
5440     }
5441
5442     // Emit an add instruction.
5443     if (isa<Constant>(Op) && isa<Constant>(Result))
5444       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5445                                     cast<Constant>(Result));
5446     else
5447       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5448                                                   GEP->getName()+".offs"), I);
5449   }
5450   return Result;
5451 }
5452
5453
5454 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5455 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5456 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5457 /// be complex, and scales are involved.  The above expression would also be
5458 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5459 /// This later form is less amenable to optimization though, and we are allowed
5460 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5461 ///
5462 /// If we can't emit an optimized form for this expression, this returns null.
5463 /// 
5464 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5465                                           InstCombiner &IC) {
5466   TargetData &TD = *IC.getTargetData();
5467   gep_type_iterator GTI = gep_type_begin(GEP);
5468
5469   // Check to see if this gep only has a single variable index.  If so, and if
5470   // any constant indices are a multiple of its scale, then we can compute this
5471   // in terms of the scale of the variable index.  For example, if the GEP
5472   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5473   // because the expression will cross zero at the same point.
5474   unsigned i, e = GEP->getNumOperands();
5475   int64_t Offset = 0;
5476   for (i = 1; i != e; ++i, ++GTI) {
5477     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5478       // Compute the aggregate offset of constant indices.
5479       if (CI->isZero()) continue;
5480
5481       // Handle a struct index, which adds its field offset to the pointer.
5482       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5483         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5484       } else {
5485         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5486         Offset += Size*CI->getSExtValue();
5487       }
5488     } else {
5489       // Found our variable index.
5490       break;
5491     }
5492   }
5493   
5494   // If there are no variable indices, we must have a constant offset, just
5495   // evaluate it the general way.
5496   if (i == e) return 0;
5497   
5498   Value *VariableIdx = GEP->getOperand(i);
5499   // Determine the scale factor of the variable element.  For example, this is
5500   // 4 if the variable index is into an array of i32.
5501   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5502   
5503   // Verify that there are no other variable indices.  If so, emit the hard way.
5504   for (++i, ++GTI; i != e; ++i, ++GTI) {
5505     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5506     if (!CI) return 0;
5507    
5508     // Compute the aggregate offset of constant indices.
5509     if (CI->isZero()) continue;
5510     
5511     // Handle a struct index, which adds its field offset to the pointer.
5512     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5513       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5514     } else {
5515       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5516       Offset += Size*CI->getSExtValue();
5517     }
5518   }
5519   
5520   // Okay, we know we have a single variable index, which must be a
5521   // pointer/array/vector index.  If there is no offset, life is simple, return
5522   // the index.
5523   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5524   if (Offset == 0) {
5525     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5526     // we don't need to bother extending: the extension won't affect where the
5527     // computation crosses zero.
5528     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5529       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5530                                   VariableIdx->getName(), &I);
5531     return VariableIdx;
5532   }
5533   
5534   // Otherwise, there is an index.  The computation we will do will be modulo
5535   // the pointer size, so get it.
5536   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5537   
5538   Offset &= PtrSizeMask;
5539   VariableScale &= PtrSizeMask;
5540
5541   // To do this transformation, any constant index must be a multiple of the
5542   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5543   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5544   // multiple of the variable scale.
5545   int64_t NewOffs = Offset / (int64_t)VariableScale;
5546   if (Offset != NewOffs*(int64_t)VariableScale)
5547     return 0;
5548
5549   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5550   const Type *IntPtrTy = TD.getIntPtrType();
5551   if (VariableIdx->getType() != IntPtrTy)
5552     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5553                                               true /*SExt*/, 
5554                                               VariableIdx->getName(), &I);
5555   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5556   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5557 }
5558
5559
5560 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5561 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5562 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5563                                        ICmpInst::Predicate Cond,
5564                                        Instruction &I) {
5565   // Look through bitcasts.
5566   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5567     RHS = BCI->getOperand(0);
5568
5569   Value *PtrBase = GEPLHS->getOperand(0);
5570   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5571     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5572     // This transformation (ignoring the base and scales) is valid because we
5573     // know pointers can't overflow since the gep is inbounds.  See if we can
5574     // output an optimized form.
5575     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5576     
5577     // If not, synthesize the offset the hard way.
5578     if (Offset == 0)
5579       Offset = EmitGEPOffset(GEPLHS, I, *this);
5580     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5581                         Context->getNullValue(Offset->getType()));
5582   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5583     // If the base pointers are different, but the indices are the same, just
5584     // compare the base pointer.
5585     if (PtrBase != GEPRHS->getOperand(0)) {
5586       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5587       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5588                         GEPRHS->getOperand(0)->getType();
5589       if (IndicesTheSame)
5590         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5592             IndicesTheSame = false;
5593             break;
5594           }
5595
5596       // If all indices are the same, just compare the base pointers.
5597       if (IndicesTheSame)
5598         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5599                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5600
5601       // Otherwise, the base pointers are different and the indices are
5602       // different, bail out.
5603       return 0;
5604     }
5605
5606     // If one of the GEPs has all zero indices, recurse.
5607     bool AllZeros = true;
5608     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5609       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5610           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5611         AllZeros = false;
5612         break;
5613       }
5614     if (AllZeros)
5615       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5616                           ICmpInst::getSwappedPredicate(Cond), I);
5617
5618     // If the other GEP has all zero indices, recurse.
5619     AllZeros = true;
5620     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5622           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5623         AllZeros = false;
5624         break;
5625       }
5626     if (AllZeros)
5627       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5628
5629     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5630       // If the GEPs only differ by one index, compare it.
5631       unsigned NumDifferences = 0;  // Keep track of # differences.
5632       unsigned DiffOperand = 0;     // The operand that differs.
5633       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5635           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5636                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5637             // Irreconcilable differences.
5638             NumDifferences = 2;
5639             break;
5640           } else {
5641             if (NumDifferences++) break;
5642             DiffOperand = i;
5643           }
5644         }
5645
5646       if (NumDifferences == 0)   // SAME GEP?
5647         return ReplaceInstUsesWith(I, // No comparison is needed here.
5648                                    ConstantInt::get(Type::Int1Ty,
5649                                              ICmpInst::isTrueWhenEqual(Cond)));
5650
5651       else if (NumDifferences == 1) {
5652         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5653         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5654         // Make sure we do a signed comparison here.
5655         return new ICmpInst(*Context,
5656                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5657       }
5658     }
5659
5660     // Only lower this if the icmp is the only user of the GEP or if we expect
5661     // the result to fold to a constant!
5662     if (TD &&
5663         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5664         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5665       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5666       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5667       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5668       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5669     }
5670   }
5671   return 0;
5672 }
5673
5674 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5675 ///
5676 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5677                                                 Instruction *LHSI,
5678                                                 Constant *RHSC) {
5679   if (!isa<ConstantFP>(RHSC)) return 0;
5680   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5681   
5682   // Get the width of the mantissa.  We don't want to hack on conversions that
5683   // might lose information from the integer, e.g. "i64 -> float"
5684   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5685   if (MantissaWidth == -1) return 0;  // Unknown.
5686   
5687   // Check to see that the input is converted from an integer type that is small
5688   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5689   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5690   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5691   
5692   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5693   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5694   if (LHSUnsigned)
5695     ++InputSize;
5696   
5697   // If the conversion would lose info, don't hack on this.
5698   if ((int)InputSize > MantissaWidth)
5699     return 0;
5700   
5701   // Otherwise, we can potentially simplify the comparison.  We know that it
5702   // will always come through as an integer value and we know the constant is
5703   // not a NAN (it would have been previously simplified).
5704   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5705   
5706   ICmpInst::Predicate Pred;
5707   switch (I.getPredicate()) {
5708   default: llvm_unreachable("Unexpected predicate!");
5709   case FCmpInst::FCMP_UEQ:
5710   case FCmpInst::FCMP_OEQ:
5711     Pred = ICmpInst::ICMP_EQ;
5712     break;
5713   case FCmpInst::FCMP_UGT:
5714   case FCmpInst::FCMP_OGT:
5715     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5716     break;
5717   case FCmpInst::FCMP_UGE:
5718   case FCmpInst::FCMP_OGE:
5719     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5720     break;
5721   case FCmpInst::FCMP_ULT:
5722   case FCmpInst::FCMP_OLT:
5723     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5724     break;
5725   case FCmpInst::FCMP_ULE:
5726   case FCmpInst::FCMP_OLE:
5727     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5728     break;
5729   case FCmpInst::FCMP_UNE:
5730   case FCmpInst::FCMP_ONE:
5731     Pred = ICmpInst::ICMP_NE;
5732     break;
5733   case FCmpInst::FCMP_ORD:
5734     return ReplaceInstUsesWith(I, Context->getTrue());
5735   case FCmpInst::FCMP_UNO:
5736     return ReplaceInstUsesWith(I, Context->getFalse());
5737   }
5738   
5739   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5740   
5741   // Now we know that the APFloat is a normal number, zero or inf.
5742   
5743   // See if the FP constant is too large for the integer.  For example,
5744   // comparing an i8 to 300.0.
5745   unsigned IntWidth = IntTy->getScalarSizeInBits();
5746   
5747   if (!LHSUnsigned) {
5748     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5749     // and large values.
5750     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5751     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5752                           APFloat::rmNearestTiesToEven);
5753     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5754       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5755           Pred == ICmpInst::ICMP_SLE)
5756         return ReplaceInstUsesWith(I, Context->getTrue());
5757       return ReplaceInstUsesWith(I, Context->getFalse());
5758     }
5759   } else {
5760     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5761     // +INF and large values.
5762     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5763     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5764                           APFloat::rmNearestTiesToEven);
5765     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5766       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5767           Pred == ICmpInst::ICMP_ULE)
5768         return ReplaceInstUsesWith(I, Context->getTrue());
5769       return ReplaceInstUsesWith(I, Context->getFalse());
5770     }
5771   }
5772   
5773   if (!LHSUnsigned) {
5774     // See if the RHS value is < SignedMin.
5775     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5776     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5777                           APFloat::rmNearestTiesToEven);
5778     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5779       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5780           Pred == ICmpInst::ICMP_SGE)
5781         return ReplaceInstUsesWith(I, Context->getTrue());
5782       return ReplaceInstUsesWith(I, Context->getFalse());
5783     }
5784   }
5785
5786   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5787   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5788   // casting the FP value to the integer value and back, checking for equality.
5789   // Don't do this for zero, because -0.0 is not fractional.
5790   Constant *RHSInt = LHSUnsigned
5791     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5792     : ConstantExpr::getFPToSI(RHSC, IntTy);
5793   if (!RHS.isZero()) {
5794     bool Equal = LHSUnsigned
5795       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5796       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5797     if (!Equal) {
5798       // If we had a comparison against a fractional value, we have to adjust
5799       // the compare predicate and sometimes the value.  RHSC is rounded towards
5800       // zero at this point.
5801       switch (Pred) {
5802       default: llvm_unreachable("Unexpected integer comparison!");
5803       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5804         return ReplaceInstUsesWith(I, Context->getTrue());
5805       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5806         return ReplaceInstUsesWith(I, Context->getFalse());
5807       case ICmpInst::ICMP_ULE:
5808         // (float)int <= 4.4   --> int <= 4
5809         // (float)int <= -4.4  --> false
5810         if (RHS.isNegative())
5811           return ReplaceInstUsesWith(I, Context->getFalse());
5812         break;
5813       case ICmpInst::ICMP_SLE:
5814         // (float)int <= 4.4   --> int <= 4
5815         // (float)int <= -4.4  --> int < -4
5816         if (RHS.isNegative())
5817           Pred = ICmpInst::ICMP_SLT;
5818         break;
5819       case ICmpInst::ICMP_ULT:
5820         // (float)int < -4.4   --> false
5821         // (float)int < 4.4    --> int <= 4
5822         if (RHS.isNegative())
5823           return ReplaceInstUsesWith(I, Context->getFalse());
5824         Pred = ICmpInst::ICMP_ULE;
5825         break;
5826       case ICmpInst::ICMP_SLT:
5827         // (float)int < -4.4   --> int < -4
5828         // (float)int < 4.4    --> int <= 4
5829         if (!RHS.isNegative())
5830           Pred = ICmpInst::ICMP_SLE;
5831         break;
5832       case ICmpInst::ICMP_UGT:
5833         // (float)int > 4.4    --> int > 4
5834         // (float)int > -4.4   --> true
5835         if (RHS.isNegative())
5836           return ReplaceInstUsesWith(I, Context->getTrue());
5837         break;
5838       case ICmpInst::ICMP_SGT:
5839         // (float)int > 4.4    --> int > 4
5840         // (float)int > -4.4   --> int >= -4
5841         if (RHS.isNegative())
5842           Pred = ICmpInst::ICMP_SGE;
5843         break;
5844       case ICmpInst::ICMP_UGE:
5845         // (float)int >= -4.4   --> true
5846         // (float)int >= 4.4    --> int > 4
5847         if (!RHS.isNegative())
5848           return ReplaceInstUsesWith(I, Context->getTrue());
5849         Pred = ICmpInst::ICMP_UGT;
5850         break;
5851       case ICmpInst::ICMP_SGE:
5852         // (float)int >= -4.4   --> int >= -4
5853         // (float)int >= 4.4    --> int > 4
5854         if (!RHS.isNegative())
5855           Pred = ICmpInst::ICMP_SGT;
5856         break;
5857       }
5858     }
5859   }
5860
5861   // Lower this FP comparison into an appropriate integer version of the
5862   // comparison.
5863   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5864 }
5865
5866 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5867   bool Changed = SimplifyCompare(I);
5868   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5869
5870   // Fold trivial predicates.
5871   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5872     return ReplaceInstUsesWith(I, Context->getFalse());
5873   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5874     return ReplaceInstUsesWith(I, Context->getTrue());
5875   
5876   // Simplify 'fcmp pred X, X'
5877   if (Op0 == Op1) {
5878     switch (I.getPredicate()) {
5879     default: llvm_unreachable("Unknown predicate!");
5880     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5881     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5882     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5883       return ReplaceInstUsesWith(I, Context->getTrue());
5884     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5885     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5886     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5887       return ReplaceInstUsesWith(I, Context->getFalse());
5888       
5889     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5890     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5891     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5892     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5893       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5894       I.setPredicate(FCmpInst::FCMP_UNO);
5895       I.setOperand(1, Context->getNullValue(Op0->getType()));
5896       return &I;
5897       
5898     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5899     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5900     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5901     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5902       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5903       I.setPredicate(FCmpInst::FCMP_ORD);
5904       I.setOperand(1, Context->getNullValue(Op0->getType()));
5905       return &I;
5906     }
5907   }
5908     
5909   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5910     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5911
5912   // Handle fcmp with constant RHS
5913   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5914     // If the constant is a nan, see if we can fold the comparison based on it.
5915     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5916       if (CFP->getValueAPF().isNaN()) {
5917         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5918           return ReplaceInstUsesWith(I, Context->getFalse());
5919         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5920                "Comparison must be either ordered or unordered!");
5921         // True if unordered.
5922         return ReplaceInstUsesWith(I, Context->getTrue());
5923       }
5924     }
5925     
5926     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5927       switch (LHSI->getOpcode()) {
5928       case Instruction::PHI:
5929         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5930         // block.  If in the same block, we're encouraging jump threading.  If
5931         // not, we are just pessimizing the code by making an i1 phi.
5932         if (LHSI->getParent() == I.getParent())
5933           if (Instruction *NV = FoldOpIntoPhi(I))
5934             return NV;
5935         break;
5936       case Instruction::SIToFP:
5937       case Instruction::UIToFP:
5938         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5939           return NV;
5940         break;
5941       case Instruction::Select:
5942         // If either operand of the select is a constant, we can fold the
5943         // comparison into the select arms, which will cause one to be
5944         // constant folded and the select turned into a bitwise or.
5945         Value *Op1 = 0, *Op2 = 0;
5946         if (LHSI->hasOneUse()) {
5947           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5948             // Fold the known value into the constant operand.
5949             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5950             // Insert a new FCmp of the other select operand.
5951             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5952                                                       LHSI->getOperand(2), RHSC,
5953                                                       I.getName()), I);
5954           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5955             // Fold the known value into the constant operand.
5956             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5957             // Insert a new FCmp of the other select operand.
5958             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5959                                                       LHSI->getOperand(1), RHSC,
5960                                                       I.getName()), I);
5961           }
5962         }
5963
5964         if (Op1)
5965           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5966         break;
5967       }
5968   }
5969
5970   return Changed ? &I : 0;
5971 }
5972
5973 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5974   bool Changed = SimplifyCompare(I);
5975   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5976   const Type *Ty = Op0->getType();
5977
5978   // icmp X, X
5979   if (Op0 == Op1)
5980     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5981                                                    I.isTrueWhenEqual()));
5982
5983   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5984     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5985   
5986   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5987   // addresses never equal each other!  We already know that Op0 != Op1.
5988   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5989        isa<ConstantPointerNull>(Op0)) &&
5990       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5991        isa<ConstantPointerNull>(Op1)))
5992     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5993                                                    !I.isTrueWhenEqual()));
5994
5995   // icmp's with boolean values can always be turned into bitwise operations
5996   if (Ty == Type::Int1Ty) {
5997     switch (I.getPredicate()) {
5998     default: llvm_unreachable("Invalid icmp instruction!");
5999     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6000       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6001       InsertNewInstBefore(Xor, I);
6002       return BinaryOperator::CreateNot(*Context, Xor);
6003     }
6004     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6005       return BinaryOperator::CreateXor(Op0, Op1);
6006
6007     case ICmpInst::ICMP_UGT:
6008       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6009       // FALL THROUGH
6010     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6011       Instruction *Not = BinaryOperator::CreateNot(*Context,
6012                                                    Op0, I.getName()+"tmp");
6013       InsertNewInstBefore(Not, I);
6014       return BinaryOperator::CreateAnd(Not, Op1);
6015     }
6016     case ICmpInst::ICMP_SGT:
6017       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6018       // FALL THROUGH
6019     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6020       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6021                                                    Op1, I.getName()+"tmp");
6022       InsertNewInstBefore(Not, I);
6023       return BinaryOperator::CreateAnd(Not, Op0);
6024     }
6025     case ICmpInst::ICMP_UGE:
6026       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6027       // FALL THROUGH
6028     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6029       Instruction *Not = BinaryOperator::CreateNot(*Context,
6030                                                    Op0, I.getName()+"tmp");
6031       InsertNewInstBefore(Not, I);
6032       return BinaryOperator::CreateOr(Not, Op1);
6033     }
6034     case ICmpInst::ICMP_SGE:
6035       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6036       // FALL THROUGH
6037     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6038       Instruction *Not = BinaryOperator::CreateNot(*Context,
6039                                                    Op1, I.getName()+"tmp");
6040       InsertNewInstBefore(Not, I);
6041       return BinaryOperator::CreateOr(Not, Op0);
6042     }
6043     }
6044   }
6045
6046   unsigned BitWidth = 0;
6047   if (TD)
6048     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6049   else if (Ty->isIntOrIntVector())
6050     BitWidth = Ty->getScalarSizeInBits();
6051
6052   bool isSignBit = false;
6053
6054   // See if we are doing a comparison with a constant.
6055   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6056     Value *A = 0, *B = 0;
6057     
6058     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6059     if (I.isEquality() && CI->isNullValue() &&
6060         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6061       // (icmp cond A B) if cond is equality
6062       return new ICmpInst(*Context, I.getPredicate(), A, B);
6063     }
6064     
6065     // If we have an icmp le or icmp ge instruction, turn it into the
6066     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6067     // them being folded in the code below.
6068     switch (I.getPredicate()) {
6069     default: break;
6070     case ICmpInst::ICMP_ULE:
6071       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6072         return ReplaceInstUsesWith(I, Context->getTrue());
6073       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6074                           AddOne(CI, Context));
6075     case ICmpInst::ICMP_SLE:
6076       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6077         return ReplaceInstUsesWith(I, Context->getTrue());
6078       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6079                           AddOne(CI, Context));
6080     case ICmpInst::ICMP_UGE:
6081       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6082         return ReplaceInstUsesWith(I, Context->getTrue());
6083       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6084                           SubOne(CI, Context));
6085     case ICmpInst::ICMP_SGE:
6086       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6087         return ReplaceInstUsesWith(I, Context->getTrue());
6088       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6089                           SubOne(CI, Context));
6090     }
6091     
6092     // If this comparison is a normal comparison, it demands all
6093     // bits, if it is a sign bit comparison, it only demands the sign bit.
6094     bool UnusedBit;
6095     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6096   }
6097
6098   // See if we can fold the comparison based on range information we can get
6099   // by checking whether bits are known to be zero or one in the input.
6100   if (BitWidth != 0) {
6101     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6102     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6103
6104     if (SimplifyDemandedBits(I.getOperandUse(0),
6105                              isSignBit ? APInt::getSignBit(BitWidth)
6106                                        : APInt::getAllOnesValue(BitWidth),
6107                              Op0KnownZero, Op0KnownOne, 0))
6108       return &I;
6109     if (SimplifyDemandedBits(I.getOperandUse(1),
6110                              APInt::getAllOnesValue(BitWidth),
6111                              Op1KnownZero, Op1KnownOne, 0))
6112       return &I;
6113
6114     // Given the known and unknown bits, compute a range that the LHS could be
6115     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6116     // EQ and NE we use unsigned values.
6117     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6118     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6119     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6120       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121                                              Op0Min, Op0Max);
6122       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123                                              Op1Min, Op1Max);
6124     } else {
6125       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126                                                Op0Min, Op0Max);
6127       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128                                                Op1Min, Op1Max);
6129     }
6130
6131     // If Min and Max are known to be the same, then SimplifyDemandedBits
6132     // figured out that the LHS is a constant.  Just constant fold this now so
6133     // that code below can assume that Min != Max.
6134     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6135       return new ICmpInst(*Context, I.getPredicate(),
6136                           ConstantInt::get(*Context, Op0Min), Op1);
6137     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6138       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6139                           ConstantInt::get(*Context, Op1Min));
6140
6141     // Based on the range information we know about the LHS, see if we can
6142     // simplify this comparison.  For example, (x&4) < 8  is always true.
6143     switch (I.getPredicate()) {
6144     default: llvm_unreachable("Unknown icmp opcode!");
6145     case ICmpInst::ICMP_EQ:
6146       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6147         return ReplaceInstUsesWith(I, Context->getFalse());
6148       break;
6149     case ICmpInst::ICMP_NE:
6150       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6151         return ReplaceInstUsesWith(I, Context->getTrue());
6152       break;
6153     case ICmpInst::ICMP_ULT:
6154       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6155         return ReplaceInstUsesWith(I, Context->getTrue());
6156       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6157         return ReplaceInstUsesWith(I, Context->getFalse());
6158       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6159         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6160       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6161         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6162           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6163                               SubOne(CI, Context));
6164
6165         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6166         if (CI->isMinValue(true))
6167           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6168                            Context->getAllOnesValue(Op0->getType()));
6169       }
6170       break;
6171     case ICmpInst::ICMP_UGT:
6172       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6173         return ReplaceInstUsesWith(I, Context->getTrue());
6174       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6175         return ReplaceInstUsesWith(I, Context->getFalse());
6176
6177       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6178         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6179       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6180         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6181           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6182                               AddOne(CI, Context));
6183
6184         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6185         if (CI->isMaxValue(true))
6186           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6187                               Context->getNullValue(Op0->getType()));
6188       }
6189       break;
6190     case ICmpInst::ICMP_SLT:
6191       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6192         return ReplaceInstUsesWith(I, Context->getTrue());
6193       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6194         return ReplaceInstUsesWith(I, Context->getFalse());
6195       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6196         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6197       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6198         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6199           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6200                               SubOne(CI, Context));
6201       }
6202       break;
6203     case ICmpInst::ICMP_SGT:
6204       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6205         return ReplaceInstUsesWith(I, Context->getTrue());
6206       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6207         return ReplaceInstUsesWith(I, Context->getFalse());
6208
6209       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6210         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6211       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6212         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6213           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6214                               AddOne(CI, Context));
6215       }
6216       break;
6217     case ICmpInst::ICMP_SGE:
6218       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6219       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6220         return ReplaceInstUsesWith(I, Context->getTrue());
6221       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6222         return ReplaceInstUsesWith(I, Context->getFalse());
6223       break;
6224     case ICmpInst::ICMP_SLE:
6225       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6226       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6227         return ReplaceInstUsesWith(I, Context->getTrue());
6228       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6229         return ReplaceInstUsesWith(I, Context->getFalse());
6230       break;
6231     case ICmpInst::ICMP_UGE:
6232       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6233       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6234         return ReplaceInstUsesWith(I, Context->getTrue());
6235       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6236         return ReplaceInstUsesWith(I, Context->getFalse());
6237       break;
6238     case ICmpInst::ICMP_ULE:
6239       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6240       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6241         return ReplaceInstUsesWith(I, Context->getTrue());
6242       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6243         return ReplaceInstUsesWith(I, Context->getFalse());
6244       break;
6245     }
6246
6247     // Turn a signed comparison into an unsigned one if both operands
6248     // are known to have the same sign.
6249     if (I.isSignedPredicate() &&
6250         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6251          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6252       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6253   }
6254
6255   // Test if the ICmpInst instruction is used exclusively by a select as
6256   // part of a minimum or maximum operation. If so, refrain from doing
6257   // any other folding. This helps out other analyses which understand
6258   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6259   // and CodeGen. And in this case, at least one of the comparison
6260   // operands has at least one user besides the compare (the select),
6261   // which would often largely negate the benefit of folding anyway.
6262   if (I.hasOneUse())
6263     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6264       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6265           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6266         return 0;
6267
6268   // See if we are doing a comparison between a constant and an instruction that
6269   // can be folded into the comparison.
6270   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6271     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6272     // instruction, see if that instruction also has constants so that the 
6273     // instruction can be folded into the icmp 
6274     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6275       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6276         return Res;
6277   }
6278
6279   // Handle icmp with constant (but not simple integer constant) RHS
6280   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6281     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6282       switch (LHSI->getOpcode()) {
6283       case Instruction::GetElementPtr:
6284         if (RHSC->isNullValue()) {
6285           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6286           bool isAllZeros = true;
6287           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6288             if (!isa<Constant>(LHSI->getOperand(i)) ||
6289                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6290               isAllZeros = false;
6291               break;
6292             }
6293           if (isAllZeros)
6294             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6295                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6296         }
6297         break;
6298
6299       case Instruction::PHI:
6300         // Only fold icmp into the PHI if the phi and fcmp are in the same
6301         // block.  If in the same block, we're encouraging jump threading.  If
6302         // not, we are just pessimizing the code by making an i1 phi.
6303         if (LHSI->getParent() == I.getParent())
6304           if (Instruction *NV = FoldOpIntoPhi(I))
6305             return NV;
6306         break;
6307       case Instruction::Select: {
6308         // If either operand of the select is a constant, we can fold the
6309         // comparison into the select arms, which will cause one to be
6310         // constant folded and the select turned into a bitwise or.
6311         Value *Op1 = 0, *Op2 = 0;
6312         if (LHSI->hasOneUse()) {
6313           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6314             // Fold the known value into the constant operand.
6315             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6316             // Insert a new ICmp of the other select operand.
6317             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6318                                                    LHSI->getOperand(2), RHSC,
6319                                                    I.getName()), I);
6320           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6321             // Fold the known value into the constant operand.
6322             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6323             // Insert a new ICmp of the other select operand.
6324             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6325                                                    LHSI->getOperand(1), RHSC,
6326                                                    I.getName()), I);
6327           }
6328         }
6329
6330         if (Op1)
6331           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6332         break;
6333       }
6334       case Instruction::Malloc:
6335         // If we have (malloc != null), and if the malloc has a single use, we
6336         // can assume it is successful and remove the malloc.
6337         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6338           AddToWorkList(LHSI);
6339           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6340                                                          !I.isTrueWhenEqual()));
6341         }
6342         break;
6343       }
6344   }
6345
6346   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6347   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6348     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6349       return NI;
6350   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6351     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6352                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6353       return NI;
6354
6355   // Test to see if the operands of the icmp are casted versions of other
6356   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6357   // now.
6358   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6359     if (isa<PointerType>(Op0->getType()) && 
6360         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6361       // We keep moving the cast from the left operand over to the right
6362       // operand, where it can often be eliminated completely.
6363       Op0 = CI->getOperand(0);
6364
6365       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6366       // so eliminate it as well.
6367       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6368         Op1 = CI2->getOperand(0);
6369
6370       // If Op1 is a constant, we can fold the cast into the constant.
6371       if (Op0->getType() != Op1->getType()) {
6372         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6373           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6374         } else {
6375           // Otherwise, cast the RHS right before the icmp
6376           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6377         }
6378       }
6379       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6380     }
6381   }
6382   
6383   if (isa<CastInst>(Op0)) {
6384     // Handle the special case of: icmp (cast bool to X), <cst>
6385     // This comes up when you have code like
6386     //   int X = A < B;
6387     //   if (X) ...
6388     // For generality, we handle any zero-extension of any operand comparison
6389     // with a constant or another cast from the same type.
6390     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6391       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6392         return R;
6393   }
6394   
6395   // See if it's the same type of instruction on the left and right.
6396   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6397     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6398       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6399           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6400         switch (Op0I->getOpcode()) {
6401         default: break;
6402         case Instruction::Add:
6403         case Instruction::Sub:
6404         case Instruction::Xor:
6405           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6406             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6407                                 Op1I->getOperand(0));
6408           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6409           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6410             if (CI->getValue().isSignBit()) {
6411               ICmpInst::Predicate Pred = I.isSignedPredicate()
6412                                              ? I.getUnsignedPredicate()
6413                                              : I.getSignedPredicate();
6414               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6415                                   Op1I->getOperand(0));
6416             }
6417             
6418             if (CI->getValue().isMaxSignedValue()) {
6419               ICmpInst::Predicate Pred = I.isSignedPredicate()
6420                                              ? I.getUnsignedPredicate()
6421                                              : I.getSignedPredicate();
6422               Pred = I.getSwappedPredicate(Pred);
6423               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6424                                   Op1I->getOperand(0));
6425             }
6426           }
6427           break;
6428         case Instruction::Mul:
6429           if (!I.isEquality())
6430             break;
6431
6432           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6433             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6434             // Mask = -1 >> count-trailing-zeros(Cst).
6435             if (!CI->isZero() && !CI->isOne()) {
6436               const APInt &AP = CI->getValue();
6437               ConstantInt *Mask = ConstantInt::get(*Context, 
6438                                       APInt::getLowBitsSet(AP.getBitWidth(),
6439                                                            AP.getBitWidth() -
6440                                                       AP.countTrailingZeros()));
6441               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6442                                                             Mask);
6443               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6444                                                             Mask);
6445               InsertNewInstBefore(And1, I);
6446               InsertNewInstBefore(And2, I);
6447               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6448             }
6449           }
6450           break;
6451         }
6452       }
6453     }
6454   }
6455   
6456   // ~x < ~y --> y < x
6457   { Value *A, *B;
6458     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6459         match(Op1, m_Not(m_Value(B)), *Context))
6460       return new ICmpInst(*Context, I.getPredicate(), B, A);
6461   }
6462   
6463   if (I.isEquality()) {
6464     Value *A, *B, *C, *D;
6465     
6466     // -x == -y --> x == y
6467     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6468         match(Op1, m_Neg(m_Value(B)), *Context))
6469       return new ICmpInst(*Context, I.getPredicate(), A, B);
6470     
6471     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6472       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6473         Value *OtherVal = A == Op1 ? B : A;
6474         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6475                             Context->getNullValue(A->getType()));
6476       }
6477
6478       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6479         // A^c1 == C^c2 --> A == C^(c1^c2)
6480         ConstantInt *C1, *C2;
6481         if (match(B, m_ConstantInt(C1), *Context) &&
6482             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6483           Constant *NC = 
6484                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6485           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6486           return new ICmpInst(*Context, I.getPredicate(), A,
6487                               InsertNewInstBefore(Xor, I));
6488         }
6489         
6490         // A^B == A^D -> B == D
6491         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6492         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6493         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6494         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6495       }
6496     }
6497     
6498     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6499         (A == Op0 || B == Op0)) {
6500       // A == (A^B)  ->  B == 0
6501       Value *OtherVal = A == Op0 ? B : A;
6502       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6503                           Context->getNullValue(A->getType()));
6504     }
6505
6506     // (A-B) == A  ->  B == 0
6507     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6508       return new ICmpInst(*Context, I.getPredicate(), B, 
6509                           Context->getNullValue(B->getType()));
6510
6511     // A == (A-B)  ->  B == 0
6512     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6513       return new ICmpInst(*Context, I.getPredicate(), B,
6514                           Context->getNullValue(B->getType()));
6515     
6516     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6517     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6518         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6519         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6520       Value *X = 0, *Y = 0, *Z = 0;
6521       
6522       if (A == C) {
6523         X = B; Y = D; Z = A;
6524       } else if (A == D) {
6525         X = B; Y = C; Z = A;
6526       } else if (B == C) {
6527         X = A; Y = D; Z = B;
6528       } else if (B == D) {
6529         X = A; Y = C; Z = B;
6530       }
6531       
6532       if (X) {   // Build (X^Y) & Z
6533         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6534         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6535         I.setOperand(0, Op1);
6536         I.setOperand(1, Context->getNullValue(Op1->getType()));
6537         return &I;
6538       }
6539     }
6540   }
6541   return Changed ? &I : 0;
6542 }
6543
6544
6545 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6546 /// and CmpRHS are both known to be integer constants.
6547 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6548                                           ConstantInt *DivRHS) {
6549   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6550   const APInt &CmpRHSV = CmpRHS->getValue();
6551   
6552   // FIXME: If the operand types don't match the type of the divide 
6553   // then don't attempt this transform. The code below doesn't have the
6554   // logic to deal with a signed divide and an unsigned compare (and
6555   // vice versa). This is because (x /s C1) <s C2  produces different 
6556   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6557   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6558   // work. :(  The if statement below tests that condition and bails 
6559   // if it finds it. 
6560   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6561   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6562     return 0;
6563   if (DivRHS->isZero())
6564     return 0; // The ProdOV computation fails on divide by zero.
6565   if (DivIsSigned && DivRHS->isAllOnesValue())
6566     return 0; // The overflow computation also screws up here
6567   if (DivRHS->isOne())
6568     return 0; // Not worth bothering, and eliminates some funny cases
6569               // with INT_MIN.
6570
6571   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6572   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6573   // C2 (CI). By solving for X we can turn this into a range check 
6574   // instead of computing a divide. 
6575   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6576
6577   // Determine if the product overflows by seeing if the product is
6578   // not equal to the divide. Make sure we do the same kind of divide
6579   // as in the LHS instruction that we're folding. 
6580   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6581                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6582
6583   // Get the ICmp opcode
6584   ICmpInst::Predicate Pred = ICI.getPredicate();
6585
6586   // Figure out the interval that is being checked.  For example, a comparison
6587   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6588   // Compute this interval based on the constants involved and the signedness of
6589   // the compare/divide.  This computes a half-open interval, keeping track of
6590   // whether either value in the interval overflows.  After analysis each
6591   // overflow variable is set to 0 if it's corresponding bound variable is valid
6592   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6593   int LoOverflow = 0, HiOverflow = 0;
6594   Constant *LoBound = 0, *HiBound = 0;
6595   
6596   if (!DivIsSigned) {  // udiv
6597     // e.g. X/5 op 3  --> [15, 20)
6598     LoBound = Prod;
6599     HiOverflow = LoOverflow = ProdOV;
6600     if (!HiOverflow)
6601       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6602   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6603     if (CmpRHSV == 0) {       // (X / pos) op 0
6604       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6605       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS, 
6606                                                                     Context)));
6607       HiBound = DivRHS;
6608     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6609       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6610       HiOverflow = LoOverflow = ProdOV;
6611       if (!HiOverflow)
6612         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6613     } else {                       // (X / pos) op neg
6614       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6615       HiBound = AddOne(Prod, Context);
6616       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6617       if (!LoOverflow) {
6618         ConstantInt* DivNeg =
6619                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6620         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6621                                      true) ? -1 : 0;
6622        }
6623     }
6624   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6625     if (CmpRHSV == 0) {       // (X / neg) op 0
6626       // e.g. X/-5 op 0  --> [-4, 5)
6627       LoBound = AddOne(DivRHS, Context);
6628       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6629       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6630         HiOverflow = 1;            // [INTMIN+1, overflow)
6631         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6632       }
6633     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6634       // e.g. X/-5 op 3  --> [-19, -14)
6635       HiBound = AddOne(Prod, Context);
6636       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6637       if (!LoOverflow)
6638         LoOverflow = AddWithOverflow(LoBound, HiBound,
6639                                      DivRHS, Context, true) ? -1 : 0;
6640     } else {                       // (X / neg) op neg
6641       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6642       LoOverflow = HiOverflow = ProdOV;
6643       if (!HiOverflow)
6644         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6645     }
6646     
6647     // Dividing by a negative swaps the condition.  LT <-> GT
6648     Pred = ICmpInst::getSwappedPredicate(Pred);
6649   }
6650
6651   Value *X = DivI->getOperand(0);
6652   switch (Pred) {
6653   default: llvm_unreachable("Unhandled icmp opcode!");
6654   case ICmpInst::ICMP_EQ:
6655     if (LoOverflow && HiOverflow)
6656       return ReplaceInstUsesWith(ICI, Context->getFalse());
6657     else if (HiOverflow)
6658       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6659                           ICmpInst::ICMP_UGE, X, LoBound);
6660     else if (LoOverflow)
6661       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6662                           ICmpInst::ICMP_ULT, X, HiBound);
6663     else
6664       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6665   case ICmpInst::ICMP_NE:
6666     if (LoOverflow && HiOverflow)
6667       return ReplaceInstUsesWith(ICI, Context->getTrue());
6668     else if (HiOverflow)
6669       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6670                           ICmpInst::ICMP_ULT, X, LoBound);
6671     else if (LoOverflow)
6672       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6673                           ICmpInst::ICMP_UGE, X, HiBound);
6674     else
6675       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6676   case ICmpInst::ICMP_ULT:
6677   case ICmpInst::ICMP_SLT:
6678     if (LoOverflow == +1)   // Low bound is greater than input range.
6679       return ReplaceInstUsesWith(ICI, Context->getTrue());
6680     if (LoOverflow == -1)   // Low bound is less than input range.
6681       return ReplaceInstUsesWith(ICI, Context->getFalse());
6682     return new ICmpInst(*Context, Pred, X, LoBound);
6683   case ICmpInst::ICMP_UGT:
6684   case ICmpInst::ICMP_SGT:
6685     if (HiOverflow == +1)       // High bound greater than input range.
6686       return ReplaceInstUsesWith(ICI, Context->getFalse());
6687     else if (HiOverflow == -1)  // High bound less than input range.
6688       return ReplaceInstUsesWith(ICI, Context->getTrue());
6689     if (Pred == ICmpInst::ICMP_UGT)
6690       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6691     else
6692       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6693   }
6694 }
6695
6696
6697 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6698 ///
6699 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6700                                                           Instruction *LHSI,
6701                                                           ConstantInt *RHS) {
6702   const APInt &RHSV = RHS->getValue();
6703   
6704   switch (LHSI->getOpcode()) {
6705   case Instruction::Trunc:
6706     if (ICI.isEquality() && LHSI->hasOneUse()) {
6707       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6708       // of the high bits truncated out of x are known.
6709       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6710              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6711       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6712       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6713       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6714       
6715       // If all the high bits are known, we can do this xform.
6716       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6717         // Pull in the high bits from known-ones set.
6718         APInt NewRHS(RHS->getValue());
6719         NewRHS.zext(SrcBits);
6720         NewRHS |= KnownOne;
6721         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6722                             ConstantInt::get(*Context, NewRHS));
6723       }
6724     }
6725     break;
6726       
6727   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6728     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6729       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6730       // fold the xor.
6731       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6732           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6733         Value *CompareVal = LHSI->getOperand(0);
6734         
6735         // If the sign bit of the XorCST is not set, there is no change to
6736         // the operation, just stop using the Xor.
6737         if (!XorCST->getValue().isNegative()) {
6738           ICI.setOperand(0, CompareVal);
6739           AddToWorkList(LHSI);
6740           return &ICI;
6741         }
6742         
6743         // Was the old condition true if the operand is positive?
6744         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6745         
6746         // If so, the new one isn't.
6747         isTrueIfPositive ^= true;
6748         
6749         if (isTrueIfPositive)
6750           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6751                               SubOne(RHS, Context));
6752         else
6753           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6754                               AddOne(RHS, Context));
6755       }
6756
6757       if (LHSI->hasOneUse()) {
6758         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6759         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6760           const APInt &SignBit = XorCST->getValue();
6761           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6762                                          ? ICI.getUnsignedPredicate()
6763                                          : ICI.getSignedPredicate();
6764           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6765                               ConstantInt::get(*Context, RHSV ^ SignBit));
6766         }
6767
6768         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6769         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6770           const APInt &NotSignBit = XorCST->getValue();
6771           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6772                                          ? ICI.getUnsignedPredicate()
6773                                          : ICI.getSignedPredicate();
6774           Pred = ICI.getSwappedPredicate(Pred);
6775           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6776                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6777         }
6778       }
6779     }
6780     break;
6781   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6782     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6783         LHSI->getOperand(0)->hasOneUse()) {
6784       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6785       
6786       // If the LHS is an AND of a truncating cast, we can widen the
6787       // and/compare to be the input width without changing the value
6788       // produced, eliminating a cast.
6789       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6790         // We can do this transformation if either the AND constant does not
6791         // have its sign bit set or if it is an equality comparison. 
6792         // Extending a relational comparison when we're checking the sign
6793         // bit would not work.
6794         if (Cast->hasOneUse() &&
6795             (ICI.isEquality() ||
6796              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6797           uint32_t BitWidth = 
6798             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6799           APInt NewCST = AndCST->getValue();
6800           NewCST.zext(BitWidth);
6801           APInt NewCI = RHSV;
6802           NewCI.zext(BitWidth);
6803           Instruction *NewAnd = 
6804             BinaryOperator::CreateAnd(Cast->getOperand(0),
6805                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6806           InsertNewInstBefore(NewAnd, ICI);
6807           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6808                               ConstantInt::get(*Context, NewCI));
6809         }
6810       }
6811       
6812       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6813       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6814       // happens a LOT in code produced by the C front-end, for bitfield
6815       // access.
6816       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6817       if (Shift && !Shift->isShift())
6818         Shift = 0;
6819       
6820       ConstantInt *ShAmt;
6821       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6822       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6823       const Type *AndTy = AndCST->getType();          // Type of the and.
6824       
6825       // We can fold this as long as we can't shift unknown bits
6826       // into the mask.  This can only happen with signed shift
6827       // rights, as they sign-extend.
6828       if (ShAmt) {
6829         bool CanFold = Shift->isLogicalShift();
6830         if (!CanFold) {
6831           // To test for the bad case of the signed shr, see if any
6832           // of the bits shifted in could be tested after the mask.
6833           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6834           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6835           
6836           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6837           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6838                AndCST->getValue()) == 0)
6839             CanFold = true;
6840         }
6841         
6842         if (CanFold) {
6843           Constant *NewCst;
6844           if (Shift->getOpcode() == Instruction::Shl)
6845             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6846           else
6847             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6848           
6849           // Check to see if we are shifting out any of the bits being
6850           // compared.
6851           if (ConstantExpr::get(Shift->getOpcode(),
6852                                        NewCst, ShAmt) != RHS) {
6853             // If we shifted bits out, the fold is not going to work out.
6854             // As a special case, check to see if this means that the
6855             // result is always true or false now.
6856             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6857               return ReplaceInstUsesWith(ICI, Context->getFalse());
6858             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6859               return ReplaceInstUsesWith(ICI, Context->getTrue());
6860           } else {
6861             ICI.setOperand(1, NewCst);
6862             Constant *NewAndCST;
6863             if (Shift->getOpcode() == Instruction::Shl)
6864               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6865             else
6866               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6867             LHSI->setOperand(1, NewAndCST);
6868             LHSI->setOperand(0, Shift->getOperand(0));
6869             AddToWorkList(Shift); // Shift is dead.
6870             AddUsesToWorkList(ICI);
6871             return &ICI;
6872           }
6873         }
6874       }
6875       
6876       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6877       // preferable because it allows the C<<Y expression to be hoisted out
6878       // of a loop if Y is invariant and X is not.
6879       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6880           ICI.isEquality() && !Shift->isArithmeticShift() &&
6881           !isa<Constant>(Shift->getOperand(0))) {
6882         // Compute C << Y.
6883         Value *NS;
6884         if (Shift->getOpcode() == Instruction::LShr) {
6885           NS = BinaryOperator::CreateShl(AndCST, 
6886                                          Shift->getOperand(1), "tmp");
6887         } else {
6888           // Insert a logical shift.
6889           NS = BinaryOperator::CreateLShr(AndCST,
6890                                           Shift->getOperand(1), "tmp");
6891         }
6892         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6893         
6894         // Compute X & (C << Y).
6895         Instruction *NewAnd = 
6896           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6897         InsertNewInstBefore(NewAnd, ICI);
6898         
6899         ICI.setOperand(0, NewAnd);
6900         return &ICI;
6901       }
6902     }
6903     break;
6904     
6905   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6906     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6907     if (!ShAmt) break;
6908     
6909     uint32_t TypeBits = RHSV.getBitWidth();
6910     
6911     // Check that the shift amount is in range.  If not, don't perform
6912     // undefined shifts.  When the shift is visited it will be
6913     // simplified.
6914     if (ShAmt->uge(TypeBits))
6915       break;
6916     
6917     if (ICI.isEquality()) {
6918       // If we are comparing against bits always shifted out, the
6919       // comparison cannot succeed.
6920       Constant *Comp =
6921         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6922                                                                  ShAmt);
6923       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6924         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6925         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6926         return ReplaceInstUsesWith(ICI, Cst);
6927       }
6928       
6929       if (LHSI->hasOneUse()) {
6930         // Otherwise strength reduce the shift into an and.
6931         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6932         Constant *Mask =
6933           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6934                                                        TypeBits-ShAmtVal));
6935         
6936         Instruction *AndI =
6937           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6938                                     Mask, LHSI->getName()+".mask");
6939         Value *And = InsertNewInstBefore(AndI, ICI);
6940         return new ICmpInst(*Context, ICI.getPredicate(), And,
6941                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6942       }
6943     }
6944     
6945     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6946     bool TrueIfSigned = false;
6947     if (LHSI->hasOneUse() &&
6948         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6949       // (X << 31) <s 0  --> (X&1) != 0
6950       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6951                                            (TypeBits-ShAmt->getZExtValue()-1));
6952       Instruction *AndI =
6953         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6954                                   Mask, LHSI->getName()+".mask");
6955       Value *And = InsertNewInstBefore(AndI, ICI);
6956       
6957       return new ICmpInst(*Context,
6958                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6959                           And, Context->getNullValue(And->getType()));
6960     }
6961     break;
6962   }
6963     
6964   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6965   case Instruction::AShr: {
6966     // Only handle equality comparisons of shift-by-constant.
6967     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6968     if (!ShAmt || !ICI.isEquality()) break;
6969
6970     // Check that the shift amount is in range.  If not, don't perform
6971     // undefined shifts.  When the shift is visited it will be
6972     // simplified.
6973     uint32_t TypeBits = RHSV.getBitWidth();
6974     if (ShAmt->uge(TypeBits))
6975       break;
6976     
6977     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6978       
6979     // If we are comparing against bits always shifted out, the
6980     // comparison cannot succeed.
6981     APInt Comp = RHSV << ShAmtVal;
6982     if (LHSI->getOpcode() == Instruction::LShr)
6983       Comp = Comp.lshr(ShAmtVal);
6984     else
6985       Comp = Comp.ashr(ShAmtVal);
6986     
6987     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6988       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6989       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6990       return ReplaceInstUsesWith(ICI, Cst);
6991     }
6992     
6993     // Otherwise, check to see if the bits shifted out are known to be zero.
6994     // If so, we can compare against the unshifted value:
6995     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6996     if (LHSI->hasOneUse() &&
6997         MaskedValueIsZero(LHSI->getOperand(0), 
6998                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6999       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7000                           ConstantExpr::getShl(RHS, ShAmt));
7001     }
7002       
7003     if (LHSI->hasOneUse()) {
7004       // Otherwise strength reduce the shift into an and.
7005       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7006       Constant *Mask = ConstantInt::get(*Context, Val);
7007       
7008       Instruction *AndI =
7009         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7010                                   Mask, LHSI->getName()+".mask");
7011       Value *And = InsertNewInstBefore(AndI, ICI);
7012       return new ICmpInst(*Context, ICI.getPredicate(), And,
7013                           ConstantExpr::getShl(RHS, ShAmt));
7014     }
7015     break;
7016   }
7017     
7018   case Instruction::SDiv:
7019   case Instruction::UDiv:
7020     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7021     // Fold this div into the comparison, producing a range check. 
7022     // Determine, based on the divide type, what the range is being 
7023     // checked.  If there is an overflow on the low or high side, remember 
7024     // it, otherwise compute the range [low, hi) bounding the new value.
7025     // See: InsertRangeTest above for the kinds of replacements possible.
7026     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7027       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7028                                           DivRHS))
7029         return R;
7030     break;
7031
7032   case Instruction::Add:
7033     // Fold: icmp pred (add, X, C1), C2
7034
7035     if (!ICI.isEquality()) {
7036       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7037       if (!LHSC) break;
7038       const APInt &LHSV = LHSC->getValue();
7039
7040       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7041                             .subtract(LHSV);
7042
7043       if (ICI.isSignedPredicate()) {
7044         if (CR.getLower().isSignBit()) {
7045           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7046                               ConstantInt::get(*Context, CR.getUpper()));
7047         } else if (CR.getUpper().isSignBit()) {
7048           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7049                               ConstantInt::get(*Context, CR.getLower()));
7050         }
7051       } else {
7052         if (CR.getLower().isMinValue()) {
7053           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7054                               ConstantInt::get(*Context, CR.getUpper()));
7055         } else if (CR.getUpper().isMinValue()) {
7056           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7057                               ConstantInt::get(*Context, CR.getLower()));
7058         }
7059       }
7060     }
7061     break;
7062   }
7063   
7064   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7065   if (ICI.isEquality()) {
7066     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7067     
7068     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7069     // the second operand is a constant, simplify a bit.
7070     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7071       switch (BO->getOpcode()) {
7072       case Instruction::SRem:
7073         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7074         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7075           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7076           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7077             Instruction *NewRem =
7078               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7079                                          BO->getName());
7080             InsertNewInstBefore(NewRem, ICI);
7081             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7082                                 Context->getNullValue(BO->getType()));
7083           }
7084         }
7085         break;
7086       case Instruction::Add:
7087         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7088         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7089           if (BO->hasOneUse())
7090             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7091                                 ConstantExpr::getSub(RHS, BOp1C));
7092         } else if (RHSV == 0) {
7093           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7094           // efficiently invertible, or if the add has just this one use.
7095           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7096           
7097           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7098             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7099           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7100             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7101           else if (BO->hasOneUse()) {
7102             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7103             InsertNewInstBefore(Neg, ICI);
7104             Neg->takeName(BO);
7105             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7106           }
7107         }
7108         break;
7109       case Instruction::Xor:
7110         // For the xor case, we can xor two constants together, eliminating
7111         // the explicit xor.
7112         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7113           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7114                               ConstantExpr::getXor(RHS, BOC));
7115         
7116         // FALLTHROUGH
7117       case Instruction::Sub:
7118         // Replace (([sub|xor] A, B) != 0) with (A != B)
7119         if (RHSV == 0)
7120           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7121                               BO->getOperand(1));
7122         break;
7123         
7124       case Instruction::Or:
7125         // If bits are being or'd in that are not present in the constant we
7126         // are comparing against, then the comparison could never succeed!
7127         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7128           Constant *NotCI = ConstantExpr::getNot(RHS);
7129           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7130             return ReplaceInstUsesWith(ICI,
7131                                        ConstantInt::get(Type::Int1Ty, 
7132                                        isICMP_NE));
7133         }
7134         break;
7135         
7136       case Instruction::And:
7137         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7138           // If bits are being compared against that are and'd out, then the
7139           // comparison can never succeed!
7140           if ((RHSV & ~BOC->getValue()) != 0)
7141             return ReplaceInstUsesWith(ICI,
7142                                        ConstantInt::get(Type::Int1Ty,
7143                                        isICMP_NE));
7144           
7145           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7146           if (RHS == BOC && RHSV.isPowerOf2())
7147             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7148                                 ICmpInst::ICMP_NE, LHSI,
7149                                 Context->getNullValue(RHS->getType()));
7150           
7151           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7152           if (BOC->getValue().isSignBit()) {
7153             Value *X = BO->getOperand(0);
7154             Constant *Zero = Context->getNullValue(X->getType());
7155             ICmpInst::Predicate pred = isICMP_NE ? 
7156               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7157             return new ICmpInst(*Context, pred, X, Zero);
7158           }
7159           
7160           // ((X & ~7) == 0) --> X < 8
7161           if (RHSV == 0 && isHighOnes(BOC)) {
7162             Value *X = BO->getOperand(0);
7163             Constant *NegX = ConstantExpr::getNeg(BOC);
7164             ICmpInst::Predicate pred = isICMP_NE ? 
7165               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7166             return new ICmpInst(*Context, pred, X, NegX);
7167           }
7168         }
7169       default: break;
7170       }
7171     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7172       // Handle icmp {eq|ne} <intrinsic>, intcst.
7173       if (II->getIntrinsicID() == Intrinsic::bswap) {
7174         AddToWorkList(II);
7175         ICI.setOperand(0, II->getOperand(1));
7176         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7177         return &ICI;
7178       }
7179     }
7180   }
7181   return 0;
7182 }
7183
7184 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7185 /// We only handle extending casts so far.
7186 ///
7187 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7188   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7189   Value *LHSCIOp        = LHSCI->getOperand(0);
7190   const Type *SrcTy     = LHSCIOp->getType();
7191   const Type *DestTy    = LHSCI->getType();
7192   Value *RHSCIOp;
7193
7194   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7195   // integer type is the same size as the pointer type.
7196   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7197       TD->getPointerSizeInBits() ==
7198          cast<IntegerType>(DestTy)->getBitWidth()) {
7199     Value *RHSOp = 0;
7200     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7201       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7202     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7203       RHSOp = RHSC->getOperand(0);
7204       // If the pointer types don't match, insert a bitcast.
7205       if (LHSCIOp->getType() != RHSOp->getType())
7206         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7207     }
7208
7209     if (RHSOp)
7210       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7211   }
7212   
7213   // The code below only handles extension cast instructions, so far.
7214   // Enforce this.
7215   if (LHSCI->getOpcode() != Instruction::ZExt &&
7216       LHSCI->getOpcode() != Instruction::SExt)
7217     return 0;
7218
7219   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7220   bool isSignedCmp = ICI.isSignedPredicate();
7221
7222   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7223     // Not an extension from the same type?
7224     RHSCIOp = CI->getOperand(0);
7225     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7226       return 0;
7227     
7228     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7229     // and the other is a zext), then we can't handle this.
7230     if (CI->getOpcode() != LHSCI->getOpcode())
7231       return 0;
7232
7233     // Deal with equality cases early.
7234     if (ICI.isEquality())
7235       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7236
7237     // A signed comparison of sign extended values simplifies into a
7238     // signed comparison.
7239     if (isSignedCmp && isSignedExt)
7240       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7241
7242     // The other three cases all fold into an unsigned comparison.
7243     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7244   }
7245
7246   // If we aren't dealing with a constant on the RHS, exit early
7247   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7248   if (!CI)
7249     return 0;
7250
7251   // Compute the constant that would happen if we truncated to SrcTy then
7252   // reextended to DestTy.
7253   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7254   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7255                                                 Res1, DestTy);
7256
7257   // If the re-extended constant didn't change...
7258   if (Res2 == CI) {
7259     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7260     // For example, we might have:
7261     //    %A = sext i16 %X to i32
7262     //    %B = icmp ugt i32 %A, 1330
7263     // It is incorrect to transform this into 
7264     //    %B = icmp ugt i16 %X, 1330
7265     // because %A may have negative value. 
7266     //
7267     // However, we allow this when the compare is EQ/NE, because they are
7268     // signless.
7269     if (isSignedExt == isSignedCmp || ICI.isEquality())
7270       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7271     return 0;
7272   }
7273
7274   // The re-extended constant changed so the constant cannot be represented 
7275   // in the shorter type. Consequently, we cannot emit a simple comparison.
7276
7277   // First, handle some easy cases. We know the result cannot be equal at this
7278   // point so handle the ICI.isEquality() cases
7279   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7280     return ReplaceInstUsesWith(ICI, Context->getFalse());
7281   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7282     return ReplaceInstUsesWith(ICI, Context->getTrue());
7283
7284   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7285   // should have been folded away previously and not enter in here.
7286   Value *Result;
7287   if (isSignedCmp) {
7288     // We're performing a signed comparison.
7289     if (cast<ConstantInt>(CI)->getValue().isNegative())
7290       Result = Context->getFalse();          // X < (small) --> false
7291     else
7292       Result = Context->getTrue();           // X < (large) --> true
7293   } else {
7294     // We're performing an unsigned comparison.
7295     if (isSignedExt) {
7296       // We're performing an unsigned comp with a sign extended value.
7297       // This is true if the input is >= 0. [aka >s -1]
7298       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7299       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7300                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7301     } else {
7302       // Unsigned extend & unsigned compare -> always true.
7303       Result = Context->getTrue();
7304     }
7305   }
7306
7307   // Finally, return the value computed.
7308   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7309       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7310     return ReplaceInstUsesWith(ICI, Result);
7311
7312   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7313           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7314          "ICmp should be folded!");
7315   if (Constant *CI = dyn_cast<Constant>(Result))
7316     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7317   return BinaryOperator::CreateNot(*Context, Result);
7318 }
7319
7320 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7321   return commonShiftTransforms(I);
7322 }
7323
7324 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7325   return commonShiftTransforms(I);
7326 }
7327
7328 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7329   if (Instruction *R = commonShiftTransforms(I))
7330     return R;
7331   
7332   Value *Op0 = I.getOperand(0);
7333   
7334   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7335   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7336     if (CSI->isAllOnesValue())
7337       return ReplaceInstUsesWith(I, CSI);
7338
7339   // See if we can turn a signed shr into an unsigned shr.
7340   if (MaskedValueIsZero(Op0,
7341                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7342     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7343
7344   // Arithmetic shifting an all-sign-bit value is a no-op.
7345   unsigned NumSignBits = ComputeNumSignBits(Op0);
7346   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7347     return ReplaceInstUsesWith(I, Op0);
7348
7349   return 0;
7350 }
7351
7352 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7353   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7354   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7355
7356   // shl X, 0 == X and shr X, 0 == X
7357   // shl 0, X == 0 and shr 0, X == 0
7358   if (Op1 == Context->getNullValue(Op1->getType()) ||
7359       Op0 == Context->getNullValue(Op0->getType()))
7360     return ReplaceInstUsesWith(I, Op0);
7361   
7362   if (isa<UndefValue>(Op0)) {            
7363     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7364       return ReplaceInstUsesWith(I, Op0);
7365     else                                    // undef << X -> 0, undef >>u X -> 0
7366       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7367   }
7368   if (isa<UndefValue>(Op1)) {
7369     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7370       return ReplaceInstUsesWith(I, Op0);          
7371     else                                     // X << undef, X >>u undef -> 0
7372       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7373   }
7374
7375   // See if we can fold away this shift.
7376   if (SimplifyDemandedInstructionBits(I))
7377     return &I;
7378
7379   // Try to fold constant and into select arguments.
7380   if (isa<Constant>(Op0))
7381     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7382       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7383         return R;
7384
7385   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7386     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7387       return Res;
7388   return 0;
7389 }
7390
7391 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7392                                                BinaryOperator &I) {
7393   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7394
7395   // See if we can simplify any instructions used by the instruction whose sole 
7396   // purpose is to compute bits we don't care about.
7397   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7398   
7399   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7400   // a signed shift.
7401   //
7402   if (Op1->uge(TypeBits)) {
7403     if (I.getOpcode() != Instruction::AShr)
7404       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7405     else {
7406       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7407       return &I;
7408     }
7409   }
7410   
7411   // ((X*C1) << C2) == (X * (C1 << C2))
7412   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7413     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7414       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7415         return BinaryOperator::CreateMul(BO->getOperand(0),
7416                                         ConstantExpr::getShl(BOOp, Op1));
7417   
7418   // Try to fold constant and into select arguments.
7419   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7420     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7421       return R;
7422   if (isa<PHINode>(Op0))
7423     if (Instruction *NV = FoldOpIntoPhi(I))
7424       return NV;
7425   
7426   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7427   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7428     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7429     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7430     // place.  Don't try to do this transformation in this case.  Also, we
7431     // require that the input operand is a shift-by-constant so that we have
7432     // confidence that the shifts will get folded together.  We could do this
7433     // xform in more cases, but it is unlikely to be profitable.
7434     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7435         isa<ConstantInt>(TrOp->getOperand(1))) {
7436       // Okay, we'll do this xform.  Make the shift of shift.
7437       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7438       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7439                                                 I.getName());
7440       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7441
7442       // For logical shifts, the truncation has the effect of making the high
7443       // part of the register be zeros.  Emulate this by inserting an AND to
7444       // clear the top bits as needed.  This 'and' will usually be zapped by
7445       // other xforms later if dead.
7446       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7447       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7448       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7449       
7450       // The mask we constructed says what the trunc would do if occurring
7451       // between the shifts.  We want to know the effect *after* the second
7452       // shift.  We know that it is a logical shift by a constant, so adjust the
7453       // mask as appropriate.
7454       if (I.getOpcode() == Instruction::Shl)
7455         MaskV <<= Op1->getZExtValue();
7456       else {
7457         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7458         MaskV = MaskV.lshr(Op1->getZExtValue());
7459       }
7460
7461       Instruction *And =
7462         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7463                                   TI->getName());
7464       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7465
7466       // Return the value truncated to the interesting size.
7467       return new TruncInst(And, I.getType());
7468     }
7469   }
7470   
7471   if (Op0->hasOneUse()) {
7472     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7473       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7474       Value *V1, *V2;
7475       ConstantInt *CC;
7476       switch (Op0BO->getOpcode()) {
7477         default: break;
7478         case Instruction::Add:
7479         case Instruction::And:
7480         case Instruction::Or:
7481         case Instruction::Xor: {
7482           // These operators commute.
7483           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7484           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7485               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7486                     m_Specific(Op1)), *Context)){
7487             Instruction *YS = BinaryOperator::CreateShl(
7488                                             Op0BO->getOperand(0), Op1,
7489                                             Op0BO->getName());
7490             InsertNewInstBefore(YS, I); // (Y << C)
7491             Instruction *X = 
7492               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7493                                      Op0BO->getOperand(1)->getName());
7494             InsertNewInstBefore(X, I);  // (X + (Y << C))
7495             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7496             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7497                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7498           }
7499           
7500           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7501           Value *Op0BOOp1 = Op0BO->getOperand(1);
7502           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7503               match(Op0BOOp1, 
7504                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7505                           m_ConstantInt(CC)), *Context) &&
7506               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7507             Instruction *YS = BinaryOperator::CreateShl(
7508                                                      Op0BO->getOperand(0), Op1,
7509                                                      Op0BO->getName());
7510             InsertNewInstBefore(YS, I); // (Y << C)
7511             Instruction *XM =
7512               BinaryOperator::CreateAnd(V1,
7513                                         ConstantExpr::getShl(CC, Op1),
7514                                         V1->getName()+".mask");
7515             InsertNewInstBefore(XM, I); // X & (CC << C)
7516             
7517             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7518           }
7519         }
7520           
7521         // FALL THROUGH.
7522         case Instruction::Sub: {
7523           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7524           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7525               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7526                     m_Specific(Op1)), *Context)){
7527             Instruction *YS = BinaryOperator::CreateShl(
7528                                                      Op0BO->getOperand(1), Op1,
7529                                                      Op0BO->getName());
7530             InsertNewInstBefore(YS, I); // (Y << C)
7531             Instruction *X =
7532               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7533                                      Op0BO->getOperand(0)->getName());
7534             InsertNewInstBefore(X, I);  // (X + (Y << C))
7535             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7536             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7537                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7538           }
7539           
7540           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7541           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7542               match(Op0BO->getOperand(0),
7543                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7544                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7545               cast<BinaryOperator>(Op0BO->getOperand(0))
7546                   ->getOperand(0)->hasOneUse()) {
7547             Instruction *YS = BinaryOperator::CreateShl(
7548                                                      Op0BO->getOperand(1), Op1,
7549                                                      Op0BO->getName());
7550             InsertNewInstBefore(YS, I); // (Y << C)
7551             Instruction *XM =
7552               BinaryOperator::CreateAnd(V1, 
7553                                         ConstantExpr::getShl(CC, Op1),
7554                                         V1->getName()+".mask");
7555             InsertNewInstBefore(XM, I); // X & (CC << C)
7556             
7557             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7558           }
7559           
7560           break;
7561         }
7562       }
7563       
7564       
7565       // If the operand is an bitwise operator with a constant RHS, and the
7566       // shift is the only use, we can pull it out of the shift.
7567       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7568         bool isValid = true;     // Valid only for And, Or, Xor
7569         bool highBitSet = false; // Transform if high bit of constant set?
7570         
7571         switch (Op0BO->getOpcode()) {
7572           default: isValid = false; break;   // Do not perform transform!
7573           case Instruction::Add:
7574             isValid = isLeftShift;
7575             break;
7576           case Instruction::Or:
7577           case Instruction::Xor:
7578             highBitSet = false;
7579             break;
7580           case Instruction::And:
7581             highBitSet = true;
7582             break;
7583         }
7584         
7585         // If this is a signed shift right, and the high bit is modified
7586         // by the logical operation, do not perform the transformation.
7587         // The highBitSet boolean indicates the value of the high bit of
7588         // the constant which would cause it to be modified for this
7589         // operation.
7590         //
7591         if (isValid && I.getOpcode() == Instruction::AShr)
7592           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7593         
7594         if (isValid) {
7595           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7596           
7597           Instruction *NewShift =
7598             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7599           InsertNewInstBefore(NewShift, I);
7600           NewShift->takeName(Op0BO);
7601           
7602           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7603                                         NewRHS);
7604         }
7605       }
7606     }
7607   }
7608   
7609   // Find out if this is a shift of a shift by a constant.
7610   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7611   if (ShiftOp && !ShiftOp->isShift())
7612     ShiftOp = 0;
7613   
7614   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7615     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7616     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7617     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7618     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7619     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7620     Value *X = ShiftOp->getOperand(0);
7621     
7622     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7623     
7624     const IntegerType *Ty = cast<IntegerType>(I.getType());
7625     
7626     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7627     if (I.getOpcode() == ShiftOp->getOpcode()) {
7628       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7629       // saturates.
7630       if (AmtSum >= TypeBits) {
7631         if (I.getOpcode() != Instruction::AShr)
7632           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7633         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7634       }
7635       
7636       return BinaryOperator::Create(I.getOpcode(), X,
7637                                     ConstantInt::get(Ty, AmtSum));
7638     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7639                I.getOpcode() == Instruction::AShr) {
7640       if (AmtSum >= TypeBits)
7641         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7642       
7643       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7644       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7645     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7646                I.getOpcode() == Instruction::LShr) {
7647       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7648       if (AmtSum >= TypeBits)
7649         AmtSum = TypeBits-1;
7650       
7651       Instruction *Shift =
7652         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7653       InsertNewInstBefore(Shift, I);
7654
7655       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7656       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7657     }
7658     
7659     // Okay, if we get here, one shift must be left, and the other shift must be
7660     // right.  See if the amounts are equal.
7661     if (ShiftAmt1 == ShiftAmt2) {
7662       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7663       if (I.getOpcode() == Instruction::Shl) {
7664         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7665         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7666       }
7667       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7668       if (I.getOpcode() == Instruction::LShr) {
7669         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7670         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7671       }
7672       // We can simplify ((X << C) >>s C) into a trunc + sext.
7673       // NOTE: we could do this for any C, but that would make 'unusual' integer
7674       // types.  For now, just stick to ones well-supported by the code
7675       // generators.
7676       const Type *SExtType = 0;
7677       switch (Ty->getBitWidth() - ShiftAmt1) {
7678       case 1  :
7679       case 8  :
7680       case 16 :
7681       case 32 :
7682       case 64 :
7683       case 128:
7684         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7685         break;
7686       default: break;
7687       }
7688       if (SExtType) {
7689         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7690         InsertNewInstBefore(NewTrunc, I);
7691         return new SExtInst(NewTrunc, Ty);
7692       }
7693       // Otherwise, we can't handle it yet.
7694     } else if (ShiftAmt1 < ShiftAmt2) {
7695       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7696       
7697       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7698       if (I.getOpcode() == Instruction::Shl) {
7699         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7700                ShiftOp->getOpcode() == Instruction::AShr);
7701         Instruction *Shift =
7702           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7703         InsertNewInstBefore(Shift, I);
7704         
7705         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7706         return BinaryOperator::CreateAnd(Shift,
7707                                          ConstantInt::get(*Context, Mask));
7708       }
7709       
7710       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7711       if (I.getOpcode() == Instruction::LShr) {
7712         assert(ShiftOp->getOpcode() == Instruction::Shl);
7713         Instruction *Shift =
7714           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7715         InsertNewInstBefore(Shift, I);
7716         
7717         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7718         return BinaryOperator::CreateAnd(Shift,
7719                                          ConstantInt::get(*Context, Mask));
7720       }
7721       
7722       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7723     } else {
7724       assert(ShiftAmt2 < ShiftAmt1);
7725       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7726
7727       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7728       if (I.getOpcode() == Instruction::Shl) {
7729         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7730                ShiftOp->getOpcode() == Instruction::AShr);
7731         Instruction *Shift =
7732           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7733                                  ConstantInt::get(Ty, ShiftDiff));
7734         InsertNewInstBefore(Shift, I);
7735         
7736         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7737         return BinaryOperator::CreateAnd(Shift,
7738                                          ConstantInt::get(*Context, Mask));
7739       }
7740       
7741       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7742       if (I.getOpcode() == Instruction::LShr) {
7743         assert(ShiftOp->getOpcode() == Instruction::Shl);
7744         Instruction *Shift =
7745           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7746         InsertNewInstBefore(Shift, I);
7747         
7748         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7749         return BinaryOperator::CreateAnd(Shift,
7750                                          ConstantInt::get(*Context, Mask));
7751       }
7752       
7753       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7754     }
7755   }
7756   return 0;
7757 }
7758
7759
7760 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7761 /// expression.  If so, decompose it, returning some value X, such that Val is
7762 /// X*Scale+Offset.
7763 ///
7764 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7765                                         int &Offset, LLVMContext *Context) {
7766   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7767   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7768     Offset = CI->getZExtValue();
7769     Scale  = 0;
7770     return ConstantInt::get(Type::Int32Ty, 0);
7771   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7772     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7773       if (I->getOpcode() == Instruction::Shl) {
7774         // This is a value scaled by '1 << the shift amt'.
7775         Scale = 1U << RHS->getZExtValue();
7776         Offset = 0;
7777         return I->getOperand(0);
7778       } else if (I->getOpcode() == Instruction::Mul) {
7779         // This value is scaled by 'RHS'.
7780         Scale = RHS->getZExtValue();
7781         Offset = 0;
7782         return I->getOperand(0);
7783       } else if (I->getOpcode() == Instruction::Add) {
7784         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7785         // where C1 is divisible by C2.
7786         unsigned SubScale;
7787         Value *SubVal = 
7788           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7789                                     Offset, Context);
7790         Offset += RHS->getZExtValue();
7791         Scale = SubScale;
7792         return SubVal;
7793       }
7794     }
7795   }
7796
7797   // Otherwise, we can't look past this.
7798   Scale = 1;
7799   Offset = 0;
7800   return Val;
7801 }
7802
7803
7804 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7805 /// try to eliminate the cast by moving the type information into the alloc.
7806 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7807                                                    AllocationInst &AI) {
7808   const PointerType *PTy = cast<PointerType>(CI.getType());
7809   
7810   // Remove any uses of AI that are dead.
7811   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7812   
7813   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7814     Instruction *User = cast<Instruction>(*UI++);
7815     if (isInstructionTriviallyDead(User)) {
7816       while (UI != E && *UI == User)
7817         ++UI; // If this instruction uses AI more than once, don't break UI.
7818       
7819       ++NumDeadInst;
7820       DOUT << "IC: DCE: " << *User;
7821       EraseInstFromFunction(*User);
7822     }
7823   }
7824
7825   // This requires TargetData to get the alloca alignment and size information.
7826   if (!TD) return 0;
7827
7828   // Get the type really allocated and the type casted to.
7829   const Type *AllocElTy = AI.getAllocatedType();
7830   const Type *CastElTy = PTy->getElementType();
7831   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7832
7833   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7834   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7835   if (CastElTyAlign < AllocElTyAlign) return 0;
7836
7837   // If the allocation has multiple uses, only promote it if we are strictly
7838   // increasing the alignment of the resultant allocation.  If we keep it the
7839   // same, we open the door to infinite loops of various kinds.  (A reference
7840   // from a dbg.declare doesn't count as a use for this purpose.)
7841   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7842       CastElTyAlign == AllocElTyAlign) return 0;
7843
7844   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7845   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7846   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7847
7848   // See if we can satisfy the modulus by pulling a scale out of the array
7849   // size argument.
7850   unsigned ArraySizeScale;
7851   int ArrayOffset;
7852   Value *NumElements = // See if the array size is a decomposable linear expr.
7853     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7854                               ArrayOffset, Context);
7855  
7856   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7857   // do the xform.
7858   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7859       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7860
7861   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7862   Value *Amt = 0;
7863   if (Scale == 1) {
7864     Amt = NumElements;
7865   } else {
7866     // If the allocation size is constant, form a constant mul expression
7867     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7868     if (isa<ConstantInt>(NumElements))
7869       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7870                                  cast<ConstantInt>(Amt));
7871     // otherwise multiply the amount and the number of elements
7872     else {
7873       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7874       Amt = InsertNewInstBefore(Tmp, AI);
7875     }
7876   }
7877   
7878   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7879     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7880     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7881     Amt = InsertNewInstBefore(Tmp, AI);
7882   }
7883   
7884   AllocationInst *New;
7885   if (isa<MallocInst>(AI))
7886     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7887   else
7888     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7889   InsertNewInstBefore(New, AI);
7890   New->takeName(&AI);
7891   
7892   // If the allocation has one real use plus a dbg.declare, just remove the
7893   // declare.
7894   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7895     EraseInstFromFunction(*DI);
7896   }
7897   // If the allocation has multiple real uses, insert a cast and change all
7898   // things that used it to use the new cast.  This will also hack on CI, but it
7899   // will die soon.
7900   else if (!AI.hasOneUse()) {
7901     AddUsesToWorkList(AI);
7902     // New is the allocation instruction, pointer typed. AI is the original
7903     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7904     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7905     InsertNewInstBefore(NewCast, AI);
7906     AI.replaceAllUsesWith(NewCast);
7907   }
7908   return ReplaceInstUsesWith(CI, New);
7909 }
7910
7911 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7912 /// and return it as type Ty without inserting any new casts and without
7913 /// changing the computed value.  This is used by code that tries to decide
7914 /// whether promoting or shrinking integer operations to wider or smaller types
7915 /// will allow us to eliminate a truncate or extend.
7916 ///
7917 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7918 /// extension operation if Ty is larger.
7919 ///
7920 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7921 /// should return true if trunc(V) can be computed by computing V in the smaller
7922 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7923 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7924 /// efficiently truncated.
7925 ///
7926 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7927 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7928 /// the final result.
7929 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7930                                               unsigned CastOpc,
7931                                               int &NumCastsRemoved){
7932   // We can always evaluate constants in another type.
7933   if (isa<Constant>(V))
7934     return true;
7935   
7936   Instruction *I = dyn_cast<Instruction>(V);
7937   if (!I) return false;
7938   
7939   const Type *OrigTy = V->getType();
7940   
7941   // If this is an extension or truncate, we can often eliminate it.
7942   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7943     // If this is a cast from the destination type, we can trivially eliminate
7944     // it, and this will remove a cast overall.
7945     if (I->getOperand(0)->getType() == Ty) {
7946       // If the first operand is itself a cast, and is eliminable, do not count
7947       // this as an eliminable cast.  We would prefer to eliminate those two
7948       // casts first.
7949       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7950         ++NumCastsRemoved;
7951       return true;
7952     }
7953   }
7954
7955   // We can't extend or shrink something that has multiple uses: doing so would
7956   // require duplicating the instruction in general, which isn't profitable.
7957   if (!I->hasOneUse()) return false;
7958
7959   unsigned Opc = I->getOpcode();
7960   switch (Opc) {
7961   case Instruction::Add:
7962   case Instruction::Sub:
7963   case Instruction::Mul:
7964   case Instruction::And:
7965   case Instruction::Or:
7966   case Instruction::Xor:
7967     // These operators can all arbitrarily be extended or truncated.
7968     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7969                                       NumCastsRemoved) &&
7970            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7971                                       NumCastsRemoved);
7972
7973   case Instruction::UDiv:
7974   case Instruction::URem: {
7975     // UDiv and URem can be truncated if all the truncated bits are zero.
7976     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7977     uint32_t BitWidth = Ty->getScalarSizeInBits();
7978     if (BitWidth < OrigBitWidth) {
7979       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7980       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7981           MaskedValueIsZero(I->getOperand(1), Mask)) {
7982         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7983                                           NumCastsRemoved) &&
7984                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7985                                           NumCastsRemoved);
7986       }
7987     }
7988     break;
7989   }
7990   case Instruction::Shl:
7991     // If we are truncating the result of this SHL, and if it's a shift of a
7992     // constant amount, we can always perform a SHL in a smaller type.
7993     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7994       uint32_t BitWidth = Ty->getScalarSizeInBits();
7995       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7996           CI->getLimitedValue(BitWidth) < BitWidth)
7997         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7998                                           NumCastsRemoved);
7999     }
8000     break;
8001   case Instruction::LShr:
8002     // If this is a truncate of a logical shr, we can truncate it to a smaller
8003     // lshr iff we know that the bits we would otherwise be shifting in are
8004     // already zeros.
8005     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8006       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8007       uint32_t BitWidth = Ty->getScalarSizeInBits();
8008       if (BitWidth < OrigBitWidth &&
8009           MaskedValueIsZero(I->getOperand(0),
8010             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8011           CI->getLimitedValue(BitWidth) < BitWidth) {
8012         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8013                                           NumCastsRemoved);
8014       }
8015     }
8016     break;
8017   case Instruction::ZExt:
8018   case Instruction::SExt:
8019   case Instruction::Trunc:
8020     // If this is the same kind of case as our original (e.g. zext+zext), we
8021     // can safely replace it.  Note that replacing it does not reduce the number
8022     // of casts in the input.
8023     if (Opc == CastOpc)
8024       return true;
8025
8026     // sext (zext ty1), ty2 -> zext ty2
8027     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8028       return true;
8029     break;
8030   case Instruction::Select: {
8031     SelectInst *SI = cast<SelectInst>(I);
8032     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8033                                       NumCastsRemoved) &&
8034            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8035                                       NumCastsRemoved);
8036   }
8037   case Instruction::PHI: {
8038     // We can change a phi if we can change all operands.
8039     PHINode *PN = cast<PHINode>(I);
8040     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8041       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8042                                       NumCastsRemoved))
8043         return false;
8044     return true;
8045   }
8046   default:
8047     // TODO: Can handle more cases here.
8048     break;
8049   }
8050   
8051   return false;
8052 }
8053
8054 /// EvaluateInDifferentType - Given an expression that 
8055 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8056 /// evaluate the expression.
8057 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8058                                              bool isSigned) {
8059   if (Constant *C = dyn_cast<Constant>(V))
8060     return ConstantExpr::getIntegerCast(C, Ty,
8061                                                isSigned /*Sext or ZExt*/);
8062
8063   // Otherwise, it must be an instruction.
8064   Instruction *I = cast<Instruction>(V);
8065   Instruction *Res = 0;
8066   unsigned Opc = I->getOpcode();
8067   switch (Opc) {
8068   case Instruction::Add:
8069   case Instruction::Sub:
8070   case Instruction::Mul:
8071   case Instruction::And:
8072   case Instruction::Or:
8073   case Instruction::Xor:
8074   case Instruction::AShr:
8075   case Instruction::LShr:
8076   case Instruction::Shl:
8077   case Instruction::UDiv:
8078   case Instruction::URem: {
8079     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8080     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8081     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8082     break;
8083   }    
8084   case Instruction::Trunc:
8085   case Instruction::ZExt:
8086   case Instruction::SExt:
8087     // If the source type of the cast is the type we're trying for then we can
8088     // just return the source.  There's no need to insert it because it is not
8089     // new.
8090     if (I->getOperand(0)->getType() == Ty)
8091       return I->getOperand(0);
8092     
8093     // Otherwise, must be the same type of cast, so just reinsert a new one.
8094     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8095                            Ty);
8096     break;
8097   case Instruction::Select: {
8098     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8099     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8100     Res = SelectInst::Create(I->getOperand(0), True, False);
8101     break;
8102   }
8103   case Instruction::PHI: {
8104     PHINode *OPN = cast<PHINode>(I);
8105     PHINode *NPN = PHINode::Create(Ty);
8106     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8107       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8108       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8109     }
8110     Res = NPN;
8111     break;
8112   }
8113   default: 
8114     // TODO: Can handle more cases here.
8115     llvm_unreachable("Unreachable!");
8116     break;
8117   }
8118   
8119   Res->takeName(I);
8120   return InsertNewInstBefore(Res, *I);
8121 }
8122
8123 /// @brief Implement the transforms common to all CastInst visitors.
8124 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8125   Value *Src = CI.getOperand(0);
8126
8127   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8128   // eliminate it now.
8129   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8130     if (Instruction::CastOps opc = 
8131         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8132       // The first cast (CSrc) is eliminable so we need to fix up or replace
8133       // the second cast (CI). CSrc will then have a good chance of being dead.
8134       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8135     }
8136   }
8137
8138   // If we are casting a select then fold the cast into the select
8139   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8140     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8141       return NV;
8142
8143   // If we are casting a PHI then fold the cast into the PHI
8144   if (isa<PHINode>(Src))
8145     if (Instruction *NV = FoldOpIntoPhi(CI))
8146       return NV;
8147   
8148   return 0;
8149 }
8150
8151 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8152 /// or not there is a sequence of GEP indices into the type that will land us at
8153 /// the specified offset.  If so, fill them into NewIndices and return the
8154 /// resultant element type, otherwise return null.
8155 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8156                                        SmallVectorImpl<Value*> &NewIndices,
8157                                        const TargetData *TD,
8158                                        LLVMContext *Context) {
8159   if (!TD) return 0;
8160   if (!Ty->isSized()) return 0;
8161   
8162   // Start with the index over the outer type.  Note that the type size
8163   // might be zero (even if the offset isn't zero) if the indexed type
8164   // is something like [0 x {int, int}]
8165   const Type *IntPtrTy = TD->getIntPtrType();
8166   int64_t FirstIdx = 0;
8167   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8168     FirstIdx = Offset/TySize;
8169     Offset -= FirstIdx*TySize;
8170     
8171     // Handle hosts where % returns negative instead of values [0..TySize).
8172     if (Offset < 0) {
8173       --FirstIdx;
8174       Offset += TySize;
8175       assert(Offset >= 0);
8176     }
8177     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8178   }
8179   
8180   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8181     
8182   // Index into the types.  If we fail, set OrigBase to null.
8183   while (Offset) {
8184     // Indexing into tail padding between struct/array elements.
8185     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8186       return 0;
8187     
8188     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8189       const StructLayout *SL = TD->getStructLayout(STy);
8190       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8191              "Offset must stay within the indexed type");
8192       
8193       unsigned Elt = SL->getElementContainingOffset(Offset);
8194       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8195       
8196       Offset -= SL->getElementOffset(Elt);
8197       Ty = STy->getElementType(Elt);
8198     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8199       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8200       assert(EltSize && "Cannot index into a zero-sized array");
8201       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8202       Offset %= EltSize;
8203       Ty = AT->getElementType();
8204     } else {
8205       // Otherwise, we can't index into the middle of this atomic type, bail.
8206       return 0;
8207     }
8208   }
8209   
8210   return Ty;
8211 }
8212
8213 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8214 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8215   Value *Src = CI.getOperand(0);
8216   
8217   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8218     // If casting the result of a getelementptr instruction with no offset, turn
8219     // this into a cast of the original pointer!
8220     if (GEP->hasAllZeroIndices()) {
8221       // Changing the cast operand is usually not a good idea but it is safe
8222       // here because the pointer operand is being replaced with another 
8223       // pointer operand so the opcode doesn't need to change.
8224       AddToWorkList(GEP);
8225       CI.setOperand(0, GEP->getOperand(0));
8226       return &CI;
8227     }
8228     
8229     // If the GEP has a single use, and the base pointer is a bitcast, and the
8230     // GEP computes a constant offset, see if we can convert these three
8231     // instructions into fewer.  This typically happens with unions and other
8232     // non-type-safe code.
8233     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8234       if (GEP->hasAllConstantIndices()) {
8235         // We are guaranteed to get a constant from EmitGEPOffset.
8236         ConstantInt *OffsetV =
8237                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8238         int64_t Offset = OffsetV->getSExtValue();
8239         
8240         // Get the base pointer input of the bitcast, and the type it points to.
8241         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8242         const Type *GEPIdxTy =
8243           cast<PointerType>(OrigBase->getType())->getElementType();
8244         SmallVector<Value*, 8> NewIndices;
8245         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8246           // If we were able to index down into an element, create the GEP
8247           // and bitcast the result.  This eliminates one bitcast, potentially
8248           // two.
8249           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8250                                                         NewIndices.begin(),
8251                                                         NewIndices.end(), "");
8252           InsertNewInstBefore(NGEP, CI);
8253           NGEP->takeName(GEP);
8254           if (cast<GEPOperator>(GEP)->isInBounds())
8255             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8256           
8257           if (isa<BitCastInst>(CI))
8258             return new BitCastInst(NGEP, CI.getType());
8259           assert(isa<PtrToIntInst>(CI));
8260           return new PtrToIntInst(NGEP, CI.getType());
8261         }
8262       }      
8263     }
8264   }
8265     
8266   return commonCastTransforms(CI);
8267 }
8268
8269 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8270 /// type like i42.  We don't want to introduce operations on random non-legal
8271 /// integer types where they don't already exist in the code.  In the future,
8272 /// we should consider making this based off target-data, so that 32-bit targets
8273 /// won't get i64 operations etc.
8274 static bool isSafeIntegerType(const Type *Ty) {
8275   switch (Ty->getPrimitiveSizeInBits()) {
8276   case 8:
8277   case 16:
8278   case 32:
8279   case 64:
8280     return true;
8281   default: 
8282     return false;
8283   }
8284 }
8285
8286 /// commonIntCastTransforms - This function implements the common transforms
8287 /// for trunc, zext, and sext.
8288 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8289   if (Instruction *Result = commonCastTransforms(CI))
8290     return Result;
8291
8292   Value *Src = CI.getOperand(0);
8293   const Type *SrcTy = Src->getType();
8294   const Type *DestTy = CI.getType();
8295   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8296   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8297
8298   // See if we can simplify any instructions used by the LHS whose sole 
8299   // purpose is to compute bits we don't care about.
8300   if (SimplifyDemandedInstructionBits(CI))
8301     return &CI;
8302
8303   // If the source isn't an instruction or has more than one use then we
8304   // can't do anything more. 
8305   Instruction *SrcI = dyn_cast<Instruction>(Src);
8306   if (!SrcI || !Src->hasOneUse())
8307     return 0;
8308
8309   // Attempt to propagate the cast into the instruction for int->int casts.
8310   int NumCastsRemoved = 0;
8311   // Only do this if the dest type is a simple type, don't convert the
8312   // expression tree to something weird like i93 unless the source is also
8313   // strange.
8314   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8315        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8316       CanEvaluateInDifferentType(SrcI, DestTy,
8317                                  CI.getOpcode(), NumCastsRemoved)) {
8318     // If this cast is a truncate, evaluting in a different type always
8319     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8320     // we need to do an AND to maintain the clear top-part of the computation,
8321     // so we require that the input have eliminated at least one cast.  If this
8322     // is a sign extension, we insert two new casts (to do the extension) so we
8323     // require that two casts have been eliminated.
8324     bool DoXForm = false;
8325     bool JustReplace = false;
8326     switch (CI.getOpcode()) {
8327     default:
8328       // All the others use floating point so we shouldn't actually 
8329       // get here because of the check above.
8330       llvm_unreachable("Unknown cast type");
8331     case Instruction::Trunc:
8332       DoXForm = true;
8333       break;
8334     case Instruction::ZExt: {
8335       DoXForm = NumCastsRemoved >= 1;
8336       if (!DoXForm && 0) {
8337         // If it's unnecessary to issue an AND to clear the high bits, it's
8338         // always profitable to do this xform.
8339         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8340         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8341         if (MaskedValueIsZero(TryRes, Mask))
8342           return ReplaceInstUsesWith(CI, TryRes);
8343         
8344         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8345           if (TryI->use_empty())
8346             EraseInstFromFunction(*TryI);
8347       }
8348       break;
8349     }
8350     case Instruction::SExt: {
8351       DoXForm = NumCastsRemoved >= 2;
8352       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8353         // If we do not have to emit the truncate + sext pair, then it's always
8354         // profitable to do this xform.
8355         //
8356         // It's not safe to eliminate the trunc + sext pair if one of the
8357         // eliminated cast is a truncate. e.g.
8358         // t2 = trunc i32 t1 to i16
8359         // t3 = sext i16 t2 to i32
8360         // !=
8361         // i32 t1
8362         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8363         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8364         if (NumSignBits > (DestBitSize - SrcBitSize))
8365           return ReplaceInstUsesWith(CI, TryRes);
8366         
8367         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8368           if (TryI->use_empty())
8369             EraseInstFromFunction(*TryI);
8370       }
8371       break;
8372     }
8373     }
8374     
8375     if (DoXForm) {
8376       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8377            << " cast: " << CI;
8378       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8379                                            CI.getOpcode() == Instruction::SExt);
8380       if (JustReplace)
8381         // Just replace this cast with the result.
8382         return ReplaceInstUsesWith(CI, Res);
8383
8384       assert(Res->getType() == DestTy);
8385       switch (CI.getOpcode()) {
8386       default: llvm_unreachable("Unknown cast type!");
8387       case Instruction::Trunc:
8388         // Just replace this cast with the result.
8389         return ReplaceInstUsesWith(CI, Res);
8390       case Instruction::ZExt: {
8391         assert(SrcBitSize < DestBitSize && "Not a zext?");
8392
8393         // If the high bits are already zero, just replace this cast with the
8394         // result.
8395         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8396         if (MaskedValueIsZero(Res, Mask))
8397           return ReplaceInstUsesWith(CI, Res);
8398
8399         // We need to emit an AND to clear the high bits.
8400         Constant *C = ConstantInt::get(*Context, 
8401                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8402         return BinaryOperator::CreateAnd(Res, C);
8403       }
8404       case Instruction::SExt: {
8405         // If the high bits are already filled with sign bit, just replace this
8406         // cast with the result.
8407         unsigned NumSignBits = ComputeNumSignBits(Res);
8408         if (NumSignBits > (DestBitSize - SrcBitSize))
8409           return ReplaceInstUsesWith(CI, Res);
8410
8411         // We need to emit a cast to truncate, then a cast to sext.
8412         return CastInst::Create(Instruction::SExt,
8413             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8414                              CI), DestTy);
8415       }
8416       }
8417     }
8418   }
8419   
8420   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8421   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8422
8423   switch (SrcI->getOpcode()) {
8424   case Instruction::Add:
8425   case Instruction::Mul:
8426   case Instruction::And:
8427   case Instruction::Or:
8428   case Instruction::Xor:
8429     // If we are discarding information, rewrite.
8430     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8431       // Don't insert two casts unless at least one can be eliminated.
8432       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8433           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8434         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8435         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8436         return BinaryOperator::Create(
8437             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8438       }
8439     }
8440
8441     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8442     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8443         SrcI->getOpcode() == Instruction::Xor &&
8444         Op1 == Context->getTrue() &&
8445         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8446       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8447       return BinaryOperator::CreateXor(New,
8448                                       ConstantInt::get(CI.getType(), 1));
8449     }
8450     break;
8451
8452   case Instruction::Shl: {
8453     // Canonicalize trunc inside shl, if we can.
8454     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8455     if (CI && DestBitSize < SrcBitSize &&
8456         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8457       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8458       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8459       return BinaryOperator::CreateShl(Op0c, Op1c);
8460     }
8461     break;
8462   }
8463   }
8464   return 0;
8465 }
8466
8467 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8468   if (Instruction *Result = commonIntCastTransforms(CI))
8469     return Result;
8470   
8471   Value *Src = CI.getOperand(0);
8472   const Type *Ty = CI.getType();
8473   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8474   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8475
8476   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8477   if (DestBitWidth == 1) {
8478     Constant *One = ConstantInt::get(Src->getType(), 1);
8479     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8480     Value *Zero = Context->getNullValue(Src->getType());
8481     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8482   }
8483
8484   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8485   ConstantInt *ShAmtV = 0;
8486   Value *ShiftOp = 0;
8487   if (Src->hasOneUse() &&
8488       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8489     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8490     
8491     // Get a mask for the bits shifting in.
8492     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8493     if (MaskedValueIsZero(ShiftOp, Mask)) {
8494       if (ShAmt >= DestBitWidth)        // All zeros.
8495         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8496       
8497       // Okay, we can shrink this.  Truncate the input, then return a new
8498       // shift.
8499       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8500       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8501       return BinaryOperator::CreateLShr(V1, V2);
8502     }
8503   }
8504   
8505   return 0;
8506 }
8507
8508 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8509 /// in order to eliminate the icmp.
8510 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8511                                              bool DoXform) {
8512   // If we are just checking for a icmp eq of a single bit and zext'ing it
8513   // to an integer, then shift the bit to the appropriate place and then
8514   // cast to integer to avoid the comparison.
8515   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8516     const APInt &Op1CV = Op1C->getValue();
8517       
8518     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8519     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8520     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8521         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8522       if (!DoXform) return ICI;
8523
8524       Value *In = ICI->getOperand(0);
8525       Value *Sh = ConstantInt::get(In->getType(),
8526                                    In->getType()->getScalarSizeInBits()-1);
8527       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8528                                                         In->getName()+".lobit"),
8529                                CI);
8530       if (In->getType() != CI.getType())
8531         In = CastInst::CreateIntegerCast(In, CI.getType(),
8532                                          false/*ZExt*/, "tmp", &CI);
8533
8534       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8535         Constant *One = ConstantInt::get(In->getType(), 1);
8536         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8537                                                          In->getName()+".not"),
8538                                  CI);
8539       }
8540
8541       return ReplaceInstUsesWith(CI, In);
8542     }
8543       
8544       
8545       
8546     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8547     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8548     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8549     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8550     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8551     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8552     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8553     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8554     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8555         // This only works for EQ and NE
8556         ICI->isEquality()) {
8557       // If Op1C some other power of two, convert:
8558       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8559       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8560       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8561       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8562         
8563       APInt KnownZeroMask(~KnownZero);
8564       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8565         if (!DoXform) return ICI;
8566
8567         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8568         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8569           // (X&4) == 2 --> false
8570           // (X&4) != 2 --> true
8571           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8572           Res = ConstantExpr::getZExt(Res, CI.getType());
8573           return ReplaceInstUsesWith(CI, Res);
8574         }
8575           
8576         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8577         Value *In = ICI->getOperand(0);
8578         if (ShiftAmt) {
8579           // Perform a logical shr by shiftamt.
8580           // Insert the shift to put the result in the low bit.
8581           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8582                               ConstantInt::get(In->getType(), ShiftAmt),
8583                                                    In->getName()+".lobit"), CI);
8584         }
8585           
8586         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8587           Constant *One = ConstantInt::get(In->getType(), 1);
8588           In = BinaryOperator::CreateXor(In, One, "tmp");
8589           InsertNewInstBefore(cast<Instruction>(In), CI);
8590         }
8591           
8592         if (CI.getType() == In->getType())
8593           return ReplaceInstUsesWith(CI, In);
8594         else
8595           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8596       }
8597     }
8598   }
8599
8600   return 0;
8601 }
8602
8603 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8604   // If one of the common conversion will work ..
8605   if (Instruction *Result = commonIntCastTransforms(CI))
8606     return Result;
8607
8608   Value *Src = CI.getOperand(0);
8609
8610   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8611   // types and if the sizes are just right we can convert this into a logical
8612   // 'and' which will be much cheaper than the pair of casts.
8613   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8614     // Get the sizes of the types involved.  We know that the intermediate type
8615     // will be smaller than A or C, but don't know the relation between A and C.
8616     Value *A = CSrc->getOperand(0);
8617     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8618     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8619     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8620     // If we're actually extending zero bits, then if
8621     // SrcSize <  DstSize: zext(a & mask)
8622     // SrcSize == DstSize: a & mask
8623     // SrcSize  > DstSize: trunc(a) & mask
8624     if (SrcSize < DstSize) {
8625       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8626       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8627       Instruction *And =
8628         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8629       InsertNewInstBefore(And, CI);
8630       return new ZExtInst(And, CI.getType());
8631     } else if (SrcSize == DstSize) {
8632       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8633       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8634                                                            AndValue));
8635     } else if (SrcSize > DstSize) {
8636       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8637       InsertNewInstBefore(Trunc, CI);
8638       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8639       return BinaryOperator::CreateAnd(Trunc, 
8640                                        ConstantInt::get(Trunc->getType(),
8641                                                                AndValue));
8642     }
8643   }
8644
8645   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8646     return transformZExtICmp(ICI, CI);
8647
8648   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8649   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8650     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8651     // of the (zext icmp) will be transformed.
8652     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8653     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8654     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8655         (transformZExtICmp(LHS, CI, false) ||
8656          transformZExtICmp(RHS, CI, false))) {
8657       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8658       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8659       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8660     }
8661   }
8662
8663   // zext(trunc(t) & C) -> (t & zext(C)).
8664   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8665     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8666       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8667         Value *TI0 = TI->getOperand(0);
8668         if (TI0->getType() == CI.getType())
8669           return
8670             BinaryOperator::CreateAnd(TI0,
8671                                 ConstantExpr::getZExt(C, CI.getType()));
8672       }
8673
8674   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8675   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8676     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8677       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8678         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8679             And->getOperand(1) == C)
8680           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8681             Value *TI0 = TI->getOperand(0);
8682             if (TI0->getType() == CI.getType()) {
8683               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8684               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8685               InsertNewInstBefore(NewAnd, *And);
8686               return BinaryOperator::CreateXor(NewAnd, ZC);
8687             }
8688           }
8689
8690   return 0;
8691 }
8692
8693 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8694   if (Instruction *I = commonIntCastTransforms(CI))
8695     return I;
8696   
8697   Value *Src = CI.getOperand(0);
8698   
8699   // Canonicalize sign-extend from i1 to a select.
8700   if (Src->getType() == Type::Int1Ty)
8701     return SelectInst::Create(Src,
8702                               Context->getAllOnesValue(CI.getType()),
8703                               Context->getNullValue(CI.getType()));
8704
8705   // See if the value being truncated is already sign extended.  If so, just
8706   // eliminate the trunc/sext pair.
8707   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8708     Value *Op = cast<User>(Src)->getOperand(0);
8709     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8710     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8711     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8712     unsigned NumSignBits = ComputeNumSignBits(Op);
8713
8714     if (OpBits == DestBits) {
8715       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8716       // bits, it is already ready.
8717       if (NumSignBits > DestBits-MidBits)
8718         return ReplaceInstUsesWith(CI, Op);
8719     } else if (OpBits < DestBits) {
8720       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8721       // bits, just sext from i32.
8722       if (NumSignBits > OpBits-MidBits)
8723         return new SExtInst(Op, CI.getType(), "tmp");
8724     } else {
8725       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8726       // bits, just truncate to i32.
8727       if (NumSignBits > OpBits-MidBits)
8728         return new TruncInst(Op, CI.getType(), "tmp");
8729     }
8730   }
8731
8732   // If the input is a shl/ashr pair of a same constant, then this is a sign
8733   // extension from a smaller value.  If we could trust arbitrary bitwidth
8734   // integers, we could turn this into a truncate to the smaller bit and then
8735   // use a sext for the whole extension.  Since we don't, look deeper and check
8736   // for a truncate.  If the source and dest are the same type, eliminate the
8737   // trunc and extend and just do shifts.  For example, turn:
8738   //   %a = trunc i32 %i to i8
8739   //   %b = shl i8 %a, 6
8740   //   %c = ashr i8 %b, 6
8741   //   %d = sext i8 %c to i32
8742   // into:
8743   //   %a = shl i32 %i, 30
8744   //   %d = ashr i32 %a, 30
8745   Value *A = 0;
8746   ConstantInt *BA = 0, *CA = 0;
8747   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8748                         m_ConstantInt(CA)), *Context) &&
8749       BA == CA && isa<TruncInst>(A)) {
8750     Value *I = cast<TruncInst>(A)->getOperand(0);
8751     if (I->getType() == CI.getType()) {
8752       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8753       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8754       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8755       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8756       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8757                                                         CI.getName()), CI);
8758       return BinaryOperator::CreateAShr(I, ShAmtV);
8759     }
8760   }
8761   
8762   return 0;
8763 }
8764
8765 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8766 /// in the specified FP type without changing its value.
8767 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8768                               LLVMContext *Context) {
8769   bool losesInfo;
8770   APFloat F = CFP->getValueAPF();
8771   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8772   if (!losesInfo)
8773     return ConstantFP::get(*Context, F);
8774   return 0;
8775 }
8776
8777 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8778 /// through it until we get the source value.
8779 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8780   if (Instruction *I = dyn_cast<Instruction>(V))
8781     if (I->getOpcode() == Instruction::FPExt)
8782       return LookThroughFPExtensions(I->getOperand(0), Context);
8783   
8784   // If this value is a constant, return the constant in the smallest FP type
8785   // that can accurately represent it.  This allows us to turn
8786   // (float)((double)X+2.0) into x+2.0f.
8787   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8788     if (CFP->getType() == Type::PPC_FP128Ty)
8789       return V;  // No constant folding of this.
8790     // See if the value can be truncated to float and then reextended.
8791     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8792       return V;
8793     if (CFP->getType() == Type::DoubleTy)
8794       return V;  // Won't shrink.
8795     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8796       return V;
8797     // Don't try to shrink to various long double types.
8798   }
8799   
8800   return V;
8801 }
8802
8803 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8804   if (Instruction *I = commonCastTransforms(CI))
8805     return I;
8806   
8807   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8808   // smaller than the destination type, we can eliminate the truncate by doing
8809   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8810   // many builtins (sqrt, etc).
8811   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8812   if (OpI && OpI->hasOneUse()) {
8813     switch (OpI->getOpcode()) {
8814     default: break;
8815     case Instruction::FAdd:
8816     case Instruction::FSub:
8817     case Instruction::FMul:
8818     case Instruction::FDiv:
8819     case Instruction::FRem:
8820       const Type *SrcTy = OpI->getType();
8821       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8822       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8823       if (LHSTrunc->getType() != SrcTy && 
8824           RHSTrunc->getType() != SrcTy) {
8825         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8826         // If the source types were both smaller than the destination type of
8827         // the cast, do this xform.
8828         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8829             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8830           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8831                                       CI.getType(), CI);
8832           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8833                                       CI.getType(), CI);
8834           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8835         }
8836       }
8837       break;  
8838     }
8839   }
8840   return 0;
8841 }
8842
8843 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8844   return commonCastTransforms(CI);
8845 }
8846
8847 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8848   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8849   if (OpI == 0)
8850     return commonCastTransforms(FI);
8851
8852   // fptoui(uitofp(X)) --> X
8853   // fptoui(sitofp(X)) --> X
8854   // This is safe if the intermediate type has enough bits in its mantissa to
8855   // accurately represent all values of X.  For example, do not do this with
8856   // i64->float->i64.  This is also safe for sitofp case, because any negative
8857   // 'X' value would cause an undefined result for the fptoui. 
8858   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8859       OpI->getOperand(0)->getType() == FI.getType() &&
8860       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8861                     OpI->getType()->getFPMantissaWidth())
8862     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8863
8864   return commonCastTransforms(FI);
8865 }
8866
8867 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8868   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8869   if (OpI == 0)
8870     return commonCastTransforms(FI);
8871   
8872   // fptosi(sitofp(X)) --> X
8873   // fptosi(uitofp(X)) --> X
8874   // This is safe if the intermediate type has enough bits in its mantissa to
8875   // accurately represent all values of X.  For example, do not do this with
8876   // i64->float->i64.  This is also safe for sitofp case, because any negative
8877   // 'X' value would cause an undefined result for the fptoui. 
8878   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8879       OpI->getOperand(0)->getType() == FI.getType() &&
8880       (int)FI.getType()->getScalarSizeInBits() <=
8881                     OpI->getType()->getFPMantissaWidth())
8882     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8883   
8884   return commonCastTransforms(FI);
8885 }
8886
8887 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8888   return commonCastTransforms(CI);
8889 }
8890
8891 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8892   return commonCastTransforms(CI);
8893 }
8894
8895 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8896   // If the destination integer type is smaller than the intptr_t type for
8897   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8898   // trunc to be exposed to other transforms.  Don't do this for extending
8899   // ptrtoint's, because we don't know if the target sign or zero extends its
8900   // pointers.
8901   if (TD &&
8902       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8903     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8904                                                     TD->getIntPtrType(),
8905                                                     "tmp"), CI);
8906     return new TruncInst(P, CI.getType());
8907   }
8908   
8909   return commonPointerCastTransforms(CI);
8910 }
8911
8912 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8913   // If the source integer type is larger than the intptr_t type for
8914   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8915   // allows the trunc to be exposed to other transforms.  Don't do this for
8916   // extending inttoptr's, because we don't know if the target sign or zero
8917   // extends to pointers.
8918   if (TD &&
8919       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8920       TD->getPointerSizeInBits()) {
8921     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8922                                                  TD->getIntPtrType(),
8923                                                  "tmp"), CI);
8924     return new IntToPtrInst(P, CI.getType());
8925   }
8926   
8927   if (Instruction *I = commonCastTransforms(CI))
8928     return I;
8929
8930   return 0;
8931 }
8932
8933 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8934   // If the operands are integer typed then apply the integer transforms,
8935   // otherwise just apply the common ones.
8936   Value *Src = CI.getOperand(0);
8937   const Type *SrcTy = Src->getType();
8938   const Type *DestTy = CI.getType();
8939
8940   if (isa<PointerType>(SrcTy)) {
8941     if (Instruction *I = commonPointerCastTransforms(CI))
8942       return I;
8943   } else {
8944     if (Instruction *Result = commonCastTransforms(CI))
8945       return Result;
8946   }
8947
8948
8949   // Get rid of casts from one type to the same type. These are useless and can
8950   // be replaced by the operand.
8951   if (DestTy == Src->getType())
8952     return ReplaceInstUsesWith(CI, Src);
8953
8954   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8955     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8956     const Type *DstElTy = DstPTy->getElementType();
8957     const Type *SrcElTy = SrcPTy->getElementType();
8958     
8959     // If the address spaces don't match, don't eliminate the bitcast, which is
8960     // required for changing types.
8961     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8962       return 0;
8963     
8964     // If we are casting a malloc or alloca to a pointer to a type of the same
8965     // size, rewrite the allocation instruction to allocate the "right" type.
8966     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8967       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8968         return V;
8969     
8970     // If the source and destination are pointers, and this cast is equivalent
8971     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8972     // This can enhance SROA and other transforms that want type-safe pointers.
8973     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
8974     unsigned NumZeros = 0;
8975     while (SrcElTy != DstElTy && 
8976            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8977            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8978       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8979       ++NumZeros;
8980     }
8981
8982     // If we found a path from the src to dest, create the getelementptr now.
8983     if (SrcElTy == DstElTy) {
8984       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8985       Instruction *GEP = GetElementPtrInst::Create(Src,
8986                                                    Idxs.begin(), Idxs.end(), "",
8987                                                    ((Instruction*) NULL));
8988       cast<GEPOperator>(GEP)->setIsInBounds(true);
8989       return GEP;
8990     }
8991   }
8992
8993   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8994     if (DestVTy->getNumElements() == 1) {
8995       if (!isa<VectorType>(SrcTy)) {
8996         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8997                                        DestVTy->getElementType(), CI);
8998         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8999                                          Context->getNullValue(Type::Int32Ty));
9000       }
9001       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9002     }
9003   }
9004
9005   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9006     if (SrcVTy->getNumElements() == 1) {
9007       if (!isa<VectorType>(DestTy)) {
9008         Instruction *Elem =
9009           ExtractElementInst::Create(Src, Context->getNullValue(Type::Int32Ty));
9010         InsertNewInstBefore(Elem, CI);
9011         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9012       }
9013     }
9014   }
9015
9016   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9017     if (SVI->hasOneUse()) {
9018       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9019       // a bitconvert to a vector with the same # elts.
9020       if (isa<VectorType>(DestTy) && 
9021           cast<VectorType>(DestTy)->getNumElements() ==
9022                 SVI->getType()->getNumElements() &&
9023           SVI->getType()->getNumElements() ==
9024             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9025         CastInst *Tmp;
9026         // If either of the operands is a cast from CI.getType(), then
9027         // evaluating the shuffle in the casted destination's type will allow
9028         // us to eliminate at least one cast.
9029         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9030              Tmp->getOperand(0)->getType() == DestTy) ||
9031             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9032              Tmp->getOperand(0)->getType() == DestTy)) {
9033           Value *LHS = InsertCastBefore(Instruction::BitCast,
9034                                         SVI->getOperand(0), DestTy, CI);
9035           Value *RHS = InsertCastBefore(Instruction::BitCast,
9036                                         SVI->getOperand(1), DestTy, CI);
9037           // Return a new shuffle vector.  Use the same element ID's, as we
9038           // know the vector types match #elts.
9039           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9040         }
9041       }
9042     }
9043   }
9044   return 0;
9045 }
9046
9047 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9048 ///   %C = or %A, %B
9049 ///   %D = select %cond, %C, %A
9050 /// into:
9051 ///   %C = select %cond, %B, 0
9052 ///   %D = or %A, %C
9053 ///
9054 /// Assuming that the specified instruction is an operand to the select, return
9055 /// a bitmask indicating which operands of this instruction are foldable if they
9056 /// equal the other incoming value of the select.
9057 ///
9058 static unsigned GetSelectFoldableOperands(Instruction *I) {
9059   switch (I->getOpcode()) {
9060   case Instruction::Add:
9061   case Instruction::Mul:
9062   case Instruction::And:
9063   case Instruction::Or:
9064   case Instruction::Xor:
9065     return 3;              // Can fold through either operand.
9066   case Instruction::Sub:   // Can only fold on the amount subtracted.
9067   case Instruction::Shl:   // Can only fold on the shift amount.
9068   case Instruction::LShr:
9069   case Instruction::AShr:
9070     return 1;
9071   default:
9072     return 0;              // Cannot fold
9073   }
9074 }
9075
9076 /// GetSelectFoldableConstant - For the same transformation as the previous
9077 /// function, return the identity constant that goes into the select.
9078 static Constant *GetSelectFoldableConstant(Instruction *I,
9079                                            LLVMContext *Context) {
9080   switch (I->getOpcode()) {
9081   default: llvm_unreachable("This cannot happen!");
9082   case Instruction::Add:
9083   case Instruction::Sub:
9084   case Instruction::Or:
9085   case Instruction::Xor:
9086   case Instruction::Shl:
9087   case Instruction::LShr:
9088   case Instruction::AShr:
9089     return Context->getNullValue(I->getType());
9090   case Instruction::And:
9091     return Context->getAllOnesValue(I->getType());
9092   case Instruction::Mul:
9093     return ConstantInt::get(I->getType(), 1);
9094   }
9095 }
9096
9097 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9098 /// have the same opcode and only one use each.  Try to simplify this.
9099 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9100                                           Instruction *FI) {
9101   if (TI->getNumOperands() == 1) {
9102     // If this is a non-volatile load or a cast from the same type,
9103     // merge.
9104     if (TI->isCast()) {
9105       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9106         return 0;
9107     } else {
9108       return 0;  // unknown unary op.
9109     }
9110
9111     // Fold this by inserting a select from the input values.
9112     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9113                                           FI->getOperand(0), SI.getName()+".v");
9114     InsertNewInstBefore(NewSI, SI);
9115     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9116                             TI->getType());
9117   }
9118
9119   // Only handle binary operators here.
9120   if (!isa<BinaryOperator>(TI))
9121     return 0;
9122
9123   // Figure out if the operations have any operands in common.
9124   Value *MatchOp, *OtherOpT, *OtherOpF;
9125   bool MatchIsOpZero;
9126   if (TI->getOperand(0) == FI->getOperand(0)) {
9127     MatchOp  = TI->getOperand(0);
9128     OtherOpT = TI->getOperand(1);
9129     OtherOpF = FI->getOperand(1);
9130     MatchIsOpZero = true;
9131   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9132     MatchOp  = TI->getOperand(1);
9133     OtherOpT = TI->getOperand(0);
9134     OtherOpF = FI->getOperand(0);
9135     MatchIsOpZero = false;
9136   } else if (!TI->isCommutative()) {
9137     return 0;
9138   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9139     MatchOp  = TI->getOperand(0);
9140     OtherOpT = TI->getOperand(1);
9141     OtherOpF = FI->getOperand(0);
9142     MatchIsOpZero = true;
9143   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9144     MatchOp  = TI->getOperand(1);
9145     OtherOpT = TI->getOperand(0);
9146     OtherOpF = FI->getOperand(1);
9147     MatchIsOpZero = true;
9148   } else {
9149     return 0;
9150   }
9151
9152   // If we reach here, they do have operations in common.
9153   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9154                                          OtherOpF, SI.getName()+".v");
9155   InsertNewInstBefore(NewSI, SI);
9156
9157   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9158     if (MatchIsOpZero)
9159       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9160     else
9161       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9162   }
9163   llvm_unreachable("Shouldn't get here");
9164   return 0;
9165 }
9166
9167 static bool isSelect01(Constant *C1, Constant *C2) {
9168   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9169   if (!C1I)
9170     return false;
9171   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9172   if (!C2I)
9173     return false;
9174   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9175 }
9176
9177 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9178 /// facilitate further optimization.
9179 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9180                                             Value *FalseVal) {
9181   // See the comment above GetSelectFoldableOperands for a description of the
9182   // transformation we are doing here.
9183   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9184     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9185         !isa<Constant>(FalseVal)) {
9186       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9187         unsigned OpToFold = 0;
9188         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9189           OpToFold = 1;
9190         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9191           OpToFold = 2;
9192         }
9193
9194         if (OpToFold) {
9195           Constant *C = GetSelectFoldableConstant(TVI, Context);
9196           Value *OOp = TVI->getOperand(2-OpToFold);
9197           // Avoid creating select between 2 constants unless it's selecting
9198           // between 0 and 1.
9199           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9200             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9201             InsertNewInstBefore(NewSel, SI);
9202             NewSel->takeName(TVI);
9203             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9204               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9205             llvm_unreachable("Unknown instruction!!");
9206           }
9207         }
9208       }
9209     }
9210   }
9211
9212   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9213     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9214         !isa<Constant>(TrueVal)) {
9215       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9216         unsigned OpToFold = 0;
9217         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9218           OpToFold = 1;
9219         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9220           OpToFold = 2;
9221         }
9222
9223         if (OpToFold) {
9224           Constant *C = GetSelectFoldableConstant(FVI, Context);
9225           Value *OOp = FVI->getOperand(2-OpToFold);
9226           // Avoid creating select between 2 constants unless it's selecting
9227           // between 0 and 1.
9228           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9229             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9230             InsertNewInstBefore(NewSel, SI);
9231             NewSel->takeName(FVI);
9232             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9233               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9234             llvm_unreachable("Unknown instruction!!");
9235           }
9236         }
9237       }
9238     }
9239   }
9240
9241   return 0;
9242 }
9243
9244 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9245 /// ICmpInst as its first operand.
9246 ///
9247 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9248                                                    ICmpInst *ICI) {
9249   bool Changed = false;
9250   ICmpInst::Predicate Pred = ICI->getPredicate();
9251   Value *CmpLHS = ICI->getOperand(0);
9252   Value *CmpRHS = ICI->getOperand(1);
9253   Value *TrueVal = SI.getTrueValue();
9254   Value *FalseVal = SI.getFalseValue();
9255
9256   // Check cases where the comparison is with a constant that
9257   // can be adjusted to fit the min/max idiom. We may edit ICI in
9258   // place here, so make sure the select is the only user.
9259   if (ICI->hasOneUse())
9260     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9261       switch (Pred) {
9262       default: break;
9263       case ICmpInst::ICMP_ULT:
9264       case ICmpInst::ICMP_SLT: {
9265         // X < MIN ? T : F  -->  F
9266         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9267           return ReplaceInstUsesWith(SI, FalseVal);
9268         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9269         Constant *AdjustedRHS = SubOne(CI, Context);
9270         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9271             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9272           Pred = ICmpInst::getSwappedPredicate(Pred);
9273           CmpRHS = AdjustedRHS;
9274           std::swap(FalseVal, TrueVal);
9275           ICI->setPredicate(Pred);
9276           ICI->setOperand(1, CmpRHS);
9277           SI.setOperand(1, TrueVal);
9278           SI.setOperand(2, FalseVal);
9279           Changed = true;
9280         }
9281         break;
9282       }
9283       case ICmpInst::ICMP_UGT:
9284       case ICmpInst::ICMP_SGT: {
9285         // X > MAX ? T : F  -->  F
9286         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9287           return ReplaceInstUsesWith(SI, FalseVal);
9288         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9289         Constant *AdjustedRHS = AddOne(CI, Context);
9290         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9291             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9292           Pred = ICmpInst::getSwappedPredicate(Pred);
9293           CmpRHS = AdjustedRHS;
9294           std::swap(FalseVal, TrueVal);
9295           ICI->setPredicate(Pred);
9296           ICI->setOperand(1, CmpRHS);
9297           SI.setOperand(1, TrueVal);
9298           SI.setOperand(2, FalseVal);
9299           Changed = true;
9300         }
9301         break;
9302       }
9303       }
9304
9305       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9306       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9307       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9308       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9309           match(FalseVal, m_ConstantInt<0>(), *Context))
9310         Pred = ICI->getPredicate();
9311       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9312                match(FalseVal, m_ConstantInt<-1>(), *Context))
9313         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9314       
9315       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9316         // If we are just checking for a icmp eq of a single bit and zext'ing it
9317         // to an integer, then shift the bit to the appropriate place and then
9318         // cast to integer to avoid the comparison.
9319         const APInt &Op1CV = CI->getValue();
9320     
9321         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9322         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9323         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9324             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9325           Value *In = ICI->getOperand(0);
9326           Value *Sh = ConstantInt::get(In->getType(),
9327                                        In->getType()->getScalarSizeInBits()-1);
9328           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9329                                                         In->getName()+".lobit"),
9330                                    *ICI);
9331           if (In->getType() != SI.getType())
9332             In = CastInst::CreateIntegerCast(In, SI.getType(),
9333                                              true/*SExt*/, "tmp", ICI);
9334     
9335           if (Pred == ICmpInst::ICMP_SGT)
9336             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9337                                        In->getName()+".not"), *ICI);
9338     
9339           return ReplaceInstUsesWith(SI, In);
9340         }
9341       }
9342     }
9343
9344   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9345     // Transform (X == Y) ? X : Y  -> Y
9346     if (Pred == ICmpInst::ICMP_EQ)
9347       return ReplaceInstUsesWith(SI, FalseVal);
9348     // Transform (X != Y) ? X : Y  -> X
9349     if (Pred == ICmpInst::ICMP_NE)
9350       return ReplaceInstUsesWith(SI, TrueVal);
9351     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9352
9353   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9354     // Transform (X == Y) ? Y : X  -> X
9355     if (Pred == ICmpInst::ICMP_EQ)
9356       return ReplaceInstUsesWith(SI, FalseVal);
9357     // Transform (X != Y) ? Y : X  -> Y
9358     if (Pred == ICmpInst::ICMP_NE)
9359       return ReplaceInstUsesWith(SI, TrueVal);
9360     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9361   }
9362
9363   /// NOTE: if we wanted to, this is where to detect integer ABS
9364
9365   return Changed ? &SI : 0;
9366 }
9367
9368 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9369   Value *CondVal = SI.getCondition();
9370   Value *TrueVal = SI.getTrueValue();
9371   Value *FalseVal = SI.getFalseValue();
9372
9373   // select true, X, Y  -> X
9374   // select false, X, Y -> Y
9375   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9376     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9377
9378   // select C, X, X -> X
9379   if (TrueVal == FalseVal)
9380     return ReplaceInstUsesWith(SI, TrueVal);
9381
9382   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9383     return ReplaceInstUsesWith(SI, FalseVal);
9384   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9385     return ReplaceInstUsesWith(SI, TrueVal);
9386   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9387     if (isa<Constant>(TrueVal))
9388       return ReplaceInstUsesWith(SI, TrueVal);
9389     else
9390       return ReplaceInstUsesWith(SI, FalseVal);
9391   }
9392
9393   if (SI.getType() == Type::Int1Ty) {
9394     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9395       if (C->getZExtValue()) {
9396         // Change: A = select B, true, C --> A = or B, C
9397         return BinaryOperator::CreateOr(CondVal, FalseVal);
9398       } else {
9399         // Change: A = select B, false, C --> A = and !B, C
9400         Value *NotCond =
9401           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9402                                              "not."+CondVal->getName()), SI);
9403         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9404       }
9405     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9406       if (C->getZExtValue() == false) {
9407         // Change: A = select B, C, false --> A = and B, C
9408         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9409       } else {
9410         // Change: A = select B, C, true --> A = or !B, C
9411         Value *NotCond =
9412           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9413                                              "not."+CondVal->getName()), SI);
9414         return BinaryOperator::CreateOr(NotCond, TrueVal);
9415       }
9416     }
9417     
9418     // select a, b, a  -> a&b
9419     // select a, a, b  -> a|b
9420     if (CondVal == TrueVal)
9421       return BinaryOperator::CreateOr(CondVal, FalseVal);
9422     else if (CondVal == FalseVal)
9423       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9424   }
9425
9426   // Selecting between two integer constants?
9427   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9428     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9429       // select C, 1, 0 -> zext C to int
9430       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9431         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9432       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9433         // select C, 0, 1 -> zext !C to int
9434         Value *NotCond =
9435           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9436                                                "not."+CondVal->getName()), SI);
9437         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9438       }
9439
9440       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9441         // If one of the constants is zero (we know they can't both be) and we
9442         // have an icmp instruction with zero, and we have an 'and' with the
9443         // non-constant value, eliminate this whole mess.  This corresponds to
9444         // cases like this: ((X & 27) ? 27 : 0)
9445         if (TrueValC->isZero() || FalseValC->isZero())
9446           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9447               cast<Constant>(IC->getOperand(1))->isNullValue())
9448             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9449               if (ICA->getOpcode() == Instruction::And &&
9450                   isa<ConstantInt>(ICA->getOperand(1)) &&
9451                   (ICA->getOperand(1) == TrueValC ||
9452                    ICA->getOperand(1) == FalseValC) &&
9453                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9454                 // Okay, now we know that everything is set up, we just don't
9455                 // know whether we have a icmp_ne or icmp_eq and whether the 
9456                 // true or false val is the zero.
9457                 bool ShouldNotVal = !TrueValC->isZero();
9458                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9459                 Value *V = ICA;
9460                 if (ShouldNotVal)
9461                   V = InsertNewInstBefore(BinaryOperator::Create(
9462                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9463                 return ReplaceInstUsesWith(SI, V);
9464               }
9465       }
9466     }
9467
9468   // See if we are selecting two values based on a comparison of the two values.
9469   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9470     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9471       // Transform (X == Y) ? X : Y  -> Y
9472       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9473         // This is not safe in general for floating point:  
9474         // consider X== -0, Y== +0.
9475         // It becomes safe if either operand is a nonzero constant.
9476         ConstantFP *CFPt, *CFPf;
9477         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9478               !CFPt->getValueAPF().isZero()) ||
9479             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9480              !CFPf->getValueAPF().isZero()))
9481         return ReplaceInstUsesWith(SI, FalseVal);
9482       }
9483       // Transform (X != Y) ? X : Y  -> X
9484       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9485         return ReplaceInstUsesWith(SI, TrueVal);
9486       // NOTE: if we wanted to, this is where to detect MIN/MAX
9487
9488     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9489       // Transform (X == Y) ? Y : X  -> X
9490       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9491         // This is not safe in general for floating point:  
9492         // consider X== -0, Y== +0.
9493         // It becomes safe if either operand is a nonzero constant.
9494         ConstantFP *CFPt, *CFPf;
9495         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9496               !CFPt->getValueAPF().isZero()) ||
9497             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9498              !CFPf->getValueAPF().isZero()))
9499           return ReplaceInstUsesWith(SI, FalseVal);
9500       }
9501       // Transform (X != Y) ? Y : X  -> Y
9502       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9503         return ReplaceInstUsesWith(SI, TrueVal);
9504       // NOTE: if we wanted to, this is where to detect MIN/MAX
9505     }
9506     // NOTE: if we wanted to, this is where to detect ABS
9507   }
9508
9509   // See if we are selecting two values based on a comparison of the two values.
9510   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9511     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9512       return Result;
9513
9514   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9515     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9516       if (TI->hasOneUse() && FI->hasOneUse()) {
9517         Instruction *AddOp = 0, *SubOp = 0;
9518
9519         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9520         if (TI->getOpcode() == FI->getOpcode())
9521           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9522             return IV;
9523
9524         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9525         // even legal for FP.
9526         if ((TI->getOpcode() == Instruction::Sub &&
9527              FI->getOpcode() == Instruction::Add) ||
9528             (TI->getOpcode() == Instruction::FSub &&
9529              FI->getOpcode() == Instruction::FAdd)) {
9530           AddOp = FI; SubOp = TI;
9531         } else if ((FI->getOpcode() == Instruction::Sub &&
9532                     TI->getOpcode() == Instruction::Add) ||
9533                    (FI->getOpcode() == Instruction::FSub &&
9534                     TI->getOpcode() == Instruction::FAdd)) {
9535           AddOp = TI; SubOp = FI;
9536         }
9537
9538         if (AddOp) {
9539           Value *OtherAddOp = 0;
9540           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9541             OtherAddOp = AddOp->getOperand(1);
9542           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9543             OtherAddOp = AddOp->getOperand(0);
9544           }
9545
9546           if (OtherAddOp) {
9547             // So at this point we know we have (Y -> OtherAddOp):
9548             //        select C, (add X, Y), (sub X, Z)
9549             Value *NegVal;  // Compute -Z
9550             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9551               NegVal = ConstantExpr::getNeg(C);
9552             } else {
9553               NegVal = InsertNewInstBefore(
9554                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9555                                               "tmp"), SI);
9556             }
9557
9558             Value *NewTrueOp = OtherAddOp;
9559             Value *NewFalseOp = NegVal;
9560             if (AddOp != TI)
9561               std::swap(NewTrueOp, NewFalseOp);
9562             Instruction *NewSel =
9563               SelectInst::Create(CondVal, NewTrueOp,
9564                                  NewFalseOp, SI.getName() + ".p");
9565
9566             NewSel = InsertNewInstBefore(NewSel, SI);
9567             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9568           }
9569         }
9570       }
9571
9572   // See if we can fold the select into one of our operands.
9573   if (SI.getType()->isInteger()) {
9574     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9575     if (FoldI)
9576       return FoldI;
9577   }
9578
9579   if (BinaryOperator::isNot(CondVal)) {
9580     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9581     SI.setOperand(1, FalseVal);
9582     SI.setOperand(2, TrueVal);
9583     return &SI;
9584   }
9585
9586   return 0;
9587 }
9588
9589 /// EnforceKnownAlignment - If the specified pointer points to an object that
9590 /// we control, modify the object's alignment to PrefAlign. This isn't
9591 /// often possible though. If alignment is important, a more reliable approach
9592 /// is to simply align all global variables and allocation instructions to
9593 /// their preferred alignment from the beginning.
9594 ///
9595 static unsigned EnforceKnownAlignment(Value *V,
9596                                       unsigned Align, unsigned PrefAlign) {
9597
9598   User *U = dyn_cast<User>(V);
9599   if (!U) return Align;
9600
9601   switch (Operator::getOpcode(U)) {
9602   default: break;
9603   case Instruction::BitCast:
9604     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9605   case Instruction::GetElementPtr: {
9606     // If all indexes are zero, it is just the alignment of the base pointer.
9607     bool AllZeroOperands = true;
9608     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9609       if (!isa<Constant>(*i) ||
9610           !cast<Constant>(*i)->isNullValue()) {
9611         AllZeroOperands = false;
9612         break;
9613       }
9614
9615     if (AllZeroOperands) {
9616       // Treat this like a bitcast.
9617       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9618     }
9619     break;
9620   }
9621   }
9622
9623   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9624     // If there is a large requested alignment and we can, bump up the alignment
9625     // of the global.
9626     if (!GV->isDeclaration()) {
9627       if (GV->getAlignment() >= PrefAlign)
9628         Align = GV->getAlignment();
9629       else {
9630         GV->setAlignment(PrefAlign);
9631         Align = PrefAlign;
9632       }
9633     }
9634   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9635     // If there is a requested alignment and if this is an alloca, round up.  We
9636     // don't do this for malloc, because some systems can't respect the request.
9637     if (isa<AllocaInst>(AI)) {
9638       if (AI->getAlignment() >= PrefAlign)
9639         Align = AI->getAlignment();
9640       else {
9641         AI->setAlignment(PrefAlign);
9642         Align = PrefAlign;
9643       }
9644     }
9645   }
9646
9647   return Align;
9648 }
9649
9650 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9651 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9652 /// and it is more than the alignment of the ultimate object, see if we can
9653 /// increase the alignment of the ultimate object, making this check succeed.
9654 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9655                                                   unsigned PrefAlign) {
9656   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9657                       sizeof(PrefAlign) * CHAR_BIT;
9658   APInt Mask = APInt::getAllOnesValue(BitWidth);
9659   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9660   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9661   unsigned TrailZ = KnownZero.countTrailingOnes();
9662   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9663
9664   if (PrefAlign > Align)
9665     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9666   
9667     // We don't need to make any adjustment.
9668   return Align;
9669 }
9670
9671 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9672   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9673   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9674   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9675   unsigned CopyAlign = MI->getAlignment();
9676
9677   if (CopyAlign < MinAlign) {
9678     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9679                                              MinAlign, false));
9680     return MI;
9681   }
9682   
9683   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9684   // load/store.
9685   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9686   if (MemOpLength == 0) return 0;
9687   
9688   // Source and destination pointer types are always "i8*" for intrinsic.  See
9689   // if the size is something we can handle with a single primitive load/store.
9690   // A single load+store correctly handles overlapping memory in the memmove
9691   // case.
9692   unsigned Size = MemOpLength->getZExtValue();
9693   if (Size == 0) return MI;  // Delete this mem transfer.
9694   
9695   if (Size > 8 || (Size&(Size-1)))
9696     return 0;  // If not 1/2/4/8 bytes, exit.
9697   
9698   // Use an integer load+store unless we can find something better.
9699   Type *NewPtrTy =
9700                 PointerType::getUnqual(IntegerType::get(Size<<3));
9701   
9702   // Memcpy forces the use of i8* for the source and destination.  That means
9703   // that if you're using memcpy to move one double around, you'll get a cast
9704   // from double* to i8*.  We'd much rather use a double load+store rather than
9705   // an i64 load+store, here because this improves the odds that the source or
9706   // dest address will be promotable.  See if we can find a better type than the
9707   // integer datatype.
9708   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9709     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9710     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9711       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9712       // down through these levels if so.
9713       while (!SrcETy->isSingleValueType()) {
9714         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9715           if (STy->getNumElements() == 1)
9716             SrcETy = STy->getElementType(0);
9717           else
9718             break;
9719         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9720           if (ATy->getNumElements() == 1)
9721             SrcETy = ATy->getElementType();
9722           else
9723             break;
9724         } else
9725           break;
9726       }
9727       
9728       if (SrcETy->isSingleValueType())
9729         NewPtrTy = PointerType::getUnqual(SrcETy);
9730     }
9731   }
9732   
9733   
9734   // If the memcpy/memmove provides better alignment info than we can
9735   // infer, use it.
9736   SrcAlign = std::max(SrcAlign, CopyAlign);
9737   DstAlign = std::max(DstAlign, CopyAlign);
9738   
9739   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9740   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9741   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9742   InsertNewInstBefore(L, *MI);
9743   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9744
9745   // Set the size of the copy to 0, it will be deleted on the next iteration.
9746   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9747   return MI;
9748 }
9749
9750 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9751   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9752   if (MI->getAlignment() < Alignment) {
9753     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9754                                              Alignment, false));
9755     return MI;
9756   }
9757   
9758   // Extract the length and alignment and fill if they are constant.
9759   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9760   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9761   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9762     return 0;
9763   uint64_t Len = LenC->getZExtValue();
9764   Alignment = MI->getAlignment();
9765   
9766   // If the length is zero, this is a no-op
9767   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9768   
9769   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9770   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9771     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9772     
9773     Value *Dest = MI->getDest();
9774     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9775
9776     // Alignment 0 is identity for alignment 1 for memset, but not store.
9777     if (Alignment == 0) Alignment = 1;
9778     
9779     // Extract the fill value and store.
9780     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9781     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9782                                       Dest, false, Alignment), *MI);
9783     
9784     // Set the size of the copy to 0, it will be deleted on the next iteration.
9785     MI->setLength(Context->getNullValue(LenC->getType()));
9786     return MI;
9787   }
9788
9789   return 0;
9790 }
9791
9792
9793 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9794 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9795 /// the heavy lifting.
9796 ///
9797 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9798   // If the caller function is nounwind, mark the call as nounwind, even if the
9799   // callee isn't.
9800   if (CI.getParent()->getParent()->doesNotThrow() &&
9801       !CI.doesNotThrow()) {
9802     CI.setDoesNotThrow();
9803     return &CI;
9804   }
9805   
9806   
9807   
9808   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9809   if (!II) return visitCallSite(&CI);
9810   
9811   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9812   // visitCallSite.
9813   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9814     bool Changed = false;
9815
9816     // memmove/cpy/set of zero bytes is a noop.
9817     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9818       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9819
9820       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9821         if (CI->getZExtValue() == 1) {
9822           // Replace the instruction with just byte operations.  We would
9823           // transform other cases to loads/stores, but we don't know if
9824           // alignment is sufficient.
9825         }
9826     }
9827
9828     // If we have a memmove and the source operation is a constant global,
9829     // then the source and dest pointers can't alias, so we can change this
9830     // into a call to memcpy.
9831     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9832       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9833         if (GVSrc->isConstant()) {
9834           Module *M = CI.getParent()->getParent()->getParent();
9835           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9836           const Type *Tys[1];
9837           Tys[0] = CI.getOperand(3)->getType();
9838           CI.setOperand(0, 
9839                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9840           Changed = true;
9841         }
9842
9843       // memmove(x,x,size) -> noop.
9844       if (MMI->getSource() == MMI->getDest())
9845         return EraseInstFromFunction(CI);
9846     }
9847
9848     // If we can determine a pointer alignment that is bigger than currently
9849     // set, update the alignment.
9850     if (isa<MemTransferInst>(MI)) {
9851       if (Instruction *I = SimplifyMemTransfer(MI))
9852         return I;
9853     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9854       if (Instruction *I = SimplifyMemSet(MSI))
9855         return I;
9856     }
9857           
9858     if (Changed) return II;
9859   }
9860   
9861   switch (II->getIntrinsicID()) {
9862   default: break;
9863   case Intrinsic::bswap:
9864     // bswap(bswap(x)) -> x
9865     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9866       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9867         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9868     break;
9869   case Intrinsic::ppc_altivec_lvx:
9870   case Intrinsic::ppc_altivec_lvxl:
9871   case Intrinsic::x86_sse_loadu_ps:
9872   case Intrinsic::x86_sse2_loadu_pd:
9873   case Intrinsic::x86_sse2_loadu_dq:
9874     // Turn PPC lvx     -> load if the pointer is known aligned.
9875     // Turn X86 loadups -> load if the pointer is known aligned.
9876     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9877       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9878                                    PointerType::getUnqual(II->getType()),
9879                                        CI);
9880       return new LoadInst(Ptr);
9881     }
9882     break;
9883   case Intrinsic::ppc_altivec_stvx:
9884   case Intrinsic::ppc_altivec_stvxl:
9885     // Turn stvx -> store if the pointer is known aligned.
9886     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9887       const Type *OpPtrTy = 
9888         PointerType::getUnqual(II->getOperand(1)->getType());
9889       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9890       return new StoreInst(II->getOperand(1), Ptr);
9891     }
9892     break;
9893   case Intrinsic::x86_sse_storeu_ps:
9894   case Intrinsic::x86_sse2_storeu_pd:
9895   case Intrinsic::x86_sse2_storeu_dq:
9896     // Turn X86 storeu -> store if the pointer is known aligned.
9897     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9898       const Type *OpPtrTy = 
9899         PointerType::getUnqual(II->getOperand(2)->getType());
9900       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9901       return new StoreInst(II->getOperand(2), Ptr);
9902     }
9903     break;
9904     
9905   case Intrinsic::x86_sse_cvttss2si: {
9906     // These intrinsics only demands the 0th element of its input vector.  If
9907     // we can simplify the input based on that, do so now.
9908     unsigned VWidth =
9909       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9910     APInt DemandedElts(VWidth, 1);
9911     APInt UndefElts(VWidth, 0);
9912     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9913                                               UndefElts)) {
9914       II->setOperand(1, V);
9915       return II;
9916     }
9917     break;
9918   }
9919     
9920   case Intrinsic::ppc_altivec_vperm:
9921     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9922     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9923       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9924       
9925       // Check that all of the elements are integer constants or undefs.
9926       bool AllEltsOk = true;
9927       for (unsigned i = 0; i != 16; ++i) {
9928         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9929             !isa<UndefValue>(Mask->getOperand(i))) {
9930           AllEltsOk = false;
9931           break;
9932         }
9933       }
9934       
9935       if (AllEltsOk) {
9936         // Cast the input vectors to byte vectors.
9937         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9938         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9939         Value *Result = UndefValue::get(Op0->getType());
9940         
9941         // Only extract each element once.
9942         Value *ExtractedElts[32];
9943         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9944         
9945         for (unsigned i = 0; i != 16; ++i) {
9946           if (isa<UndefValue>(Mask->getOperand(i)))
9947             continue;
9948           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9949           Idx &= 31;  // Match the hardware behavior.
9950           
9951           if (ExtractedElts[Idx] == 0) {
9952             Instruction *Elt = 
9953               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9954                   ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
9955             InsertNewInstBefore(Elt, CI);
9956             ExtractedElts[Idx] = Elt;
9957           }
9958         
9959           // Insert this value into the result vector.
9960           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9961                                ConstantInt::get(Type::Int32Ty, i, false), 
9962                                "tmp");
9963           InsertNewInstBefore(cast<Instruction>(Result), CI);
9964         }
9965         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9966       }
9967     }
9968     break;
9969
9970   case Intrinsic::stackrestore: {
9971     // If the save is right next to the restore, remove the restore.  This can
9972     // happen when variable allocas are DCE'd.
9973     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9974       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9975         BasicBlock::iterator BI = SS;
9976         if (&*++BI == II)
9977           return EraseInstFromFunction(CI);
9978       }
9979     }
9980     
9981     // Scan down this block to see if there is another stack restore in the
9982     // same block without an intervening call/alloca.
9983     BasicBlock::iterator BI = II;
9984     TerminatorInst *TI = II->getParent()->getTerminator();
9985     bool CannotRemove = false;
9986     for (++BI; &*BI != TI; ++BI) {
9987       if (isa<AllocaInst>(BI)) {
9988         CannotRemove = true;
9989         break;
9990       }
9991       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9992         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9993           // If there is a stackrestore below this one, remove this one.
9994           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9995             return EraseInstFromFunction(CI);
9996           // Otherwise, ignore the intrinsic.
9997         } else {
9998           // If we found a non-intrinsic call, we can't remove the stack
9999           // restore.
10000           CannotRemove = true;
10001           break;
10002         }
10003       }
10004     }
10005     
10006     // If the stack restore is in a return/unwind block and if there are no
10007     // allocas or calls between the restore and the return, nuke the restore.
10008     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10009       return EraseInstFromFunction(CI);
10010     break;
10011   }
10012   }
10013
10014   return visitCallSite(II);
10015 }
10016
10017 // InvokeInst simplification
10018 //
10019 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10020   return visitCallSite(&II);
10021 }
10022
10023 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10024 /// passed through the varargs area, we can eliminate the use of the cast.
10025 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10026                                          const CastInst * const CI,
10027                                          const TargetData * const TD,
10028                                          const int ix) {
10029   if (!CI->isLosslessCast())
10030     return false;
10031
10032   // The size of ByVal arguments is derived from the type, so we
10033   // can't change to a type with a different size.  If the size were
10034   // passed explicitly we could avoid this check.
10035   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10036     return true;
10037
10038   const Type* SrcTy = 
10039             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10040   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10041   if (!SrcTy->isSized() || !DstTy->isSized())
10042     return false;
10043   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10044     return false;
10045   return true;
10046 }
10047
10048 // visitCallSite - Improvements for call and invoke instructions.
10049 //
10050 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10051   bool Changed = false;
10052
10053   // If the callee is a constexpr cast of a function, attempt to move the cast
10054   // to the arguments of the call/invoke.
10055   if (transformConstExprCastCall(CS)) return 0;
10056
10057   Value *Callee = CS.getCalledValue();
10058
10059   if (Function *CalleeF = dyn_cast<Function>(Callee))
10060     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10061       Instruction *OldCall = CS.getInstruction();
10062       // If the call and callee calling conventions don't match, this call must
10063       // be unreachable, as the call is undefined.
10064       new StoreInst(Context->getTrue(),
10065                 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
10066                                   OldCall);
10067       if (!OldCall->use_empty())
10068         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10069       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10070         return EraseInstFromFunction(*OldCall);
10071       return 0;
10072     }
10073
10074   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10075     // This instruction is not reachable, just remove it.  We insert a store to
10076     // undef so that we know that this code is not reachable, despite the fact
10077     // that we can't modify the CFG here.
10078     new StoreInst(Context->getTrue(),
10079                UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10080                   CS.getInstruction());
10081
10082     if (!CS.getInstruction()->use_empty())
10083       CS.getInstruction()->
10084         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10085
10086     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10087       // Don't break the CFG, insert a dummy cond branch.
10088       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10089                          Context->getTrue(), II);
10090     }
10091     return EraseInstFromFunction(*CS.getInstruction());
10092   }
10093
10094   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10095     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10096       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10097         return transformCallThroughTrampoline(CS);
10098
10099   const PointerType *PTy = cast<PointerType>(Callee->getType());
10100   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10101   if (FTy->isVarArg()) {
10102     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10103     // See if we can optimize any arguments passed through the varargs area of
10104     // the call.
10105     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10106            E = CS.arg_end(); I != E; ++I, ++ix) {
10107       CastInst *CI = dyn_cast<CastInst>(*I);
10108       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10109         *I = CI->getOperand(0);
10110         Changed = true;
10111       }
10112     }
10113   }
10114
10115   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10116     // Inline asm calls cannot throw - mark them 'nounwind'.
10117     CS.setDoesNotThrow();
10118     Changed = true;
10119   }
10120
10121   return Changed ? CS.getInstruction() : 0;
10122 }
10123
10124 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10125 // attempt to move the cast to the arguments of the call/invoke.
10126 //
10127 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10128   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10129   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10130   if (CE->getOpcode() != Instruction::BitCast || 
10131       !isa<Function>(CE->getOperand(0)))
10132     return false;
10133   Function *Callee = cast<Function>(CE->getOperand(0));
10134   Instruction *Caller = CS.getInstruction();
10135   const AttrListPtr &CallerPAL = CS.getAttributes();
10136
10137   // Okay, this is a cast from a function to a different type.  Unless doing so
10138   // would cause a type conversion of one of our arguments, change this call to
10139   // be a direct call with arguments casted to the appropriate types.
10140   //
10141   const FunctionType *FT = Callee->getFunctionType();
10142   const Type *OldRetTy = Caller->getType();
10143   const Type *NewRetTy = FT->getReturnType();
10144
10145   if (isa<StructType>(NewRetTy))
10146     return false; // TODO: Handle multiple return values.
10147
10148   // Check to see if we are changing the return type...
10149   if (OldRetTy != NewRetTy) {
10150     if (Callee->isDeclaration() &&
10151         // Conversion is ok if changing from one pointer type to another or from
10152         // a pointer to an integer of the same size.
10153         !((isa<PointerType>(OldRetTy) || !TD ||
10154            OldRetTy == TD->getIntPtrType()) &&
10155           (isa<PointerType>(NewRetTy) || !TD ||
10156            NewRetTy == TD->getIntPtrType())))
10157       return false;   // Cannot transform this return value.
10158
10159     if (!Caller->use_empty() &&
10160         // void -> non-void is handled specially
10161         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10162       return false;   // Cannot transform this return value.
10163
10164     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10165       Attributes RAttrs = CallerPAL.getRetAttributes();
10166       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10167         return false;   // Attribute not compatible with transformed value.
10168     }
10169
10170     // If the callsite is an invoke instruction, and the return value is used by
10171     // a PHI node in a successor, we cannot change the return type of the call
10172     // because there is no place to put the cast instruction (without breaking
10173     // the critical edge).  Bail out in this case.
10174     if (!Caller->use_empty())
10175       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10176         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10177              UI != E; ++UI)
10178           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10179             if (PN->getParent() == II->getNormalDest() ||
10180                 PN->getParent() == II->getUnwindDest())
10181               return false;
10182   }
10183
10184   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10185   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10186
10187   CallSite::arg_iterator AI = CS.arg_begin();
10188   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10189     const Type *ParamTy = FT->getParamType(i);
10190     const Type *ActTy = (*AI)->getType();
10191
10192     if (!CastInst::isCastable(ActTy, ParamTy))
10193       return false;   // Cannot transform this parameter value.
10194
10195     if (CallerPAL.getParamAttributes(i + 1) 
10196         & Attribute::typeIncompatible(ParamTy))
10197       return false;   // Attribute not compatible with transformed value.
10198
10199     // Converting from one pointer type to another or between a pointer and an
10200     // integer of the same size is safe even if we do not have a body.
10201     bool isConvertible = ActTy == ParamTy ||
10202       (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10203               (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10204     if (Callee->isDeclaration() && !isConvertible) return false;
10205   }
10206
10207   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10208       Callee->isDeclaration())
10209     return false;   // Do not delete arguments unless we have a function body.
10210
10211   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10212       !CallerPAL.isEmpty())
10213     // In this case we have more arguments than the new function type, but we
10214     // won't be dropping them.  Check that these extra arguments have attributes
10215     // that are compatible with being a vararg call argument.
10216     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10217       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10218         break;
10219       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10220       if (PAttrs & Attribute::VarArgsIncompatible)
10221         return false;
10222     }
10223
10224   // Okay, we decided that this is a safe thing to do: go ahead and start
10225   // inserting cast instructions as necessary...
10226   std::vector<Value*> Args;
10227   Args.reserve(NumActualArgs);
10228   SmallVector<AttributeWithIndex, 8> attrVec;
10229   attrVec.reserve(NumCommonArgs);
10230
10231   // Get any return attributes.
10232   Attributes RAttrs = CallerPAL.getRetAttributes();
10233
10234   // If the return value is not being used, the type may not be compatible
10235   // with the existing attributes.  Wipe out any problematic attributes.
10236   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10237
10238   // Add the new return attributes.
10239   if (RAttrs)
10240     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10241
10242   AI = CS.arg_begin();
10243   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10244     const Type *ParamTy = FT->getParamType(i);
10245     if ((*AI)->getType() == ParamTy) {
10246       Args.push_back(*AI);
10247     } else {
10248       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10249           false, ParamTy, false);
10250       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10251       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10252     }
10253
10254     // Add any parameter attributes.
10255     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10256       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10257   }
10258
10259   // If the function takes more arguments than the call was taking, add them
10260   // now...
10261   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10262     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10263
10264   // If we are removing arguments to the function, emit an obnoxious warning...
10265   if (FT->getNumParams() < NumActualArgs) {
10266     if (!FT->isVarArg()) {
10267       errs() << "WARNING: While resolving call to function '"
10268              << Callee->getName() << "' arguments were dropped!\n";
10269     } else {
10270       // Add all of the arguments in their promoted form to the arg list...
10271       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10272         const Type *PTy = getPromotedType((*AI)->getType());
10273         if (PTy != (*AI)->getType()) {
10274           // Must promote to pass through va_arg area!
10275           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10276                                                                 PTy, false);
10277           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10278           InsertNewInstBefore(Cast, *Caller);
10279           Args.push_back(Cast);
10280         } else {
10281           Args.push_back(*AI);
10282         }
10283
10284         // Add any parameter attributes.
10285         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10286           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10287       }
10288     }
10289   }
10290
10291   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10292     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10293
10294   if (NewRetTy == Type::VoidTy)
10295     Caller->setName("");   // Void type should not have a name.
10296
10297   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10298                                                      attrVec.end());
10299
10300   Instruction *NC;
10301   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10302     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10303                             Args.begin(), Args.end(),
10304                             Caller->getName(), Caller);
10305     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10306     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10307   } else {
10308     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10309                           Caller->getName(), Caller);
10310     CallInst *CI = cast<CallInst>(Caller);
10311     if (CI->isTailCall())
10312       cast<CallInst>(NC)->setTailCall();
10313     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10314     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10315   }
10316
10317   // Insert a cast of the return type as necessary.
10318   Value *NV = NC;
10319   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10320     if (NV->getType() != Type::VoidTy) {
10321       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10322                                                             OldRetTy, false);
10323       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10324
10325       // If this is an invoke instruction, we should insert it after the first
10326       // non-phi, instruction in the normal successor block.
10327       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10328         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10329         InsertNewInstBefore(NC, *I);
10330       } else {
10331         // Otherwise, it's a call, just insert cast right after the call instr
10332         InsertNewInstBefore(NC, *Caller);
10333       }
10334       AddUsersToWorkList(*Caller);
10335     } else {
10336       NV = UndefValue::get(Caller->getType());
10337     }
10338   }
10339
10340   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10341     Caller->replaceAllUsesWith(NV);
10342   Caller->eraseFromParent();
10343   RemoveFromWorkList(Caller);
10344   return true;
10345 }
10346
10347 // transformCallThroughTrampoline - Turn a call to a function created by the
10348 // init_trampoline intrinsic into a direct call to the underlying function.
10349 //
10350 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10351   Value *Callee = CS.getCalledValue();
10352   const PointerType *PTy = cast<PointerType>(Callee->getType());
10353   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10354   const AttrListPtr &Attrs = CS.getAttributes();
10355
10356   // If the call already has the 'nest' attribute somewhere then give up -
10357   // otherwise 'nest' would occur twice after splicing in the chain.
10358   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10359     return 0;
10360
10361   IntrinsicInst *Tramp =
10362     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10363
10364   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10365   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10366   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10367
10368   const AttrListPtr &NestAttrs = NestF->getAttributes();
10369   if (!NestAttrs.isEmpty()) {
10370     unsigned NestIdx = 1;
10371     const Type *NestTy = 0;
10372     Attributes NestAttr = Attribute::None;
10373
10374     // Look for a parameter marked with the 'nest' attribute.
10375     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10376          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10377       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10378         // Record the parameter type and any other attributes.
10379         NestTy = *I;
10380         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10381         break;
10382       }
10383
10384     if (NestTy) {
10385       Instruction *Caller = CS.getInstruction();
10386       std::vector<Value*> NewArgs;
10387       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10388
10389       SmallVector<AttributeWithIndex, 8> NewAttrs;
10390       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10391
10392       // Insert the nest argument into the call argument list, which may
10393       // mean appending it.  Likewise for attributes.
10394
10395       // Add any result attributes.
10396       if (Attributes Attr = Attrs.getRetAttributes())
10397         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10398
10399       {
10400         unsigned Idx = 1;
10401         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10402         do {
10403           if (Idx == NestIdx) {
10404             // Add the chain argument and attributes.
10405             Value *NestVal = Tramp->getOperand(3);
10406             if (NestVal->getType() != NestTy)
10407               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10408             NewArgs.push_back(NestVal);
10409             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10410           }
10411
10412           if (I == E)
10413             break;
10414
10415           // Add the original argument and attributes.
10416           NewArgs.push_back(*I);
10417           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10418             NewAttrs.push_back
10419               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10420
10421           ++Idx, ++I;
10422         } while (1);
10423       }
10424
10425       // Add any function attributes.
10426       if (Attributes Attr = Attrs.getFnAttributes())
10427         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10428
10429       // The trampoline may have been bitcast to a bogus type (FTy).
10430       // Handle this by synthesizing a new function type, equal to FTy
10431       // with the chain parameter inserted.
10432
10433       std::vector<const Type*> NewTypes;
10434       NewTypes.reserve(FTy->getNumParams()+1);
10435
10436       // Insert the chain's type into the list of parameter types, which may
10437       // mean appending it.
10438       {
10439         unsigned Idx = 1;
10440         FunctionType::param_iterator I = FTy->param_begin(),
10441           E = FTy->param_end();
10442
10443         do {
10444           if (Idx == NestIdx)
10445             // Add the chain's type.
10446             NewTypes.push_back(NestTy);
10447
10448           if (I == E)
10449             break;
10450
10451           // Add the original type.
10452           NewTypes.push_back(*I);
10453
10454           ++Idx, ++I;
10455         } while (1);
10456       }
10457
10458       // Replace the trampoline call with a direct call.  Let the generic
10459       // code sort out any function type mismatches.
10460       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10461                                                 FTy->isVarArg());
10462       Constant *NewCallee =
10463         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10464         NestF : ConstantExpr::getBitCast(NestF, 
10465                                          PointerType::getUnqual(NewFTy));
10466       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10467                                                    NewAttrs.end());
10468
10469       Instruction *NewCaller;
10470       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10471         NewCaller = InvokeInst::Create(NewCallee,
10472                                        II->getNormalDest(), II->getUnwindDest(),
10473                                        NewArgs.begin(), NewArgs.end(),
10474                                        Caller->getName(), Caller);
10475         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10476         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10477       } else {
10478         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10479                                      Caller->getName(), Caller);
10480         if (cast<CallInst>(Caller)->isTailCall())
10481           cast<CallInst>(NewCaller)->setTailCall();
10482         cast<CallInst>(NewCaller)->
10483           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10484         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10485       }
10486       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10487         Caller->replaceAllUsesWith(NewCaller);
10488       Caller->eraseFromParent();
10489       RemoveFromWorkList(Caller);
10490       return 0;
10491     }
10492   }
10493
10494   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10495   // parameter, there is no need to adjust the argument list.  Let the generic
10496   // code sort out any function type mismatches.
10497   Constant *NewCallee =
10498     NestF->getType() == PTy ? NestF : 
10499                               ConstantExpr::getBitCast(NestF, PTy);
10500   CS.setCalledFunction(NewCallee);
10501   return CS.getInstruction();
10502 }
10503
10504 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10505 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10506 /// and a single binop.
10507 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10508   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10509   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10510   unsigned Opc = FirstInst->getOpcode();
10511   Value *LHSVal = FirstInst->getOperand(0);
10512   Value *RHSVal = FirstInst->getOperand(1);
10513     
10514   const Type *LHSType = LHSVal->getType();
10515   const Type *RHSType = RHSVal->getType();
10516   
10517   // Scan to see if all operands are the same opcode, all have one use, and all
10518   // kill their operands (i.e. the operands have one use).
10519   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10520     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10521     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10522         // Verify type of the LHS matches so we don't fold cmp's of different
10523         // types or GEP's with different index types.
10524         I->getOperand(0)->getType() != LHSType ||
10525         I->getOperand(1)->getType() != RHSType)
10526       return 0;
10527
10528     // If they are CmpInst instructions, check their predicates
10529     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10530       if (cast<CmpInst>(I)->getPredicate() !=
10531           cast<CmpInst>(FirstInst)->getPredicate())
10532         return 0;
10533     
10534     // Keep track of which operand needs a phi node.
10535     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10536     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10537   }
10538   
10539   // Otherwise, this is safe to transform!
10540   
10541   Value *InLHS = FirstInst->getOperand(0);
10542   Value *InRHS = FirstInst->getOperand(1);
10543   PHINode *NewLHS = 0, *NewRHS = 0;
10544   if (LHSVal == 0) {
10545     NewLHS = PHINode::Create(LHSType,
10546                              FirstInst->getOperand(0)->getName() + ".pn");
10547     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10548     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10549     InsertNewInstBefore(NewLHS, PN);
10550     LHSVal = NewLHS;
10551   }
10552   
10553   if (RHSVal == 0) {
10554     NewRHS = PHINode::Create(RHSType,
10555                              FirstInst->getOperand(1)->getName() + ".pn");
10556     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10557     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10558     InsertNewInstBefore(NewRHS, PN);
10559     RHSVal = NewRHS;
10560   }
10561   
10562   // Add all operands to the new PHIs.
10563   if (NewLHS || NewRHS) {
10564     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10565       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10566       if (NewLHS) {
10567         Value *NewInLHS = InInst->getOperand(0);
10568         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10569       }
10570       if (NewRHS) {
10571         Value *NewInRHS = InInst->getOperand(1);
10572         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10573       }
10574     }
10575   }
10576     
10577   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10578     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10579   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10580   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10581                          LHSVal, RHSVal);
10582 }
10583
10584 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10585   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10586   
10587   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10588                                         FirstInst->op_end());
10589   // This is true if all GEP bases are allocas and if all indices into them are
10590   // constants.
10591   bool AllBasePointersAreAllocas = true;
10592   
10593   // Scan to see if all operands are the same opcode, all have one use, and all
10594   // kill their operands (i.e. the operands have one use).
10595   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10596     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10597     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10598       GEP->getNumOperands() != FirstInst->getNumOperands())
10599       return 0;
10600
10601     // Keep track of whether or not all GEPs are of alloca pointers.
10602     if (AllBasePointersAreAllocas &&
10603         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10604          !GEP->hasAllConstantIndices()))
10605       AllBasePointersAreAllocas = false;
10606     
10607     // Compare the operand lists.
10608     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10609       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10610         continue;
10611       
10612       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10613       // if one of the PHIs has a constant for the index.  The index may be
10614       // substantially cheaper to compute for the constants, so making it a
10615       // variable index could pessimize the path.  This also handles the case
10616       // for struct indices, which must always be constant.
10617       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10618           isa<ConstantInt>(GEP->getOperand(op)))
10619         return 0;
10620       
10621       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10622         return 0;
10623       FixedOperands[op] = 0;  // Needs a PHI.
10624     }
10625   }
10626   
10627   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10628   // bother doing this transformation.  At best, this will just save a bit of
10629   // offset calculation, but all the predecessors will have to materialize the
10630   // stack address into a register anyway.  We'd actually rather *clone* the
10631   // load up into the predecessors so that we have a load of a gep of an alloca,
10632   // which can usually all be folded into the load.
10633   if (AllBasePointersAreAllocas)
10634     return 0;
10635   
10636   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10637   // that is variable.
10638   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10639   
10640   bool HasAnyPHIs = false;
10641   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10642     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10643     Value *FirstOp = FirstInst->getOperand(i);
10644     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10645                                      FirstOp->getName()+".pn");
10646     InsertNewInstBefore(NewPN, PN);
10647     
10648     NewPN->reserveOperandSpace(e);
10649     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10650     OperandPhis[i] = NewPN;
10651     FixedOperands[i] = NewPN;
10652     HasAnyPHIs = true;
10653   }
10654
10655   
10656   // Add all operands to the new PHIs.
10657   if (HasAnyPHIs) {
10658     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10659       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10660       BasicBlock *InBB = PN.getIncomingBlock(i);
10661       
10662       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10663         if (PHINode *OpPhi = OperandPhis[op])
10664           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10665     }
10666   }
10667   
10668   Value *Base = FixedOperands[0];
10669   GetElementPtrInst *GEP =
10670     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10671                               FixedOperands.end());
10672   if (cast<GEPOperator>(FirstInst)->isInBounds())
10673     cast<GEPOperator>(GEP)->setIsInBounds(true);
10674   return GEP;
10675 }
10676
10677
10678 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10679 /// sink the load out of the block that defines it.  This means that it must be
10680 /// obvious the value of the load is not changed from the point of the load to
10681 /// the end of the block it is in.
10682 ///
10683 /// Finally, it is safe, but not profitable, to sink a load targetting a
10684 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10685 /// to a register.
10686 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10687   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10688   
10689   for (++BBI; BBI != E; ++BBI)
10690     if (BBI->mayWriteToMemory())
10691       return false;
10692   
10693   // Check for non-address taken alloca.  If not address-taken already, it isn't
10694   // profitable to do this xform.
10695   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10696     bool isAddressTaken = false;
10697     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10698          UI != E; ++UI) {
10699       if (isa<LoadInst>(UI)) continue;
10700       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10701         // If storing TO the alloca, then the address isn't taken.
10702         if (SI->getOperand(1) == AI) continue;
10703       }
10704       isAddressTaken = true;
10705       break;
10706     }
10707     
10708     if (!isAddressTaken && AI->isStaticAlloca())
10709       return false;
10710   }
10711   
10712   // If this load is a load from a GEP with a constant offset from an alloca,
10713   // then we don't want to sink it.  In its present form, it will be
10714   // load [constant stack offset].  Sinking it will cause us to have to
10715   // materialize the stack addresses in each predecessor in a register only to
10716   // do a shared load from register in the successor.
10717   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10718     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10719       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10720         return false;
10721   
10722   return true;
10723 }
10724
10725
10726 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10727 // operator and they all are only used by the PHI, PHI together their
10728 // inputs, and do the operation once, to the result of the PHI.
10729 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10730   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10731
10732   // Scan the instruction, looking for input operations that can be folded away.
10733   // If all input operands to the phi are the same instruction (e.g. a cast from
10734   // the same type or "+42") we can pull the operation through the PHI, reducing
10735   // code size and simplifying code.
10736   Constant *ConstantOp = 0;
10737   const Type *CastSrcTy = 0;
10738   bool isVolatile = false;
10739   if (isa<CastInst>(FirstInst)) {
10740     CastSrcTy = FirstInst->getOperand(0)->getType();
10741   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10742     // Can fold binop, compare or shift here if the RHS is a constant, 
10743     // otherwise call FoldPHIArgBinOpIntoPHI.
10744     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10745     if (ConstantOp == 0)
10746       return FoldPHIArgBinOpIntoPHI(PN);
10747   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10748     isVolatile = LI->isVolatile();
10749     // We can't sink the load if the loaded value could be modified between the
10750     // load and the PHI.
10751     if (LI->getParent() != PN.getIncomingBlock(0) ||
10752         !isSafeAndProfitableToSinkLoad(LI))
10753       return 0;
10754     
10755     // If the PHI is of volatile loads and the load block has multiple
10756     // successors, sinking it would remove a load of the volatile value from
10757     // the path through the other successor.
10758     if (isVolatile &&
10759         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10760       return 0;
10761     
10762   } else if (isa<GetElementPtrInst>(FirstInst)) {
10763     return FoldPHIArgGEPIntoPHI(PN);
10764   } else {
10765     return 0;  // Cannot fold this operation.
10766   }
10767
10768   // Check to see if all arguments are the same operation.
10769   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10770     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10771     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10772     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10773       return 0;
10774     if (CastSrcTy) {
10775       if (I->getOperand(0)->getType() != CastSrcTy)
10776         return 0;  // Cast operation must match.
10777     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10778       // We can't sink the load if the loaded value could be modified between 
10779       // the load and the PHI.
10780       if (LI->isVolatile() != isVolatile ||
10781           LI->getParent() != PN.getIncomingBlock(i) ||
10782           !isSafeAndProfitableToSinkLoad(LI))
10783         return 0;
10784       
10785       // If the PHI is of volatile loads and the load block has multiple
10786       // successors, sinking it would remove a load of the volatile value from
10787       // the path through the other successor.
10788       if (isVolatile &&
10789           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10790         return 0;
10791       
10792     } else if (I->getOperand(1) != ConstantOp) {
10793       return 0;
10794     }
10795   }
10796
10797   // Okay, they are all the same operation.  Create a new PHI node of the
10798   // correct type, and PHI together all of the LHS's of the instructions.
10799   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10800                                    PN.getName()+".in");
10801   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10802
10803   Value *InVal = FirstInst->getOperand(0);
10804   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10805
10806   // Add all operands to the new PHI.
10807   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10808     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10809     if (NewInVal != InVal)
10810       InVal = 0;
10811     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10812   }
10813
10814   Value *PhiVal;
10815   if (InVal) {
10816     // The new PHI unions all of the same values together.  This is really
10817     // common, so we handle it intelligently here for compile-time speed.
10818     PhiVal = InVal;
10819     delete NewPN;
10820   } else {
10821     InsertNewInstBefore(NewPN, PN);
10822     PhiVal = NewPN;
10823   }
10824
10825   // Insert and return the new operation.
10826   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10827     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10828   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10829     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10830   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10831     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10832                            PhiVal, ConstantOp);
10833   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10834   
10835   // If this was a volatile load that we are merging, make sure to loop through
10836   // and mark all the input loads as non-volatile.  If we don't do this, we will
10837   // insert a new volatile load and the old ones will not be deletable.
10838   if (isVolatile)
10839     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10840       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10841   
10842   return new LoadInst(PhiVal, "", isVolatile);
10843 }
10844
10845 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10846 /// that is dead.
10847 static bool DeadPHICycle(PHINode *PN,
10848                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10849   if (PN->use_empty()) return true;
10850   if (!PN->hasOneUse()) return false;
10851
10852   // Remember this node, and if we find the cycle, return.
10853   if (!PotentiallyDeadPHIs.insert(PN))
10854     return true;
10855   
10856   // Don't scan crazily complex things.
10857   if (PotentiallyDeadPHIs.size() == 16)
10858     return false;
10859
10860   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10861     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10862
10863   return false;
10864 }
10865
10866 /// PHIsEqualValue - Return true if this phi node is always equal to
10867 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10868 ///   z = some value; x = phi (y, z); y = phi (x, z)
10869 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10870                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10871   // See if we already saw this PHI node.
10872   if (!ValueEqualPHIs.insert(PN))
10873     return true;
10874   
10875   // Don't scan crazily complex things.
10876   if (ValueEqualPHIs.size() == 16)
10877     return false;
10878  
10879   // Scan the operands to see if they are either phi nodes or are equal to
10880   // the value.
10881   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10882     Value *Op = PN->getIncomingValue(i);
10883     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10884       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10885         return false;
10886     } else if (Op != NonPhiInVal)
10887       return false;
10888   }
10889   
10890   return true;
10891 }
10892
10893
10894 // PHINode simplification
10895 //
10896 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10897   // If LCSSA is around, don't mess with Phi nodes
10898   if (MustPreserveLCSSA) return 0;
10899   
10900   if (Value *V = PN.hasConstantValue())
10901     return ReplaceInstUsesWith(PN, V);
10902
10903   // If all PHI operands are the same operation, pull them through the PHI,
10904   // reducing code size.
10905   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10906       isa<Instruction>(PN.getIncomingValue(1)) &&
10907       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10908       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10909       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10910       // than themselves more than once.
10911       PN.getIncomingValue(0)->hasOneUse())
10912     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10913       return Result;
10914
10915   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10916   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10917   // PHI)... break the cycle.
10918   if (PN.hasOneUse()) {
10919     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10920     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10921       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10922       PotentiallyDeadPHIs.insert(&PN);
10923       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10924         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10925     }
10926    
10927     // If this phi has a single use, and if that use just computes a value for
10928     // the next iteration of a loop, delete the phi.  This occurs with unused
10929     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10930     // common case here is good because the only other things that catch this
10931     // are induction variable analysis (sometimes) and ADCE, which is only run
10932     // late.
10933     if (PHIUser->hasOneUse() &&
10934         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10935         PHIUser->use_back() == &PN) {
10936       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10937     }
10938   }
10939
10940   // We sometimes end up with phi cycles that non-obviously end up being the
10941   // same value, for example:
10942   //   z = some value; x = phi (y, z); y = phi (x, z)
10943   // where the phi nodes don't necessarily need to be in the same block.  Do a
10944   // quick check to see if the PHI node only contains a single non-phi value, if
10945   // so, scan to see if the phi cycle is actually equal to that value.
10946   {
10947     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10948     // Scan for the first non-phi operand.
10949     while (InValNo != NumOperandVals && 
10950            isa<PHINode>(PN.getIncomingValue(InValNo)))
10951       ++InValNo;
10952
10953     if (InValNo != NumOperandVals) {
10954       Value *NonPhiInVal = PN.getOperand(InValNo);
10955       
10956       // Scan the rest of the operands to see if there are any conflicts, if so
10957       // there is no need to recursively scan other phis.
10958       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10959         Value *OpVal = PN.getIncomingValue(InValNo);
10960         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10961           break;
10962       }
10963       
10964       // If we scanned over all operands, then we have one unique value plus
10965       // phi values.  Scan PHI nodes to see if they all merge in each other or
10966       // the value.
10967       if (InValNo == NumOperandVals) {
10968         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10969         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10970           return ReplaceInstUsesWith(PN, NonPhiInVal);
10971       }
10972     }
10973   }
10974   return 0;
10975 }
10976
10977 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10978                                    Instruction *InsertPoint,
10979                                    InstCombiner *IC) {
10980   unsigned PtrSize = DTy->getScalarSizeInBits();
10981   unsigned VTySize = V->getType()->getScalarSizeInBits();
10982   // We must cast correctly to the pointer type. Ensure that we
10983   // sign extend the integer value if it is smaller as this is
10984   // used for address computation.
10985   Instruction::CastOps opcode = 
10986      (VTySize < PtrSize ? Instruction::SExt :
10987       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10988   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10989 }
10990
10991
10992 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10993   Value *PtrOp = GEP.getOperand(0);
10994   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10995   // If so, eliminate the noop.
10996   if (GEP.getNumOperands() == 1)
10997     return ReplaceInstUsesWith(GEP, PtrOp);
10998
10999   if (isa<UndefValue>(GEP.getOperand(0)))
11000     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11001
11002   bool HasZeroPointerIndex = false;
11003   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11004     HasZeroPointerIndex = C->isNullValue();
11005
11006   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11007     return ReplaceInstUsesWith(GEP, PtrOp);
11008
11009   // Eliminate unneeded casts for indices.
11010   bool MadeChange = false;
11011   
11012   gep_type_iterator GTI = gep_type_begin(GEP);
11013   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11014        i != e; ++i, ++GTI) {
11015     if (TD && isa<SequentialType>(*GTI)) {
11016       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11017         if (CI->getOpcode() == Instruction::ZExt ||
11018             CI->getOpcode() == Instruction::SExt) {
11019           const Type *SrcTy = CI->getOperand(0)->getType();
11020           // We can eliminate a cast from i32 to i64 iff the target 
11021           // is a 32-bit pointer target.
11022           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11023             MadeChange = true;
11024             *i = CI->getOperand(0);
11025           }
11026         }
11027       }
11028       // If we are using a wider index than needed for this platform, shrink it
11029       // to what we need.  If narrower, sign-extend it to what we need.
11030       // If the incoming value needs a cast instruction,
11031       // insert it.  This explicit cast can make subsequent optimizations more
11032       // obvious.
11033       Value *Op = *i;
11034       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11035         if (Constant *C = dyn_cast<Constant>(Op)) {
11036           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
11037           MadeChange = true;
11038         } else {
11039           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11040                                 GEP);
11041           *i = Op;
11042           MadeChange = true;
11043         }
11044       } else if (TD->getTypeSizeInBits(Op->getType()) 
11045                   < TD->getPointerSizeInBits()) {
11046         if (Constant *C = dyn_cast<Constant>(Op)) {
11047           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
11048           MadeChange = true;
11049         } else {
11050           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11051                                 GEP);
11052           *i = Op;
11053           MadeChange = true;
11054         }
11055       }
11056     }
11057   }
11058   if (MadeChange) return &GEP;
11059
11060   // Combine Indices - If the source pointer to this getelementptr instruction
11061   // is a getelementptr instruction, combine the indices of the two
11062   // getelementptr instructions into a single instruction.
11063   //
11064   SmallVector<Value*, 8> SrcGEPOperands;
11065   bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11066   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11067     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11068     if (!Src->isInBounds())
11069       BothInBounds = false;
11070   }
11071
11072   if (!SrcGEPOperands.empty()) {
11073     // Note that if our source is a gep chain itself that we wait for that
11074     // chain to be resolved before we perform this transformation.  This
11075     // avoids us creating a TON of code in some cases.
11076     //
11077     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11078         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11079       return 0;   // Wait until our source is folded to completion.
11080
11081     SmallVector<Value*, 8> Indices;
11082
11083     // Find out whether the last index in the source GEP is a sequential idx.
11084     bool EndsWithSequential = false;
11085     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11086            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11087       EndsWithSequential = !isa<StructType>(*I);
11088
11089     // Can we combine the two pointer arithmetics offsets?
11090     if (EndsWithSequential) {
11091       // Replace: gep (gep %P, long B), long A, ...
11092       // With:    T = long A+B; gep %P, T, ...
11093       //
11094       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11095       if (SO1 == Context->getNullValue(SO1->getType())) {
11096         Sum = GO1;
11097       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11098         Sum = SO1;
11099       } else {
11100         // If they aren't the same type, convert both to an integer of the
11101         // target's pointer size.
11102         if (SO1->getType() != GO1->getType()) {
11103           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11104             SO1 =
11105                 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11106           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11107             GO1 =
11108                 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11109           } else if (TD) {
11110             unsigned PS = TD->getPointerSizeInBits();
11111             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11112               // Convert GO1 to SO1's type.
11113               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11114
11115             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11116               // Convert SO1 to GO1's type.
11117               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11118             } else {
11119               const Type *PT = TD->getIntPtrType();
11120               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11121               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11122             }
11123           }
11124         }
11125         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11126           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), 
11127                                             cast<Constant>(GO1));
11128         else {
11129           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11130           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11131         }
11132       }
11133
11134       // Recycle the GEP we already have if possible.
11135       if (SrcGEPOperands.size() == 2) {
11136         GEP.setOperand(0, SrcGEPOperands[0]);
11137         GEP.setOperand(1, Sum);
11138         return &GEP;
11139       } else {
11140         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11141                        SrcGEPOperands.end()-1);
11142         Indices.push_back(Sum);
11143         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11144       }
11145     } else if (isa<Constant>(*GEP.idx_begin()) &&
11146                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11147                SrcGEPOperands.size() != 1) {
11148       // Otherwise we can do the fold if the first index of the GEP is a zero
11149       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11150                      SrcGEPOperands.end());
11151       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11152     }
11153
11154     if (!Indices.empty()) {
11155       GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11156                                                             Indices.begin(),
11157                                                             Indices.end(),
11158                                                             GEP.getName());
11159       if (BothInBounds)
11160         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11161       return NewGEP;
11162     }
11163
11164   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11165     // GEP of global variable.  If all of the indices for this GEP are
11166     // constants, we can promote this to a constexpr instead of an instruction.
11167
11168     // Scan for nonconstants...
11169     SmallVector<Constant*, 8> Indices;
11170     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11171     for (; I != E && isa<Constant>(*I); ++I)
11172       Indices.push_back(cast<Constant>(*I));
11173
11174     if (I == E) {  // If they are all constants...
11175       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11176                                                     &Indices[0],Indices.size());
11177
11178       // Replace all uses of the GEP with the new constexpr...
11179       return ReplaceInstUsesWith(GEP, CE);
11180     }
11181   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11182     if (!isa<PointerType>(X->getType())) {
11183       // Not interesting.  Source pointer must be a cast from pointer.
11184     } else if (HasZeroPointerIndex) {
11185       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11186       // into     : GEP [10 x i8]* X, i32 0, ...
11187       //
11188       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11189       //           into     : GEP i8* X, ...
11190       // 
11191       // This occurs when the program declares an array extern like "int X[];"
11192       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11193       const PointerType *XTy = cast<PointerType>(X->getType());
11194       if (const ArrayType *CATy =
11195           dyn_cast<ArrayType>(CPTy->getElementType())) {
11196         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11197         if (CATy->getElementType() == XTy->getElementType()) {
11198           // -> GEP i8* X, ...
11199           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11200           GetElementPtrInst *NewGEP =
11201             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11202                                       GEP.getName());
11203           if (cast<GEPOperator>(&GEP)->isInBounds())
11204             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11205           return NewGEP;
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 (TD && 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         GetElementPtrInst *NewGEP =
11233           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11234         if (cast<GEPOperator>(&GEP)->isInBounds())
11235           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11236         Value *V = InsertNewInstBefore(NewGEP, GEP);
11237         // V and GEP are both pointer types --> BitCast
11238         return new BitCastInst(V, GEP.getType());
11239       }
11240       
11241       // Transform things like:
11242       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11243       //   (where tmp = 8*tmp2) into:
11244       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11245       
11246       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11247         uint64_t ArrayEltSize =
11248             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11249         
11250         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11251         // allow either a mul, shift, or constant here.
11252         Value *NewIdx = 0;
11253         ConstantInt *Scale = 0;
11254         if (ArrayEltSize == 1) {
11255           NewIdx = GEP.getOperand(1);
11256           Scale = 
11257                ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11258         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11259           NewIdx = ConstantInt::get(CI->getType(), 1);
11260           Scale = CI;
11261         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11262           if (Inst->getOpcode() == Instruction::Shl &&
11263               isa<ConstantInt>(Inst->getOperand(1))) {
11264             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11265             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11266             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11267                                      1ULL << ShAmtVal);
11268             NewIdx = Inst->getOperand(0);
11269           } else if (Inst->getOpcode() == Instruction::Mul &&
11270                      isa<ConstantInt>(Inst->getOperand(1))) {
11271             Scale = cast<ConstantInt>(Inst->getOperand(1));
11272             NewIdx = Inst->getOperand(0);
11273           }
11274         }
11275         
11276         // If the index will be to exactly the right offset with the scale taken
11277         // out, perform the transformation. Note, we don't know whether Scale is
11278         // signed or not. We'll use unsigned version of division/modulo
11279         // operation after making sure Scale doesn't have the sign bit set.
11280         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11281             Scale->getZExtValue() % ArrayEltSize == 0) {
11282           Scale = ConstantInt::get(Scale->getType(),
11283                                    Scale->getZExtValue() / ArrayEltSize);
11284           if (Scale->getZExtValue() != 1) {
11285             Constant *C =
11286                    ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11287                                                        false /*ZExt*/);
11288             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11289             NewIdx = InsertNewInstBefore(Sc, GEP);
11290           }
11291
11292           // Insert the new GEP instruction.
11293           Value *Idx[2];
11294           Idx[0] = Context->getNullValue(Type::Int32Ty);
11295           Idx[1] = NewIdx;
11296           Instruction *NewGEP =
11297             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11298           if (cast<GEPOperator>(&GEP)->isInBounds())
11299             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11300           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11301           // The NewGEP must be pointer typed, so must the old one -> BitCast
11302           return new BitCastInst(NewGEP, GEP.getType());
11303         }
11304       }
11305     }
11306   }
11307   
11308   /// See if we can simplify:
11309   ///   X = bitcast A to B*
11310   ///   Y = gep X, <...constant indices...>
11311   /// into a gep of the original struct.  This is important for SROA and alias
11312   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11313   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11314     if (TD &&
11315         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11316       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11317       // a constant back from EmitGEPOffset.
11318       ConstantInt *OffsetV =
11319                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11320       int64_t Offset = OffsetV->getSExtValue();
11321       
11322       // If this GEP instruction doesn't move the pointer, just replace the GEP
11323       // with a bitcast of the real input to the dest type.
11324       if (Offset == 0) {
11325         // If the bitcast is of an allocation, and the allocation will be
11326         // converted to match the type of the cast, don't touch this.
11327         if (isa<AllocationInst>(BCI->getOperand(0))) {
11328           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11329           if (Instruction *I = visitBitCast(*BCI)) {
11330             if (I != BCI) {
11331               I->takeName(BCI);
11332               BCI->getParent()->getInstList().insert(BCI, I);
11333               ReplaceInstUsesWith(*BCI, I);
11334             }
11335             return &GEP;
11336           }
11337         }
11338         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11339       }
11340       
11341       // Otherwise, if the offset is non-zero, we need to find out if there is a
11342       // field at Offset in 'A's type.  If so, we can pull the cast through the
11343       // GEP.
11344       SmallVector<Value*, 8> NewIndices;
11345       const Type *InTy =
11346         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11347       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11348         Instruction *NGEP =
11349            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11350                                      NewIndices.end());
11351         if (NGEP->getType() == GEP.getType()) return NGEP;
11352         if (cast<GEPOperator>(&GEP)->isInBounds())
11353           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11354         InsertNewInstBefore(NGEP, GEP);
11355         NGEP->takeName(&GEP);
11356         return new BitCastInst(NGEP, GEP.getType());
11357       }
11358     }
11359   }    
11360     
11361   return 0;
11362 }
11363
11364 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11365   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11366   if (AI.isArrayAllocation()) {  // Check C != 1
11367     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11368       const Type *NewTy = 
11369         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11370       AllocationInst *New = 0;
11371
11372       // Create and insert the replacement instruction...
11373       if (isa<MallocInst>(AI))
11374         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11375       else {
11376         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11377         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11378       }
11379
11380       InsertNewInstBefore(New, AI);
11381
11382       // Scan to the end of the allocation instructions, to skip over a block of
11383       // allocas if possible...also skip interleaved debug info
11384       //
11385       BasicBlock::iterator It = New;
11386       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11387
11388       // Now that I is pointing to the first non-allocation-inst in the block,
11389       // insert our getelementptr instruction...
11390       //
11391       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11392       Value *Idx[2];
11393       Idx[0] = NullIdx;
11394       Idx[1] = NullIdx;
11395       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11396                                            New->getName()+".sub", It);
11397       cast<GEPOperator>(V)->setIsInBounds(true);
11398
11399       // Now make everything use the getelementptr instead of the original
11400       // allocation.
11401       return ReplaceInstUsesWith(AI, V);
11402     } else if (isa<UndefValue>(AI.getArraySize())) {
11403       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11404     }
11405   }
11406
11407   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11408     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11409     // Note that we only do this for alloca's, because malloc should allocate
11410     // and return a unique pointer, even for a zero byte allocation.
11411     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11412       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11413
11414     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11415     if (AI.getAlignment() == 0)
11416       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11417   }
11418
11419   return 0;
11420 }
11421
11422 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11423   Value *Op = FI.getOperand(0);
11424
11425   // free undef -> unreachable.
11426   if (isa<UndefValue>(Op)) {
11427     // Insert a new store to null because we cannot modify the CFG here.
11428     new StoreInst(Context->getTrue(),
11429            UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11430     return EraseInstFromFunction(FI);
11431   }
11432   
11433   // If we have 'free null' delete the instruction.  This can happen in stl code
11434   // when lots of inlining happens.
11435   if (isa<ConstantPointerNull>(Op))
11436     return EraseInstFromFunction(FI);
11437   
11438   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11439   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11440     FI.setOperand(0, CI->getOperand(0));
11441     return &FI;
11442   }
11443   
11444   // Change free (gep X, 0,0,0,0) into free(X)
11445   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11446     if (GEPI->hasAllZeroIndices()) {
11447       AddToWorkList(GEPI);
11448       FI.setOperand(0, GEPI->getOperand(0));
11449       return &FI;
11450     }
11451   }
11452   
11453   // Change free(malloc) into nothing, if the malloc has a single use.
11454   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11455     if (MI->hasOneUse()) {
11456       EraseInstFromFunction(FI);
11457       return EraseInstFromFunction(*MI);
11458     }
11459
11460   return 0;
11461 }
11462
11463
11464 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11465 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11466                                         const TargetData *TD) {
11467   User *CI = cast<User>(LI.getOperand(0));
11468   Value *CastOp = CI->getOperand(0);
11469   LLVMContext *Context = IC.getContext();
11470
11471   if (TD) {
11472     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11473       // Instead of loading constant c string, use corresponding integer value
11474       // directly if string length is small enough.
11475       std::string Str;
11476       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11477         unsigned len = Str.length();
11478         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11479         unsigned numBits = Ty->getPrimitiveSizeInBits();
11480         // Replace LI with immediate integer store.
11481         if ((numBits >> 3) == len + 1) {
11482           APInt StrVal(numBits, 0);
11483           APInt SingleChar(numBits, 0);
11484           if (TD->isLittleEndian()) {
11485             for (signed i = len-1; i >= 0; i--) {
11486               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11487               StrVal = (StrVal << 8) | SingleChar;
11488             }
11489           } else {
11490             for (unsigned i = 0; i < len; i++) {
11491               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11492               StrVal = (StrVal << 8) | SingleChar;
11493             }
11494             // Append NULL at the end.
11495             SingleChar = 0;
11496             StrVal = (StrVal << 8) | SingleChar;
11497           }
11498           Value *NL = ConstantInt::get(*Context, StrVal);
11499           return IC.ReplaceInstUsesWith(LI, NL);
11500         }
11501       }
11502     }
11503   }
11504
11505   const PointerType *DestTy = cast<PointerType>(CI->getType());
11506   const Type *DestPTy = DestTy->getElementType();
11507   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11508
11509     // If the address spaces don't match, don't eliminate the cast.
11510     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11511       return 0;
11512
11513     const Type *SrcPTy = SrcTy->getElementType();
11514
11515     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11516          isa<VectorType>(DestPTy)) {
11517       // If the source is an array, the code below will not succeed.  Check to
11518       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11519       // constants.
11520       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11521         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11522           if (ASrcTy->getNumElements() != 0) {
11523             Value *Idxs[2];
11524             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11525             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11526             SrcTy = cast<PointerType>(CastOp->getType());
11527             SrcPTy = SrcTy->getElementType();
11528           }
11529
11530       if (IC.getTargetData() &&
11531           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11532             isa<VectorType>(SrcPTy)) &&
11533           // Do not allow turning this into a load of an integer, which is then
11534           // casted to a pointer, this pessimizes pointer analysis a lot.
11535           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11536           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11537                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11538
11539         // Okay, we are casting from one integer or pointer type to another of
11540         // the same size.  Instead of casting the pointer before the load, cast
11541         // the result of the loaded value.
11542         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11543                                                              CI->getName(),
11544                                                          LI.isVolatile()),LI);
11545         // Now cast the result of the load.
11546         return new BitCastInst(NewLoad, LI.getType());
11547       }
11548     }
11549   }
11550   return 0;
11551 }
11552
11553 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11554   Value *Op = LI.getOperand(0);
11555
11556   // Attempt to improve the alignment.
11557   if (TD) {
11558     unsigned KnownAlign =
11559       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11560     if (KnownAlign >
11561         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11562                                   LI.getAlignment()))
11563       LI.setAlignment(KnownAlign);
11564   }
11565
11566   // load (cast X) --> cast (load X) iff safe
11567   if (isa<CastInst>(Op))
11568     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11569       return Res;
11570
11571   // None of the following transforms are legal for volatile loads.
11572   if (LI.isVolatile()) return 0;
11573   
11574   // Do really simple store-to-load forwarding and load CSE, to catch cases
11575   // where there are several consequtive memory accesses to the same location,
11576   // separated by a few arithmetic operations.
11577   BasicBlock::iterator BBI = &LI;
11578   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11579     return ReplaceInstUsesWith(LI, AvailableVal);
11580
11581   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11582     const Value *GEPI0 = GEPI->getOperand(0);
11583     // TODO: Consider a target hook for valid address spaces for this xform.
11584     if (isa<ConstantPointerNull>(GEPI0) &&
11585         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11586       // Insert a new store to null instruction before the load to indicate
11587       // that this code is not reachable.  We do this instead of inserting
11588       // an unreachable instruction directly because we cannot modify the
11589       // CFG.
11590       new StoreInst(UndefValue::get(LI.getType()),
11591                     Context->getNullValue(Op->getType()), &LI);
11592       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11593     }
11594   } 
11595
11596   if (Constant *C = dyn_cast<Constant>(Op)) {
11597     // load null/undef -> undef
11598     // TODO: Consider a target hook for valid address spaces for this xform.
11599     if (isa<UndefValue>(C) || (C->isNullValue() && 
11600         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11601       // Insert a new store to null instruction before the load to indicate that
11602       // this code is not reachable.  We do this instead of inserting an
11603       // unreachable instruction directly because we cannot modify the CFG.
11604       new StoreInst(UndefValue::get(LI.getType()),
11605                     Context->getNullValue(Op->getType()), &LI);
11606       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11607     }
11608
11609     // Instcombine load (constant global) into the value loaded.
11610     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11611       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11612         return ReplaceInstUsesWith(LI, GV->getInitializer());
11613
11614     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11615     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11616       if (CE->getOpcode() == Instruction::GetElementPtr) {
11617         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11618           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11619             if (Constant *V = 
11620                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11621                                                       *Context))
11622               return ReplaceInstUsesWith(LI, V);
11623         if (CE->getOperand(0)->isNullValue()) {
11624           // Insert a new store to null instruction before the load to indicate
11625           // that this code is not reachable.  We do this instead of inserting
11626           // an unreachable instruction directly because we cannot modify the
11627           // CFG.
11628           new StoreInst(UndefValue::get(LI.getType()),
11629                         Context->getNullValue(Op->getType()), &LI);
11630           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11631         }
11632
11633       } else if (CE->isCast()) {
11634         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11635           return Res;
11636       }
11637     }
11638   }
11639     
11640   // If this load comes from anywhere in a constant global, and if the global
11641   // is all undef or zero, we know what it loads.
11642   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11643     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11644       if (GV->getInitializer()->isNullValue())
11645         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11646       else if (isa<UndefValue>(GV->getInitializer()))
11647         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11648     }
11649   }
11650
11651   if (Op->hasOneUse()) {
11652     // Change select and PHI nodes to select values instead of addresses: this
11653     // helps alias analysis out a lot, allows many others simplifications, and
11654     // exposes redundancy in the code.
11655     //
11656     // Note that we cannot do the transformation unless we know that the
11657     // introduced loads cannot trap!  Something like this is valid as long as
11658     // the condition is always false: load (select bool %C, int* null, int* %G),
11659     // but it would not be valid if we transformed it to load from null
11660     // unconditionally.
11661     //
11662     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11663       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11664       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11665           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11666         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11667                                      SI->getOperand(1)->getName()+".val"), LI);
11668         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11669                                      SI->getOperand(2)->getName()+".val"), LI);
11670         return SelectInst::Create(SI->getCondition(), V1, V2);
11671       }
11672
11673       // load (select (cond, null, P)) -> load P
11674       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11675         if (C->isNullValue()) {
11676           LI.setOperand(0, SI->getOperand(2));
11677           return &LI;
11678         }
11679
11680       // load (select (cond, P, null)) -> load P
11681       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11682         if (C->isNullValue()) {
11683           LI.setOperand(0, SI->getOperand(1));
11684           return &LI;
11685         }
11686     }
11687   }
11688   return 0;
11689 }
11690
11691 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11692 /// when possible.  This makes it generally easy to do alias analysis and/or
11693 /// SROA/mem2reg of the memory object.
11694 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11695   User *CI = cast<User>(SI.getOperand(1));
11696   Value *CastOp = CI->getOperand(0);
11697   LLVMContext *Context = IC.getContext();
11698
11699   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11700   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11701   if (SrcTy == 0) return 0;
11702   
11703   const Type *SrcPTy = SrcTy->getElementType();
11704
11705   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11706     return 0;
11707   
11708   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11709   /// to its first element.  This allows us to handle things like:
11710   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11711   /// on 32-bit hosts.
11712   SmallVector<Value*, 4> NewGEPIndices;
11713   
11714   // If the source is an array, the code below will not succeed.  Check to
11715   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11716   // constants.
11717   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11718     // Index through pointer.
11719     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11720     NewGEPIndices.push_back(Zero);
11721     
11722     while (1) {
11723       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11724         if (!STy->getNumElements()) /* Struct can be empty {} */
11725           break;
11726         NewGEPIndices.push_back(Zero);
11727         SrcPTy = STy->getElementType(0);
11728       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11729         NewGEPIndices.push_back(Zero);
11730         SrcPTy = ATy->getElementType();
11731       } else {
11732         break;
11733       }
11734     }
11735     
11736     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11737   }
11738
11739   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11740     return 0;
11741   
11742   // If the pointers point into different address spaces or if they point to
11743   // values with different sizes, we can't do the transformation.
11744   if (!IC.getTargetData() ||
11745       SrcTy->getAddressSpace() != 
11746         cast<PointerType>(CI->getType())->getAddressSpace() ||
11747       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11748       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11749     return 0;
11750
11751   // Okay, we are casting from one integer or pointer type to another of
11752   // the same size.  Instead of casting the pointer before 
11753   // the store, cast the value to be stored.
11754   Value *NewCast;
11755   Value *SIOp0 = SI.getOperand(0);
11756   Instruction::CastOps opcode = Instruction::BitCast;
11757   const Type* CastSrcTy = SIOp0->getType();
11758   const Type* CastDstTy = SrcPTy;
11759   if (isa<PointerType>(CastDstTy)) {
11760     if (CastSrcTy->isInteger())
11761       opcode = Instruction::IntToPtr;
11762   } else if (isa<IntegerType>(CastDstTy)) {
11763     if (isa<PointerType>(SIOp0->getType()))
11764       opcode = Instruction::PtrToInt;
11765   }
11766   
11767   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11768   // emit a GEP to index into its first field.
11769   if (!NewGEPIndices.empty()) {
11770     if (Constant *C = dyn_cast<Constant>(CastOp))
11771       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11772                                               NewGEPIndices.size());
11773     else
11774       CastOp = IC.InsertNewInstBefore(
11775               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11776                                         NewGEPIndices.end()), SI);
11777     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11778   }
11779   
11780   if (Constant *C = dyn_cast<Constant>(SIOp0))
11781     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11782   else
11783     NewCast = IC.InsertNewInstBefore(
11784       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11785       SI);
11786   return new StoreInst(NewCast, CastOp);
11787 }
11788
11789 /// equivalentAddressValues - Test if A and B will obviously have the same
11790 /// value. This includes recognizing that %t0 and %t1 will have the same
11791 /// value in code like this:
11792 ///   %t0 = getelementptr \@a, 0, 3
11793 ///   store i32 0, i32* %t0
11794 ///   %t1 = getelementptr \@a, 0, 3
11795 ///   %t2 = load i32* %t1
11796 ///
11797 static bool equivalentAddressValues(Value *A, Value *B) {
11798   // Test if the values are trivially equivalent.
11799   if (A == B) return true;
11800   
11801   // Test if the values come form identical arithmetic instructions.
11802   if (isa<BinaryOperator>(A) ||
11803       isa<CastInst>(A) ||
11804       isa<PHINode>(A) ||
11805       isa<GetElementPtrInst>(A))
11806     if (Instruction *BI = dyn_cast<Instruction>(B))
11807       if (cast<Instruction>(A)->isIdenticalTo(BI))
11808         return true;
11809   
11810   // Otherwise they may not be equivalent.
11811   return false;
11812 }
11813
11814 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11815 // return the llvm.dbg.declare.
11816 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11817   if (!V->hasNUses(2))
11818     return 0;
11819   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11820        UI != E; ++UI) {
11821     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11822       return DI;
11823     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11824       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11825         return DI;
11826       }
11827   }
11828   return 0;
11829 }
11830
11831 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11832   Value *Val = SI.getOperand(0);
11833   Value *Ptr = SI.getOperand(1);
11834
11835   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11836     EraseInstFromFunction(SI);
11837     ++NumCombined;
11838     return 0;
11839   }
11840   
11841   // If the RHS is an alloca with a single use, zapify the store, making the
11842   // alloca dead.
11843   // If the RHS is an alloca with a two uses, the other one being a 
11844   // llvm.dbg.declare, zapify the store and the declare, making the
11845   // alloca dead.  We must do this to prevent declare's from affecting
11846   // codegen.
11847   if (!SI.isVolatile()) {
11848     if (Ptr->hasOneUse()) {
11849       if (isa<AllocaInst>(Ptr)) {
11850         EraseInstFromFunction(SI);
11851         ++NumCombined;
11852         return 0;
11853       }
11854       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11855         if (isa<AllocaInst>(GEP->getOperand(0))) {
11856           if (GEP->getOperand(0)->hasOneUse()) {
11857             EraseInstFromFunction(SI);
11858             ++NumCombined;
11859             return 0;
11860           }
11861           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11862             EraseInstFromFunction(*DI);
11863             EraseInstFromFunction(SI);
11864             ++NumCombined;
11865             return 0;
11866           }
11867         }
11868       }
11869     }
11870     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11871       EraseInstFromFunction(*DI);
11872       EraseInstFromFunction(SI);
11873       ++NumCombined;
11874       return 0;
11875     }
11876   }
11877
11878   // Attempt to improve the alignment.
11879   if (TD) {
11880     unsigned KnownAlign =
11881       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11882     if (KnownAlign >
11883         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11884                                   SI.getAlignment()))
11885       SI.setAlignment(KnownAlign);
11886   }
11887
11888   // Do really simple DSE, to catch cases where there are several consecutive
11889   // stores to the same location, separated by a few arithmetic operations. This
11890   // situation often occurs with bitfield accesses.
11891   BasicBlock::iterator BBI = &SI;
11892   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11893        --ScanInsts) {
11894     --BBI;
11895     // Don't count debug info directives, lest they affect codegen,
11896     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11897     // It is necessary for correctness to skip those that feed into a
11898     // llvm.dbg.declare, as these are not present when debugging is off.
11899     if (isa<DbgInfoIntrinsic>(BBI) ||
11900         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11901       ScanInsts++;
11902       continue;
11903     }    
11904     
11905     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11906       // Prev store isn't volatile, and stores to the same location?
11907       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11908                                                           SI.getOperand(1))) {
11909         ++NumDeadStore;
11910         ++BBI;
11911         EraseInstFromFunction(*PrevSI);
11912         continue;
11913       }
11914       break;
11915     }
11916     
11917     // If this is a load, we have to stop.  However, if the loaded value is from
11918     // the pointer we're loading and is producing the pointer we're storing,
11919     // then *this* store is dead (X = load P; store X -> P).
11920     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11921       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11922           !SI.isVolatile()) {
11923         EraseInstFromFunction(SI);
11924         ++NumCombined;
11925         return 0;
11926       }
11927       // Otherwise, this is a load from some other location.  Stores before it
11928       // may not be dead.
11929       break;
11930     }
11931     
11932     // Don't skip over loads or things that can modify memory.
11933     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11934       break;
11935   }
11936   
11937   
11938   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11939
11940   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11941   if (isa<ConstantPointerNull>(Ptr) &&
11942       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11943     if (!isa<UndefValue>(Val)) {
11944       SI.setOperand(0, UndefValue::get(Val->getType()));
11945       if (Instruction *U = dyn_cast<Instruction>(Val))
11946         AddToWorkList(U);  // Dropped a use.
11947       ++NumCombined;
11948     }
11949     return 0;  // Do not modify these!
11950   }
11951
11952   // store undef, Ptr -> noop
11953   if (isa<UndefValue>(Val)) {
11954     EraseInstFromFunction(SI);
11955     ++NumCombined;
11956     return 0;
11957   }
11958
11959   // If the pointer destination is a cast, see if we can fold the cast into the
11960   // source instead.
11961   if (isa<CastInst>(Ptr))
11962     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11963       return Res;
11964   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11965     if (CE->isCast())
11966       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11967         return Res;
11968
11969   
11970   // If this store is the last instruction in the basic block (possibly
11971   // excepting debug info instructions and the pointer bitcasts that feed
11972   // into them), and if the block ends with an unconditional branch, try
11973   // to move it to the successor block.
11974   BBI = &SI; 
11975   do {
11976     ++BBI;
11977   } while (isa<DbgInfoIntrinsic>(BBI) ||
11978            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11979   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11980     if (BI->isUnconditional())
11981       if (SimplifyStoreAtEndOfBlock(SI))
11982         return 0;  // xform done!
11983   
11984   return 0;
11985 }
11986
11987 /// SimplifyStoreAtEndOfBlock - Turn things like:
11988 ///   if () { *P = v1; } else { *P = v2 }
11989 /// into a phi node with a store in the successor.
11990 ///
11991 /// Simplify things like:
11992 ///   *P = v1; if () { *P = v2; }
11993 /// into a phi node with a store in the successor.
11994 ///
11995 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11996   BasicBlock *StoreBB = SI.getParent();
11997   
11998   // Check to see if the successor block has exactly two incoming edges.  If
11999   // so, see if the other predecessor contains a store to the same location.
12000   // if so, insert a PHI node (if needed) and move the stores down.
12001   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12002   
12003   // Determine whether Dest has exactly two predecessors and, if so, compute
12004   // the other predecessor.
12005   pred_iterator PI = pred_begin(DestBB);
12006   BasicBlock *OtherBB = 0;
12007   if (*PI != StoreBB)
12008     OtherBB = *PI;
12009   ++PI;
12010   if (PI == pred_end(DestBB))
12011     return false;
12012   
12013   if (*PI != StoreBB) {
12014     if (OtherBB)
12015       return false;
12016     OtherBB = *PI;
12017   }
12018   if (++PI != pred_end(DestBB))
12019     return false;
12020
12021   // Bail out if all the relevant blocks aren't distinct (this can happen,
12022   // for example, if SI is in an infinite loop)
12023   if (StoreBB == DestBB || OtherBB == DestBB)
12024     return false;
12025
12026   // Verify that the other block ends in a branch and is not otherwise empty.
12027   BasicBlock::iterator BBI = OtherBB->getTerminator();
12028   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12029   if (!OtherBr || BBI == OtherBB->begin())
12030     return false;
12031   
12032   // If the other block ends in an unconditional branch, check for the 'if then
12033   // else' case.  there is an instruction before the branch.
12034   StoreInst *OtherStore = 0;
12035   if (OtherBr->isUnconditional()) {
12036     --BBI;
12037     // Skip over debugging info.
12038     while (isa<DbgInfoIntrinsic>(BBI) ||
12039            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12040       if (BBI==OtherBB->begin())
12041         return false;
12042       --BBI;
12043     }
12044     // If this isn't a store, or isn't a store to the same location, bail out.
12045     OtherStore = dyn_cast<StoreInst>(BBI);
12046     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12047       return false;
12048   } else {
12049     // Otherwise, the other block ended with a conditional branch. If one of the
12050     // destinations is StoreBB, then we have the if/then case.
12051     if (OtherBr->getSuccessor(0) != StoreBB && 
12052         OtherBr->getSuccessor(1) != StoreBB)
12053       return false;
12054     
12055     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12056     // if/then triangle.  See if there is a store to the same ptr as SI that
12057     // lives in OtherBB.
12058     for (;; --BBI) {
12059       // Check to see if we find the matching store.
12060       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12061         if (OtherStore->getOperand(1) != SI.getOperand(1))
12062           return false;
12063         break;
12064       }
12065       // If we find something that may be using or overwriting the stored
12066       // value, or if we run out of instructions, we can't do the xform.
12067       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12068           BBI == OtherBB->begin())
12069         return false;
12070     }
12071     
12072     // In order to eliminate the store in OtherBr, we have to
12073     // make sure nothing reads or overwrites the stored value in
12074     // StoreBB.
12075     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12076       // FIXME: This should really be AA driven.
12077       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12078         return false;
12079     }
12080   }
12081   
12082   // Insert a PHI node now if we need it.
12083   Value *MergedVal = OtherStore->getOperand(0);
12084   if (MergedVal != SI.getOperand(0)) {
12085     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12086     PN->reserveOperandSpace(2);
12087     PN->addIncoming(SI.getOperand(0), SI.getParent());
12088     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12089     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12090   }
12091   
12092   // Advance to a place where it is safe to insert the new store and
12093   // insert it.
12094   BBI = DestBB->getFirstNonPHI();
12095   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12096                                     OtherStore->isVolatile()), *BBI);
12097   
12098   // Nuke the old stores.
12099   EraseInstFromFunction(SI);
12100   EraseInstFromFunction(*OtherStore);
12101   ++NumCombined;
12102   return true;
12103 }
12104
12105
12106 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12107   // Change br (not X), label True, label False to: br X, label False, True
12108   Value *X = 0;
12109   BasicBlock *TrueDest;
12110   BasicBlock *FalseDest;
12111   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12112       !isa<Constant>(X)) {
12113     // Swap Destinations and condition...
12114     BI.setCondition(X);
12115     BI.setSuccessor(0, FalseDest);
12116     BI.setSuccessor(1, TrueDest);
12117     return &BI;
12118   }
12119
12120   // Cannonicalize fcmp_one -> fcmp_oeq
12121   FCmpInst::Predicate FPred; Value *Y;
12122   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12123                              TrueDest, FalseDest), *Context))
12124     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12125          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12126       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12127       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12128       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12129       NewSCC->takeName(I);
12130       // Swap Destinations and condition...
12131       BI.setCondition(NewSCC);
12132       BI.setSuccessor(0, FalseDest);
12133       BI.setSuccessor(1, TrueDest);
12134       RemoveFromWorkList(I);
12135       I->eraseFromParent();
12136       AddToWorkList(NewSCC);
12137       return &BI;
12138     }
12139
12140   // Cannonicalize icmp_ne -> icmp_eq
12141   ICmpInst::Predicate IPred;
12142   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12143                       TrueDest, FalseDest), *Context))
12144     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12145          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12146          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12147       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12148       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12149       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12150       NewSCC->takeName(I);
12151       // Swap Destinations and condition...
12152       BI.setCondition(NewSCC);
12153       BI.setSuccessor(0, FalseDest);
12154       BI.setSuccessor(1, TrueDest);
12155       RemoveFromWorkList(I);
12156       I->eraseFromParent();;
12157       AddToWorkList(NewSCC);
12158       return &BI;
12159     }
12160
12161   return 0;
12162 }
12163
12164 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12165   Value *Cond = SI.getCondition();
12166   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12167     if (I->getOpcode() == Instruction::Add)
12168       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12169         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12170         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12171           SI.setOperand(i,
12172                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12173                                                 AddRHS));
12174         SI.setOperand(0, I->getOperand(0));
12175         AddToWorkList(I);
12176         return &SI;
12177       }
12178   }
12179   return 0;
12180 }
12181
12182 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12183   Value *Agg = EV.getAggregateOperand();
12184
12185   if (!EV.hasIndices())
12186     return ReplaceInstUsesWith(EV, Agg);
12187
12188   if (Constant *C = dyn_cast<Constant>(Agg)) {
12189     if (isa<UndefValue>(C))
12190       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12191       
12192     if (isa<ConstantAggregateZero>(C))
12193       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12194
12195     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12196       // Extract the element indexed by the first index out of the constant
12197       Value *V = C->getOperand(*EV.idx_begin());
12198       if (EV.getNumIndices() > 1)
12199         // Extract the remaining indices out of the constant indexed by the
12200         // first index
12201         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12202       else
12203         return ReplaceInstUsesWith(EV, V);
12204     }
12205     return 0; // Can't handle other constants
12206   } 
12207   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12208     // We're extracting from an insertvalue instruction, compare the indices
12209     const unsigned *exti, *exte, *insi, *inse;
12210     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12211          exte = EV.idx_end(), inse = IV->idx_end();
12212          exti != exte && insi != inse;
12213          ++exti, ++insi) {
12214       if (*insi != *exti)
12215         // The insert and extract both reference distinctly different elements.
12216         // This means the extract is not influenced by the insert, and we can
12217         // replace the aggregate operand of the extract with the aggregate
12218         // operand of the insert. i.e., replace
12219         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12220         // %E = extractvalue { i32, { i32 } } %I, 0
12221         // with
12222         // %E = extractvalue { i32, { i32 } } %A, 0
12223         return ExtractValueInst::Create(IV->getAggregateOperand(),
12224                                         EV.idx_begin(), EV.idx_end());
12225     }
12226     if (exti == exte && insi == inse)
12227       // Both iterators are at the end: Index lists are identical. Replace
12228       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12229       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12230       // with "i32 42"
12231       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12232     if (exti == exte) {
12233       // The extract list is a prefix of the insert list. i.e. replace
12234       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12235       // %E = extractvalue { i32, { i32 } } %I, 1
12236       // with
12237       // %X = extractvalue { i32, { i32 } } %A, 1
12238       // %E = insertvalue { i32 } %X, i32 42, 0
12239       // by switching the order of the insert and extract (though the
12240       // insertvalue should be left in, since it may have other uses).
12241       Value *NewEV = InsertNewInstBefore(
12242         ExtractValueInst::Create(IV->getAggregateOperand(),
12243                                  EV.idx_begin(), EV.idx_end()),
12244         EV);
12245       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12246                                      insi, inse);
12247     }
12248     if (insi == inse)
12249       // The insert list is a prefix of the extract list
12250       // We can simply remove the common indices from the extract and make it
12251       // operate on the inserted value instead of the insertvalue result.
12252       // i.e., replace
12253       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12254       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12255       // with
12256       // %E extractvalue { i32 } { i32 42 }, 0
12257       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12258                                       exti, exte);
12259   }
12260   // Can't simplify extracts from other values. Note that nested extracts are
12261   // already simplified implicitely by the above (extract ( extract (insert) )
12262   // will be translated into extract ( insert ( extract ) ) first and then just
12263   // the value inserted, if appropriate).
12264   return 0;
12265 }
12266
12267 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12268 /// is to leave as a vector operation.
12269 static bool CheapToScalarize(Value *V, bool isConstant) {
12270   if (isa<ConstantAggregateZero>(V)) 
12271     return true;
12272   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12273     if (isConstant) return true;
12274     // If all elts are the same, we can extract.
12275     Constant *Op0 = C->getOperand(0);
12276     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12277       if (C->getOperand(i) != Op0)
12278         return false;
12279     return true;
12280   }
12281   Instruction *I = dyn_cast<Instruction>(V);
12282   if (!I) return false;
12283   
12284   // Insert element gets simplified to the inserted element or is deleted if
12285   // this is constant idx extract element and its a constant idx insertelt.
12286   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12287       isa<ConstantInt>(I->getOperand(2)))
12288     return true;
12289   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12290     return true;
12291   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12292     if (BO->hasOneUse() &&
12293         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12294          CheapToScalarize(BO->getOperand(1), isConstant)))
12295       return true;
12296   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12297     if (CI->hasOneUse() &&
12298         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12299          CheapToScalarize(CI->getOperand(1), isConstant)))
12300       return true;
12301   
12302   return false;
12303 }
12304
12305 /// Read and decode a shufflevector mask.
12306 ///
12307 /// It turns undef elements into values that are larger than the number of
12308 /// elements in the input.
12309 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12310   unsigned NElts = SVI->getType()->getNumElements();
12311   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12312     return std::vector<unsigned>(NElts, 0);
12313   if (isa<UndefValue>(SVI->getOperand(2)))
12314     return std::vector<unsigned>(NElts, 2*NElts);
12315
12316   std::vector<unsigned> Result;
12317   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12318   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12319     if (isa<UndefValue>(*i))
12320       Result.push_back(NElts*2);  // undef -> 8
12321     else
12322       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12323   return Result;
12324 }
12325
12326 /// FindScalarElement - Given a vector and an element number, see if the scalar
12327 /// value is already around as a register, for example if it were inserted then
12328 /// extracted from the vector.
12329 static Value *FindScalarElement(Value *V, unsigned EltNo,
12330                                 LLVMContext *Context) {
12331   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12332   const VectorType *PTy = cast<VectorType>(V->getType());
12333   unsigned Width = PTy->getNumElements();
12334   if (EltNo >= Width)  // Out of range access.
12335     return UndefValue::get(PTy->getElementType());
12336   
12337   if (isa<UndefValue>(V))
12338     return UndefValue::get(PTy->getElementType());
12339   else if (isa<ConstantAggregateZero>(V))
12340     return Context->getNullValue(PTy->getElementType());
12341   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12342     return CP->getOperand(EltNo);
12343   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12344     // If this is an insert to a variable element, we don't know what it is.
12345     if (!isa<ConstantInt>(III->getOperand(2))) 
12346       return 0;
12347     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12348     
12349     // If this is an insert to the element we are looking for, return the
12350     // inserted value.
12351     if (EltNo == IIElt) 
12352       return III->getOperand(1);
12353     
12354     // Otherwise, the insertelement doesn't modify the value, recurse on its
12355     // vector input.
12356     return FindScalarElement(III->getOperand(0), EltNo, Context);
12357   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12358     unsigned LHSWidth =
12359       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12360     unsigned InEl = getShuffleMask(SVI)[EltNo];
12361     if (InEl < LHSWidth)
12362       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12363     else if (InEl < LHSWidth*2)
12364       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12365     else
12366       return UndefValue::get(PTy->getElementType());
12367   }
12368   
12369   // Otherwise, we don't know.
12370   return 0;
12371 }
12372
12373 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12374   // If vector val is undef, replace extract with scalar undef.
12375   if (isa<UndefValue>(EI.getOperand(0)))
12376     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12377
12378   // If vector val is constant 0, replace extract with scalar 0.
12379   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12380     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12381   
12382   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12383     // If vector val is constant with all elements the same, replace EI with
12384     // that element. When the elements are not identical, we cannot replace yet
12385     // (we do that below, but only when the index is constant).
12386     Constant *op0 = C->getOperand(0);
12387     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12388       if (C->getOperand(i) != op0) {
12389         op0 = 0; 
12390         break;
12391       }
12392     if (op0)
12393       return ReplaceInstUsesWith(EI, op0);
12394   }
12395   
12396   // If extracting a specified index from the vector, see if we can recursively
12397   // find a previously computed scalar that was inserted into the vector.
12398   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12399     unsigned IndexVal = IdxC->getZExtValue();
12400     unsigned VectorWidth = 
12401       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12402       
12403     // If this is extracting an invalid index, turn this into undef, to avoid
12404     // crashing the code below.
12405     if (IndexVal >= VectorWidth)
12406       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12407     
12408     // This instruction only demands the single element from the input vector.
12409     // If the input vector has a single use, simplify it based on this use
12410     // property.
12411     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12412       APInt UndefElts(VectorWidth, 0);
12413       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12414       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12415                                                 DemandedMask, UndefElts)) {
12416         EI.setOperand(0, V);
12417         return &EI;
12418       }
12419     }
12420     
12421     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12422       return ReplaceInstUsesWith(EI, Elt);
12423     
12424     // If the this extractelement is directly using a bitcast from a vector of
12425     // the same number of elements, see if we can find the source element from
12426     // it.  In this case, we will end up needing to bitcast the scalars.
12427     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12428       if (const VectorType *VT = 
12429               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12430         if (VT->getNumElements() == VectorWidth)
12431           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12432                                              IndexVal, Context))
12433             return new BitCastInst(Elt, EI.getType());
12434     }
12435   }
12436   
12437   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12438     if (I->hasOneUse()) {
12439       // Push extractelement into predecessor operation if legal and
12440       // profitable to do so
12441       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12442         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12443         if (CheapToScalarize(BO, isConstantElt)) {
12444           ExtractElementInst *newEI0 = 
12445             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12446                                    EI.getName()+".lhs");
12447           ExtractElementInst *newEI1 =
12448             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12449                                    EI.getName()+".rhs");
12450           InsertNewInstBefore(newEI0, EI);
12451           InsertNewInstBefore(newEI1, EI);
12452           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12453         }
12454       } else if (isa<LoadInst>(I)) {
12455         unsigned AS = 
12456           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12457         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12458                                   PointerType::get(EI.getType(), AS),EI);
12459         GetElementPtrInst *GEP =
12460           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12461         cast<GEPOperator>(GEP)->setIsInBounds(true);
12462         InsertNewInstBefore(GEP, EI);
12463         return new LoadInst(GEP);
12464       }
12465     }
12466     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12467       // Extracting the inserted element?
12468       if (IE->getOperand(2) == EI.getOperand(1))
12469         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12470       // If the inserted and extracted elements are constants, they must not
12471       // be the same value, extract from the pre-inserted value instead.
12472       if (isa<Constant>(IE->getOperand(2)) &&
12473           isa<Constant>(EI.getOperand(1))) {
12474         AddUsesToWorkList(EI);
12475         EI.setOperand(0, IE->getOperand(0));
12476         return &EI;
12477       }
12478     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12479       // If this is extracting an element from a shufflevector, figure out where
12480       // it came from and extract from the appropriate input element instead.
12481       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12482         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12483         Value *Src;
12484         unsigned LHSWidth =
12485           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12486
12487         if (SrcIdx < LHSWidth)
12488           Src = SVI->getOperand(0);
12489         else if (SrcIdx < LHSWidth*2) {
12490           SrcIdx -= LHSWidth;
12491           Src = SVI->getOperand(1);
12492         } else {
12493           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12494         }
12495         return ExtractElementInst::Create(Src,
12496                          ConstantInt::get(Type::Int32Ty, SrcIdx, false));
12497       }
12498     }
12499     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12500   }
12501   return 0;
12502 }
12503
12504 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12505 /// elements from either LHS or RHS, return the shuffle mask and true. 
12506 /// Otherwise, return false.
12507 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12508                                          std::vector<Constant*> &Mask,
12509                                          LLVMContext *Context) {
12510   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12511          "Invalid CollectSingleShuffleElements");
12512   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12513
12514   if (isa<UndefValue>(V)) {
12515     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12516     return true;
12517   } else if (V == LHS) {
12518     for (unsigned i = 0; i != NumElts; ++i)
12519       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12520     return true;
12521   } else if (V == RHS) {
12522     for (unsigned i = 0; i != NumElts; ++i)
12523       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12524     return true;
12525   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12526     // If this is an insert of an extract from some other vector, include it.
12527     Value *VecOp    = IEI->getOperand(0);
12528     Value *ScalarOp = IEI->getOperand(1);
12529     Value *IdxOp    = IEI->getOperand(2);
12530     
12531     if (!isa<ConstantInt>(IdxOp))
12532       return false;
12533     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12534     
12535     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12536       // Okay, we can handle this if the vector we are insertinting into is
12537       // transitively ok.
12538       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12539         // If so, update the mask to reflect the inserted undef.
12540         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12541         return true;
12542       }      
12543     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12544       if (isa<ConstantInt>(EI->getOperand(1)) &&
12545           EI->getOperand(0)->getType() == V->getType()) {
12546         unsigned ExtractedIdx =
12547           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12548         
12549         // This must be extracting from either LHS or RHS.
12550         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12551           // Okay, we can handle this if the vector we are insertinting into is
12552           // transitively ok.
12553           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12554             // If so, update the mask to reflect the inserted value.
12555             if (EI->getOperand(0) == LHS) {
12556               Mask[InsertedIdx % NumElts] = 
12557                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12558             } else {
12559               assert(EI->getOperand(0) == RHS);
12560               Mask[InsertedIdx % NumElts] = 
12561                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12562               
12563             }
12564             return true;
12565           }
12566         }
12567       }
12568     }
12569   }
12570   // TODO: Handle shufflevector here!
12571   
12572   return false;
12573 }
12574
12575 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12576 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12577 /// that computes V and the LHS value of the shuffle.
12578 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12579                                      Value *&RHS, LLVMContext *Context) {
12580   assert(isa<VectorType>(V->getType()) && 
12581          (RHS == 0 || V->getType() == RHS->getType()) &&
12582          "Invalid shuffle!");
12583   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12584
12585   if (isa<UndefValue>(V)) {
12586     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12587     return V;
12588   } else if (isa<ConstantAggregateZero>(V)) {
12589     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12590     return V;
12591   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12592     // If this is an insert of an extract from some other vector, include it.
12593     Value *VecOp    = IEI->getOperand(0);
12594     Value *ScalarOp = IEI->getOperand(1);
12595     Value *IdxOp    = IEI->getOperand(2);
12596     
12597     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12598       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12599           EI->getOperand(0)->getType() == V->getType()) {
12600         unsigned ExtractedIdx =
12601           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12602         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12603         
12604         // Either the extracted from or inserted into vector must be RHSVec,
12605         // otherwise we'd end up with a shuffle of three inputs.
12606         if (EI->getOperand(0) == RHS || RHS == 0) {
12607           RHS = EI->getOperand(0);
12608           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12609           Mask[InsertedIdx % NumElts] = 
12610             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12611           return V;
12612         }
12613         
12614         if (VecOp == RHS) {
12615           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12616                                             RHS, Context);
12617           // Everything but the extracted element is replaced with the RHS.
12618           for (unsigned i = 0; i != NumElts; ++i) {
12619             if (i != InsertedIdx)
12620               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12621           }
12622           return V;
12623         }
12624         
12625         // If this insertelement is a chain that comes from exactly these two
12626         // vectors, return the vector and the effective shuffle.
12627         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12628                                          Context))
12629           return EI->getOperand(0);
12630         
12631       }
12632     }
12633   }
12634   // TODO: Handle shufflevector here!
12635   
12636   // Otherwise, can't do anything fancy.  Return an identity vector.
12637   for (unsigned i = 0; i != NumElts; ++i)
12638     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12639   return V;
12640 }
12641
12642 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12643   Value *VecOp    = IE.getOperand(0);
12644   Value *ScalarOp = IE.getOperand(1);
12645   Value *IdxOp    = IE.getOperand(2);
12646   
12647   // Inserting an undef or into an undefined place, remove this.
12648   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12649     ReplaceInstUsesWith(IE, VecOp);
12650   
12651   // If the inserted element was extracted from some other vector, and if the 
12652   // indexes are constant, try to turn this into a shufflevector operation.
12653   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12654     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12655         EI->getOperand(0)->getType() == IE.getType()) {
12656       unsigned NumVectorElts = IE.getType()->getNumElements();
12657       unsigned ExtractedIdx =
12658         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12659       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12660       
12661       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12662         return ReplaceInstUsesWith(IE, VecOp);
12663       
12664       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12665         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12666       
12667       // If we are extracting a value from a vector, then inserting it right
12668       // back into the same place, just use the input vector.
12669       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12670         return ReplaceInstUsesWith(IE, VecOp);      
12671       
12672       // We could theoretically do this for ANY input.  However, doing so could
12673       // turn chains of insertelement instructions into a chain of shufflevector
12674       // instructions, and right now we do not merge shufflevectors.  As such,
12675       // only do this in a situation where it is clear that there is benefit.
12676       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12677         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12678         // the values of VecOp, except then one read from EIOp0.
12679         // Build a new shuffle mask.
12680         std::vector<Constant*> Mask;
12681         if (isa<UndefValue>(VecOp))
12682           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12683         else {
12684           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12685           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12686                                                        NumVectorElts));
12687         } 
12688         Mask[InsertedIdx] = 
12689                            ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12690         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12691                                      ConstantVector::get(Mask));
12692       }
12693       
12694       // If this insertelement isn't used by some other insertelement, turn it
12695       // (and any insertelements it points to), into one big shuffle.
12696       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12697         std::vector<Constant*> Mask;
12698         Value *RHS = 0;
12699         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12700         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12701         // We now have a shuffle of LHS, RHS, Mask.
12702         return new ShuffleVectorInst(LHS, RHS,
12703                                      ConstantVector::get(Mask));
12704       }
12705     }
12706   }
12707
12708   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12709   APInt UndefElts(VWidth, 0);
12710   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12711   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12712     return &IE;
12713
12714   return 0;
12715 }
12716
12717
12718 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12719   Value *LHS = SVI.getOperand(0);
12720   Value *RHS = SVI.getOperand(1);
12721   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12722
12723   bool MadeChange = false;
12724
12725   // Undefined shuffle mask -> undefined value.
12726   if (isa<UndefValue>(SVI.getOperand(2)))
12727     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12728
12729   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12730
12731   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12732     return 0;
12733
12734   APInt UndefElts(VWidth, 0);
12735   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12736   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12737     LHS = SVI.getOperand(0);
12738     RHS = SVI.getOperand(1);
12739     MadeChange = true;
12740   }
12741   
12742   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12743   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12744   if (LHS == RHS || isa<UndefValue>(LHS)) {
12745     if (isa<UndefValue>(LHS) && LHS == RHS) {
12746       // shuffle(undef,undef,mask) -> undef.
12747       return ReplaceInstUsesWith(SVI, LHS);
12748     }
12749     
12750     // Remap any references to RHS to use LHS.
12751     std::vector<Constant*> Elts;
12752     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12753       if (Mask[i] >= 2*e)
12754         Elts.push_back(UndefValue::get(Type::Int32Ty));
12755       else {
12756         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12757             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12758           Mask[i] = 2*e;     // Turn into undef.
12759           Elts.push_back(UndefValue::get(Type::Int32Ty));
12760         } else {
12761           Mask[i] = Mask[i] % e;  // Force to LHS.
12762           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12763         }
12764       }
12765     }
12766     SVI.setOperand(0, SVI.getOperand(1));
12767     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12768     SVI.setOperand(2, ConstantVector::get(Elts));
12769     LHS = SVI.getOperand(0);
12770     RHS = SVI.getOperand(1);
12771     MadeChange = true;
12772   }
12773   
12774   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12775   bool isLHSID = true, isRHSID = true;
12776     
12777   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12778     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12779     // Is this an identity shuffle of the LHS value?
12780     isLHSID &= (Mask[i] == i);
12781       
12782     // Is this an identity shuffle of the RHS value?
12783     isRHSID &= (Mask[i]-e == i);
12784   }
12785
12786   // Eliminate identity shuffles.
12787   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12788   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12789   
12790   // If the LHS is a shufflevector itself, see if we can combine it with this
12791   // one without producing an unusual shuffle.  Here we are really conservative:
12792   // we are absolutely afraid of producing a shuffle mask not in the input
12793   // program, because the code gen may not be smart enough to turn a merged
12794   // shuffle into two specific shuffles: it may produce worse code.  As such,
12795   // we only merge two shuffles if the result is one of the two input shuffle
12796   // masks.  In this case, merging the shuffles just removes one instruction,
12797   // which we know is safe.  This is good for things like turning:
12798   // (splat(splat)) -> splat.
12799   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12800     if (isa<UndefValue>(RHS)) {
12801       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12802
12803       std::vector<unsigned> NewMask;
12804       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12805         if (Mask[i] >= 2*e)
12806           NewMask.push_back(2*e);
12807         else
12808           NewMask.push_back(LHSMask[Mask[i]]);
12809       
12810       // If the result mask is equal to the src shuffle or this shuffle mask, do
12811       // the replacement.
12812       if (NewMask == LHSMask || NewMask == Mask) {
12813         unsigned LHSInNElts =
12814           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12815         std::vector<Constant*> Elts;
12816         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12817           if (NewMask[i] >= LHSInNElts*2) {
12818             Elts.push_back(UndefValue::get(Type::Int32Ty));
12819           } else {
12820             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12821           }
12822         }
12823         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12824                                      LHSSVI->getOperand(1),
12825                                      ConstantVector::get(Elts));
12826       }
12827     }
12828   }
12829
12830   return MadeChange ? &SVI : 0;
12831 }
12832
12833
12834
12835
12836 /// TryToSinkInstruction - Try to move the specified instruction from its
12837 /// current block into the beginning of DestBlock, which can only happen if it's
12838 /// safe to move the instruction past all of the instructions between it and the
12839 /// end of its block.
12840 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12841   assert(I->hasOneUse() && "Invariants didn't hold!");
12842
12843   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12844   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12845     return false;
12846
12847   // Do not sink alloca instructions out of the entry block.
12848   if (isa<AllocaInst>(I) && I->getParent() ==
12849         &DestBlock->getParent()->getEntryBlock())
12850     return false;
12851
12852   // We can only sink load instructions if there is nothing between the load and
12853   // the end of block that could change the value.
12854   if (I->mayReadFromMemory()) {
12855     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12856          Scan != E; ++Scan)
12857       if (Scan->mayWriteToMemory())
12858         return false;
12859   }
12860
12861   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12862
12863   CopyPrecedingStopPoint(I, InsertPos);
12864   I->moveBefore(InsertPos);
12865   ++NumSunkInst;
12866   return true;
12867 }
12868
12869
12870 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12871 /// all reachable code to the worklist.
12872 ///
12873 /// This has a couple of tricks to make the code faster and more powerful.  In
12874 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12875 /// them to the worklist (this significantly speeds up instcombine on code where
12876 /// many instructions are dead or constant).  Additionally, if we find a branch
12877 /// whose condition is a known constant, we only visit the reachable successors.
12878 ///
12879 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12880                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12881                                        InstCombiner &IC,
12882                                        const TargetData *TD) {
12883   SmallVector<BasicBlock*, 256> Worklist;
12884   Worklist.push_back(BB);
12885
12886   while (!Worklist.empty()) {
12887     BB = Worklist.back();
12888     Worklist.pop_back();
12889     
12890     // We have now visited this block!  If we've already been here, ignore it.
12891     if (!Visited.insert(BB)) continue;
12892
12893     DbgInfoIntrinsic *DBI_Prev = NULL;
12894     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12895       Instruction *Inst = BBI++;
12896       
12897       // DCE instruction if trivially dead.
12898       if (isInstructionTriviallyDead(Inst)) {
12899         ++NumDeadInst;
12900         DOUT << "IC: DCE: " << *Inst;
12901         Inst->eraseFromParent();
12902         continue;
12903       }
12904       
12905       // ConstantProp instruction if trivially constant.
12906       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12907         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12908         Inst->replaceAllUsesWith(C);
12909         ++NumConstProp;
12910         Inst->eraseFromParent();
12911         continue;
12912       }
12913      
12914       // If there are two consecutive llvm.dbg.stoppoint calls then
12915       // it is likely that the optimizer deleted code in between these
12916       // two intrinsics. 
12917       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12918       if (DBI_Next) {
12919         if (DBI_Prev
12920             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12921             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12922           IC.RemoveFromWorkList(DBI_Prev);
12923           DBI_Prev->eraseFromParent();
12924         }
12925         DBI_Prev = DBI_Next;
12926       } else {
12927         DBI_Prev = 0;
12928       }
12929
12930       IC.AddToWorkList(Inst);
12931     }
12932
12933     // Recursively visit successors.  If this is a branch or switch on a
12934     // constant, only visit the reachable successor.
12935     TerminatorInst *TI = BB->getTerminator();
12936     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12937       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12938         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12939         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12940         Worklist.push_back(ReachableBB);
12941         continue;
12942       }
12943     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12944       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12945         // See if this is an explicit destination.
12946         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12947           if (SI->getCaseValue(i) == Cond) {
12948             BasicBlock *ReachableBB = SI->getSuccessor(i);
12949             Worklist.push_back(ReachableBB);
12950             continue;
12951           }
12952         
12953         // Otherwise it is the default destination.
12954         Worklist.push_back(SI->getSuccessor(0));
12955         continue;
12956       }
12957     }
12958     
12959     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12960       Worklist.push_back(TI->getSuccessor(i));
12961   }
12962 }
12963
12964 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12965   bool Changed = false;
12966   TD = getAnalysisIfAvailable<TargetData>();
12967   
12968   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12969         << F.getNameStr() << "\n");
12970
12971   {
12972     // Do a depth-first traversal of the function, populate the worklist with
12973     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12974     // track of which blocks we visit.
12975     SmallPtrSet<BasicBlock*, 64> Visited;
12976     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12977
12978     // Do a quick scan over the function.  If we find any blocks that are
12979     // unreachable, remove any instructions inside of them.  This prevents
12980     // the instcombine code from having to deal with some bad special cases.
12981     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12982       if (!Visited.count(BB)) {
12983         Instruction *Term = BB->getTerminator();
12984         while (Term != BB->begin()) {   // Remove instrs bottom-up
12985           BasicBlock::iterator I = Term; --I;
12986
12987           DOUT << "IC: DCE: " << *I;
12988           // A debug intrinsic shouldn't force another iteration if we weren't
12989           // going to do one without it.
12990           if (!isa<DbgInfoIntrinsic>(I)) {
12991             ++NumDeadInst;
12992             Changed = true;
12993           }
12994           if (!I->use_empty())
12995             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12996           I->eraseFromParent();
12997         }
12998       }
12999   }
13000
13001   while (!Worklist.empty()) {
13002     Instruction *I = RemoveOneFromWorkList();
13003     if (I == 0) continue;  // skip null values.
13004
13005     // Check to see if we can DCE the instruction.
13006     if (isInstructionTriviallyDead(I)) {
13007       // Add operands to the worklist.
13008       if (I->getNumOperands() < 4)
13009         AddUsesToWorkList(*I);
13010       ++NumDeadInst;
13011
13012       DOUT << "IC: DCE: " << *I;
13013
13014       I->eraseFromParent();
13015       RemoveFromWorkList(I);
13016       Changed = true;
13017       continue;
13018     }
13019
13020     // Instruction isn't dead, see if we can constant propagate it.
13021     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13022       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13023
13024       // Add operands to the worklist.
13025       AddUsesToWorkList(*I);
13026       ReplaceInstUsesWith(*I, C);
13027
13028       ++NumConstProp;
13029       I->eraseFromParent();
13030       RemoveFromWorkList(I);
13031       Changed = true;
13032       continue;
13033     }
13034
13035     if (TD) {
13036       // See if we can constant fold its operands.
13037       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13038         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13039           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13040                                   F.getContext(), TD))
13041             if (NewC != CE) {
13042               i->set(NewC);
13043               Changed = true;
13044             }
13045     }
13046
13047     // See if we can trivially sink this instruction to a successor basic block.
13048     if (I->hasOneUse()) {
13049       BasicBlock *BB = I->getParent();
13050       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13051       if (UserParent != BB) {
13052         bool UserIsSuccessor = false;
13053         // See if the user is one of our successors.
13054         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13055           if (*SI == UserParent) {
13056             UserIsSuccessor = true;
13057             break;
13058           }
13059
13060         // If the user is one of our immediate successors, and if that successor
13061         // only has us as a predecessors (we'd have to split the critical edge
13062         // otherwise), we can keep going.
13063         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13064             next(pred_begin(UserParent)) == pred_end(UserParent))
13065           // Okay, the CFG is simple enough, try to sink this instruction.
13066           Changed |= TryToSinkInstruction(I, UserParent);
13067       }
13068     }
13069
13070     // Now that we have an instruction, try combining it to simplify it...
13071 #ifndef NDEBUG
13072     std::string OrigI;
13073 #endif
13074     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13075     if (Instruction *Result = visit(*I)) {
13076       ++NumCombined;
13077       // Should we replace the old instruction with a new one?
13078       if (Result != I) {
13079         DOUT << "IC: Old = " << *I
13080              << "    New = " << *Result;
13081
13082         // Everything uses the new instruction now.
13083         I->replaceAllUsesWith(Result);
13084
13085         // Push the new instruction and any users onto the worklist.
13086         AddToWorkList(Result);
13087         AddUsersToWorkList(*Result);
13088
13089         // Move the name to the new instruction first.
13090         Result->takeName(I);
13091
13092         // Insert the new instruction into the basic block...
13093         BasicBlock *InstParent = I->getParent();
13094         BasicBlock::iterator InsertPos = I;
13095
13096         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13097           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13098             ++InsertPos;
13099
13100         InstParent->getInstList().insert(InsertPos, Result);
13101
13102         // Make sure that we reprocess all operands now that we reduced their
13103         // use counts.
13104         AddUsesToWorkList(*I);
13105
13106         // Instructions can end up on the worklist more than once.  Make sure
13107         // we do not process an instruction that has been deleted.
13108         RemoveFromWorkList(I);
13109
13110         // Erase the old instruction.
13111         InstParent->getInstList().erase(I);
13112       } else {
13113 #ifndef NDEBUG
13114         DOUT << "IC: Mod = " << OrigI
13115              << "    New = " << *I;
13116 #endif
13117
13118         // If the instruction was modified, it's possible that it is now dead.
13119         // if so, remove it.
13120         if (isInstructionTriviallyDead(I)) {
13121           // Make sure we process all operands now that we are reducing their
13122           // use counts.
13123           AddUsesToWorkList(*I);
13124
13125           // Instructions may end up in the worklist more than once.  Erase all
13126           // occurrences of this instruction.
13127           RemoveFromWorkList(I);
13128           I->eraseFromParent();
13129         } else {
13130           AddToWorkList(I);
13131           AddUsersToWorkList(*I);
13132         }
13133       }
13134       Changed = true;
13135     }
13136   }
13137
13138   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13139     
13140   // Do an explicit clear, this shrinks the map if needed.
13141   WorklistMap.clear();
13142   return Changed;
13143 }
13144
13145
13146 bool InstCombiner::runOnFunction(Function &F) {
13147   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13148   Context = &F.getContext();
13149   
13150   bool EverMadeChange = false;
13151
13152   // Iterate while there is work to do.
13153   unsigned Iteration = 0;
13154   while (DoOneIteration(F, Iteration++))
13155     EverMadeChange = true;
13156   return EverMadeChange;
13157 }
13158
13159 FunctionPass *llvm::createInstructionCombiningPass() {
13160   return new InstCombiner();
13161 }