Fix 80-col violations.
[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 = Context->getUndef(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(User *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 Context->getConstantExprCast(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(Context->getUndef(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 = Context->getConstantExpr(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 = Context->getConstantExpr(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 Context->getConstantExprNeg(C);
570
571   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572     if (C->getType()->getElementType()->isInteger())
573       return Context->getConstantExprNeg(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 Context->getConstantExprFNeg(C);
589
590   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591     if (C->getType()->getElementType()->isFloatingPoint())
592       return Context->getConstantExprFNeg(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 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
632 /// expression, return it.
633 static User *dyn_castGetElementPtr(Value *V) {
634   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
635   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
636     if (CE->getOpcode() == Instruction::GetElementPtr)
637       return cast<User>(V);
638   return false;
639 }
640
641 /// AddOne - Add one to a ConstantInt
642 static Constant *AddOne(Constant *C, LLVMContext *Context) {
643   return Context->getConstantExprAdd(C, 
644     ConstantInt::get(C->getType(), 1));
645 }
646 /// SubOne - Subtract one from a ConstantInt
647 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
648   return Context->getConstantExprSub(C, 
649     ConstantInt::get(C->getType(), 1));
650 }
651 /// MultiplyOverflows - True if the multiply can not be expressed in an int
652 /// this size.
653 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
654                               LLVMContext *Context) {
655   uint32_t W = C1->getBitWidth();
656   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
657   if (sign) {
658     LHSExt.sext(W * 2);
659     RHSExt.sext(W * 2);
660   } else {
661     LHSExt.zext(W * 2);
662     RHSExt.zext(W * 2);
663   }
664
665   APInt MulExt = LHSExt * RHSExt;
666
667   if (sign) {
668     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670     return MulExt.slt(Min) || MulExt.sgt(Max);
671   } else 
672     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673 }
674
675
676 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
677 /// specified instruction is a constant integer.  If so, check to see if there
678 /// are any bits set in the constant that are not demanded.  If so, shrink the
679 /// constant and return true.
680 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
681                                    APInt Demanded, LLVMContext *Context) {
682   assert(I && "No instruction?");
683   assert(OpNo < I->getNumOperands() && "Operand index too large");
684
685   // If the operand is not a constant integer, nothing to do.
686   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687   if (!OpC) return false;
688
689   // If there are no bits set that aren't demanded, nothing to do.
690   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691   if ((~Demanded & OpC->getValue()) == 0)
692     return false;
693
694   // This instruction is producing bits that are not demanded. Shrink the RHS.
695   Demanded &= OpC->getValue();
696   I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
697   return true;
698 }
699
700 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
701 // set of known zero and one bits, compute the maximum and minimum values that
702 // could have the specified known zero and known one bits, returning them in
703 // min/max.
704 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
705                                                    const APInt& KnownOne,
706                                                    APInt& Min, APInt& Max) {
707   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708          KnownZero.getBitWidth() == Min.getBitWidth() &&
709          KnownZero.getBitWidth() == Max.getBitWidth() &&
710          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
711   APInt UnknownBits = ~(KnownZero|KnownOne);
712
713   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714   // bit if it is unknown.
715   Min = KnownOne;
716   Max = KnownOne|UnknownBits;
717   
718   if (UnknownBits.isNegative()) { // Sign bit is unknown
719     Min.set(Min.getBitWidth()-1);
720     Max.clear(Max.getBitWidth()-1);
721   }
722 }
723
724 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725 // a set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
727 // min/max.
728 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732          KnownZero.getBitWidth() == Min.getBitWidth() &&
733          KnownZero.getBitWidth() == Max.getBitWidth() &&
734          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735   APInt UnknownBits = ~(KnownZero|KnownOne);
736   
737   // The minimum value is when the unknown bits are all zeros.
738   Min = KnownOne;
739   // The maximum value is when the unknown bits are all ones.
740   Max = KnownOne|UnknownBits;
741 }
742
743 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744 /// SimplifyDemandedBits knows about.  See if the instruction has any
745 /// properties that allow us to simplify its operands.
746 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
747   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
748   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
750   
751   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
752                                      KnownZero, KnownOne, 0);
753   if (V == 0) return false;
754   if (V == &Inst) return true;
755   ReplaceInstUsesWith(Inst, V);
756   return true;
757 }
758
759 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760 /// specified instruction operand if possible, updating it in place.  It returns
761 /// true if it made any change and false otherwise.
762 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
763                                         APInt &KnownZero, APInt &KnownOne,
764                                         unsigned Depth) {
765   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766                                           KnownZero, KnownOne, Depth);
767   if (NewVal == 0) return false;
768   U.set(NewVal);
769   return true;
770 }
771
772
773 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774 /// value based on the demanded bits.  When this function is called, it is known
775 /// that only the bits set in DemandedMask of the result of V are ever used
776 /// downstream. Consequently, depending on the mask and V, it may be possible
777 /// to replace V with a constant or one of its operands. In such cases, this
778 /// function does the replacement and returns true. In all other cases, it
779 /// returns false after analyzing the expression and setting KnownOne and known
780 /// to be one in the expression.  KnownZero contains all the bits that are known
781 /// to be zero in the expression. These are provided to potentially allow the
782 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783 /// the expression. KnownOne and KnownZero always follow the invariant that 
784 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
786 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787 /// and KnownOne must all be the same.
788 ///
789 /// This returns null if it did not change anything and it permits no
790 /// simplification.  This returns V itself if it did some simplification of V's
791 /// operands based on the information about what bits are demanded. This returns
792 /// some other non-null value if it found out that V is equal to another value
793 /// in the context where the specified bits are demanded, but not for all users.
794 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795                                              APInt &KnownZero, APInt &KnownOne,
796                                              unsigned Depth) {
797   assert(V != 0 && "Null pointer of Value???");
798   assert(Depth <= 6 && "Limit Search Depth");
799   uint32_t BitWidth = DemandedMask.getBitWidth();
800   const Type *VTy = V->getType();
801   assert((TD || !isa<PointerType>(VTy)) &&
802          "SimplifyDemandedBits needs to know bit widths!");
803   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804          (!VTy->isIntOrIntVector() ||
805           VTy->getScalarSizeInBits() == BitWidth) &&
806          KnownZero.getBitWidth() == BitWidth &&
807          KnownOne.getBitWidth() == BitWidth &&
808          "Value *V, DemandedMask, KnownZero and KnownOne "
809          "must have same BitWidth");
810   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811     // We know all of the bits for a constant!
812     KnownOne = CI->getValue() & DemandedMask;
813     KnownZero = ~KnownOne & DemandedMask;
814     return 0;
815   }
816   if (isa<ConstantPointerNull>(V)) {
817     // We know all of the bits for a constant!
818     KnownOne.clear();
819     KnownZero = DemandedMask;
820     return 0;
821   }
822
823   KnownZero.clear();
824   KnownOne.clear();
825   if (DemandedMask == 0) {   // Not demanding any bits from V.
826     if (isa<UndefValue>(V))
827       return 0;
828     return Context->getUndef(VTy);
829   }
830   
831   if (Depth == 6)        // Limit search depth.
832     return 0;
833   
834   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
836
837   Instruction *I = dyn_cast<Instruction>(V);
838   if (!I) {
839     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840     return 0;        // Only analyze instructions.
841   }
842
843   // If there are multiple uses of this value and we aren't at the root, then
844   // we can't do any simplifications of the operands, because DemandedMask
845   // only reflects the bits demanded by *one* of the users.
846   if (Depth != 0 && !I->hasOneUse()) {
847     // Despite the fact that we can't simplify this instruction in all User's
848     // context, we can at least compute the knownzero/knownone bits, and we can
849     // do simplifications that apply to *just* the one user if we know that
850     // this instruction has a simpler value in that context.
851     if (I->getOpcode() == Instruction::And) {
852       // If either the LHS or the RHS are Zero, the result is zero.
853       ComputeMaskedBits(I->getOperand(1), DemandedMask,
854                         RHSKnownZero, RHSKnownOne, Depth+1);
855       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856                         LHSKnownZero, LHSKnownOne, Depth+1);
857       
858       // If all of the demanded bits are known 1 on one side, return the other.
859       // These bits cannot contribute to the result of the 'and' in this
860       // context.
861       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
862           (DemandedMask & ~LHSKnownZero))
863         return I->getOperand(0);
864       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
865           (DemandedMask & ~RHSKnownZero))
866         return I->getOperand(1);
867       
868       // If all of the demanded bits in the inputs are known zeros, return zero.
869       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
870         return Context->getNullValue(VTy);
871       
872     } else if (I->getOpcode() == Instruction::Or) {
873       // We can simplify (X|Y) -> X or Y in the user's context if we know that
874       // only bits from X or Y are demanded.
875       
876       // If either the LHS or the RHS are One, the result is One.
877       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
878                         RHSKnownZero, RHSKnownOne, Depth+1);
879       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
880                         LHSKnownZero, LHSKnownOne, Depth+1);
881       
882       // If all of the demanded bits are known zero on one side, return the
883       // other.  These bits cannot contribute to the result of the 'or' in this
884       // context.
885       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
886           (DemandedMask & ~LHSKnownOne))
887         return I->getOperand(0);
888       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
889           (DemandedMask & ~RHSKnownOne))
890         return I->getOperand(1);
891       
892       // If all of the potentially set bits on one side are known to be set on
893       // the other side, just use the 'other' side.
894       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
895           (DemandedMask & (~RHSKnownZero)))
896         return I->getOperand(0);
897       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
898           (DemandedMask & (~LHSKnownZero)))
899         return I->getOperand(1);
900     }
901     
902     // Compute the KnownZero/KnownOne bits to simplify things downstream.
903     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904     return 0;
905   }
906   
907   // If this is the root being simplified, allow it to have multiple uses,
908   // just set the DemandedMask to all bits so that we can try to simplify the
909   // operands.  This allows visitTruncInst (for example) to simplify the
910   // operand of a trunc without duplicating all the logic below.
911   if (Depth == 0 && !V->hasOneUse())
912     DemandedMask = APInt::getAllOnesValue(BitWidth);
913   
914   switch (I->getOpcode()) {
915   default:
916     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
917     break;
918   case Instruction::And:
919     // If either the LHS or the RHS are Zero, the result is zero.
920     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921                              RHSKnownZero, RHSKnownOne, Depth+1) ||
922         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
923                              LHSKnownZero, LHSKnownOne, Depth+1))
924       return I;
925     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
926     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
927
928     // If all of the demanded bits are known 1 on one side, return the other.
929     // These bits cannot contribute to the result of the 'and'.
930     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
931         (DemandedMask & ~LHSKnownZero))
932       return I->getOperand(0);
933     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
934         (DemandedMask & ~RHSKnownZero))
935       return I->getOperand(1);
936     
937     // If all of the demanded bits in the inputs are known zeros, return zero.
938     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
939       return Context->getNullValue(VTy);
940       
941     // If the RHS is a constant, see if we can simplify it.
942     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
943       return I;
944       
945     // Output known-1 bits are only known if set in both the LHS & RHS.
946     RHSKnownOne &= LHSKnownOne;
947     // Output known-0 are known to be clear if zero in either the LHS | RHS.
948     RHSKnownZero |= LHSKnownZero;
949     break;
950   case Instruction::Or:
951     // If either the LHS or the RHS are One, the result is One.
952     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
953                              RHSKnownZero, RHSKnownOne, Depth+1) ||
954         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
955                              LHSKnownZero, LHSKnownOne, Depth+1))
956       return I;
957     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
958     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
959     
960     // If all of the demanded bits are known zero on one side, return the other.
961     // These bits cannot contribute to the result of the 'or'.
962     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
963         (DemandedMask & ~LHSKnownOne))
964       return I->getOperand(0);
965     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
966         (DemandedMask & ~RHSKnownOne))
967       return I->getOperand(1);
968
969     // If all of the potentially set bits on one side are known to be set on
970     // the other side, just use the 'other' side.
971     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
972         (DemandedMask & (~RHSKnownZero)))
973       return I->getOperand(0);
974     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
975         (DemandedMask & (~LHSKnownZero)))
976       return I->getOperand(1);
977         
978     // If the RHS is a constant, see if we can simplify it.
979     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
980       return I;
981           
982     // Output known-0 bits are only known if clear in both the LHS & RHS.
983     RHSKnownZero &= LHSKnownZero;
984     // Output known-1 are known to be set if set in either the LHS | RHS.
985     RHSKnownOne |= LHSKnownOne;
986     break;
987   case Instruction::Xor: {
988     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989                              RHSKnownZero, RHSKnownOne, Depth+1) ||
990         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
991                              LHSKnownZero, LHSKnownOne, Depth+1))
992       return I;
993     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
994     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
995     
996     // If all of the demanded bits are known zero on one side, return the other.
997     // These bits cannot contribute to the result of the 'xor'.
998     if ((DemandedMask & RHSKnownZero) == DemandedMask)
999       return I->getOperand(0);
1000     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1001       return I->getOperand(1);
1002     
1003     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1005                          (RHSKnownOne & LHSKnownOne);
1006     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1008                         (RHSKnownOne & LHSKnownZero);
1009     
1010     // If all of the demanded bits are known to be zero on one side or the
1011     // other, turn this into an *inclusive* or.
1012     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1013     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1014       Instruction *Or =
1015         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1016                                  I->getName());
1017       return InsertNewInstBefore(Or, *I);
1018     }
1019     
1020     // If all of the demanded bits on one side are known, and all of the set
1021     // bits on that side are also known to be set on the other side, turn this
1022     // into an AND, as we know the bits will be cleared.
1023     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1024     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1025       // all known
1026       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1027         Constant *AndC = ConstantInt::get(*Context, 
1028                                           ~RHSKnownOne & DemandedMask);
1029         Instruction *And = 
1030           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1031         return InsertNewInstBefore(And, *I);
1032       }
1033     }
1034     
1035     // If the RHS is a constant, see if we can simplify it.
1036     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1037     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1038       return I;
1039     
1040     RHSKnownZero = KnownZeroOut;
1041     RHSKnownOne  = KnownOneOut;
1042     break;
1043   }
1044   case Instruction::Select:
1045     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1046                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1047         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1048                              LHSKnownZero, LHSKnownOne, Depth+1))
1049       return I;
1050     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1051     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1052     
1053     // If the operands are constants, see if we can simplify them.
1054     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1055         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1056       return I;
1057     
1058     // Only known if known in both the LHS and RHS.
1059     RHSKnownOne &= LHSKnownOne;
1060     RHSKnownZero &= LHSKnownZero;
1061     break;
1062   case Instruction::Trunc: {
1063     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1064     DemandedMask.zext(truncBf);
1065     RHSKnownZero.zext(truncBf);
1066     RHSKnownOne.zext(truncBf);
1067     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1068                              RHSKnownZero, RHSKnownOne, Depth+1))
1069       return I;
1070     DemandedMask.trunc(BitWidth);
1071     RHSKnownZero.trunc(BitWidth);
1072     RHSKnownOne.trunc(BitWidth);
1073     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1074     break;
1075   }
1076   case Instruction::BitCast:
1077     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1078       return false;  // vector->int or fp->int?
1079
1080     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1081       if (const VectorType *SrcVTy =
1082             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1083         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1084           // Don't touch a bitcast between vectors of different element counts.
1085           return false;
1086       } else
1087         // Don't touch a scalar-to-vector bitcast.
1088         return false;
1089     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1090       // Don't touch a vector-to-scalar bitcast.
1091       return false;
1092
1093     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1094                              RHSKnownZero, RHSKnownOne, Depth+1))
1095       return I;
1096     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1097     break;
1098   case Instruction::ZExt: {
1099     // Compute the bits in the result that are not present in the input.
1100     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1101     
1102     DemandedMask.trunc(SrcBitWidth);
1103     RHSKnownZero.trunc(SrcBitWidth);
1104     RHSKnownOne.trunc(SrcBitWidth);
1105     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     DemandedMask.zext(BitWidth);
1109     RHSKnownZero.zext(BitWidth);
1110     RHSKnownOne.zext(BitWidth);
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112     // The top bits are known to be zero.
1113     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1114     break;
1115   }
1116   case Instruction::SExt: {
1117     // Compute the bits in the result that are not present in the input.
1118     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1119     
1120     APInt InputDemandedBits = DemandedMask & 
1121                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1122
1123     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1124     // If any of the sign extended bits are demanded, we know that the sign
1125     // bit is demanded.
1126     if ((NewBits & DemandedMask) != 0)
1127       InputDemandedBits.set(SrcBitWidth-1);
1128       
1129     InputDemandedBits.trunc(SrcBitWidth);
1130     RHSKnownZero.trunc(SrcBitWidth);
1131     RHSKnownOne.trunc(SrcBitWidth);
1132     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1133                              RHSKnownZero, RHSKnownOne, Depth+1))
1134       return I;
1135     InputDemandedBits.zext(BitWidth);
1136     RHSKnownZero.zext(BitWidth);
1137     RHSKnownOne.zext(BitWidth);
1138     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1139       
1140     // If the sign bit of the input is known set or clear, then we know the
1141     // top bits of the result.
1142
1143     // If the input sign bit is known zero, or if the NewBits are not demanded
1144     // convert this into a zero extension.
1145     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1146       // Convert to ZExt cast
1147       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1148       return InsertNewInstBefore(NewCast, *I);
1149     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1150       RHSKnownOne |= NewBits;
1151     }
1152     break;
1153   }
1154   case Instruction::Add: {
1155     // Figure out what the input bits are.  If the top bits of the and result
1156     // are not demanded, then the add doesn't demand them from its input
1157     // either.
1158     unsigned NLZ = DemandedMask.countLeadingZeros();
1159       
1160     // If there is a constant on the RHS, there are a variety of xformations
1161     // we can do.
1162     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163       // If null, this should be simplified elsewhere.  Some of the xforms here
1164       // won't work if the RHS is zero.
1165       if (RHS->isZero())
1166         break;
1167       
1168       // If the top bit of the output is demanded, demand everything from the
1169       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1170       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1171
1172       // Find information about known zero/one bits in the input.
1173       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1174                                LHSKnownZero, LHSKnownOne, Depth+1))
1175         return I;
1176
1177       // If the RHS of the add has bits set that can't affect the input, reduce
1178       // the constant.
1179       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1180         return I;
1181       
1182       // Avoid excess work.
1183       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1184         break;
1185       
1186       // Turn it into OR if input bits are zero.
1187       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1188         Instruction *Or =
1189           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1190                                    I->getName());
1191         return InsertNewInstBefore(Or, *I);
1192       }
1193       
1194       // We can say something about the output known-zero and known-one bits,
1195       // depending on potential carries from the input constant and the
1196       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1197       // bits set and the RHS constant is 0x01001, then we know we have a known
1198       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1199       
1200       // To compute this, we first compute the potential carry bits.  These are
1201       // the bits which may be modified.  I'm not aware of a better way to do
1202       // this scan.
1203       const APInt &RHSVal = RHS->getValue();
1204       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1205       
1206       // Now that we know which bits have carries, compute the known-1/0 sets.
1207       
1208       // Bits are known one if they are known zero in one operand and one in the
1209       // other, and there is no input carry.
1210       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1211                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1212       
1213       // Bits are known zero if they are known zero in both operands and there
1214       // is no input carry.
1215       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1216     } else {
1217       // If the high-bits of this ADD are not demanded, then it does not demand
1218       // the high bits of its LHS or RHS.
1219       if (DemandedMask[BitWidth-1] == 0) {
1220         // Right fill the mask of bits for this ADD to demand the most
1221         // significant bit and all those below it.
1222         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1223         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1224                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1225             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1226                                  LHSKnownZero, LHSKnownOne, Depth+1))
1227           return I;
1228       }
1229     }
1230     break;
1231   }
1232   case Instruction::Sub:
1233     // If the high-bits of this SUB are not demanded, then it does not demand
1234     // the high bits of its LHS or RHS.
1235     if (DemandedMask[BitWidth-1] == 0) {
1236       // Right fill the mask of bits for this SUB to demand the most
1237       // significant bit and all those below it.
1238       uint32_t NLZ = DemandedMask.countLeadingZeros();
1239       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1240       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1241                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1242           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1243                                LHSKnownZero, LHSKnownOne, Depth+1))
1244         return I;
1245     }
1246     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1247     // the known zeros and ones.
1248     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1249     break;
1250   case Instruction::Shl:
1251     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1252       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1253       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1254       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1255                                RHSKnownZero, RHSKnownOne, Depth+1))
1256         return I;
1257       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1258       RHSKnownZero <<= ShiftAmt;
1259       RHSKnownOne  <<= ShiftAmt;
1260       // low bits known zero.
1261       if (ShiftAmt)
1262         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1263     }
1264     break;
1265   case Instruction::LShr:
1266     // For a logical shift right
1267     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1268       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1269       
1270       // Unsigned shift right.
1271       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1272       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1273                                RHSKnownZero, RHSKnownOne, Depth+1))
1274         return I;
1275       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1276       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1277       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1278       if (ShiftAmt) {
1279         // Compute the new bits that are at the top now.
1280         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1281         RHSKnownZero |= HighBits;  // high bits known zero.
1282       }
1283     }
1284     break;
1285   case Instruction::AShr:
1286     // If this is an arithmetic shift right and only the low-bit is set, we can
1287     // always convert this into a logical shr, even if the shift amount is
1288     // variable.  The low bit of the shift cannot be an input sign bit unless
1289     // the shift amount is >= the size of the datatype, which is undefined.
1290     if (DemandedMask == 1) {
1291       // Perform the logical shift right.
1292       Instruction *NewVal = BinaryOperator::CreateLShr(
1293                         I->getOperand(0), I->getOperand(1), I->getName());
1294       return InsertNewInstBefore(NewVal, *I);
1295     }    
1296
1297     // If the sign bit is the only bit demanded by this ashr, then there is no
1298     // need to do it, the shift doesn't change the high bit.
1299     if (DemandedMask.isSignBit())
1300       return I->getOperand(0);
1301     
1302     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1303       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1304       
1305       // Signed shift right.
1306       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1307       // If any of the "high bits" are demanded, we should set the sign bit as
1308       // demanded.
1309       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1310         DemandedMaskIn.set(BitWidth-1);
1311       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1312                                RHSKnownZero, RHSKnownOne, Depth+1))
1313         return I;
1314       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1315       // Compute the new bits that are at the top now.
1316       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1317       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1319         
1320       // Handle the sign bits.
1321       APInt SignBit(APInt::getSignBit(BitWidth));
1322       // Adjust to where it is now in the mask.
1323       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1324         
1325       // If the input sign bit is known to be zero, or if none of the top bits
1326       // are demanded, turn this into an unsigned shift right.
1327       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1328           (HighBits & ~DemandedMask) == HighBits) {
1329         // Perform the logical shift right.
1330         Instruction *NewVal = BinaryOperator::CreateLShr(
1331                           I->getOperand(0), SA, I->getName());
1332         return InsertNewInstBefore(NewVal, *I);
1333       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1334         RHSKnownOne |= HighBits;
1335       }
1336     }
1337     break;
1338   case Instruction::SRem:
1339     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1340       APInt RA = Rem->getValue().abs();
1341       if (RA.isPowerOf2()) {
1342         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1343           return I->getOperand(0);
1344
1345         APInt LowBits = RA - 1;
1346         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1347         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1348                                  LHSKnownZero, LHSKnownOne, Depth+1))
1349           return I;
1350
1351         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1352           LHSKnownZero |= ~LowBits;
1353
1354         KnownZero |= LHSKnownZero & DemandedMask;
1355
1356         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1357       }
1358     }
1359     break;
1360   case Instruction::URem: {
1361     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1362     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1363     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1364                              KnownZero2, KnownOne2, Depth+1) ||
1365         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1366                              KnownZero2, KnownOne2, Depth+1))
1367       return I;
1368
1369     unsigned Leaders = KnownZero2.countLeadingOnes();
1370     Leaders = std::max(Leaders,
1371                        KnownZero2.countLeadingOnes());
1372     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1373     break;
1374   }
1375   case Instruction::Call:
1376     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1377       switch (II->getIntrinsicID()) {
1378       default: break;
1379       case Intrinsic::bswap: {
1380         // If the only bits demanded come from one byte of the bswap result,
1381         // just shift the input byte into position to eliminate the bswap.
1382         unsigned NLZ = DemandedMask.countLeadingZeros();
1383         unsigned NTZ = DemandedMask.countTrailingZeros();
1384           
1385         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1386         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1387         // have 14 leading zeros, round to 8.
1388         NLZ &= ~7;
1389         NTZ &= ~7;
1390         // If we need exactly one byte, we can do this transformation.
1391         if (BitWidth-NLZ-NTZ == 8) {
1392           unsigned ResultBit = NTZ;
1393           unsigned InputBit = BitWidth-NTZ-8;
1394           
1395           // Replace this with either a left or right shift to get the byte into
1396           // the right place.
1397           Instruction *NewVal;
1398           if (InputBit > ResultBit)
1399             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1400                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1401           else
1402             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1403                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1404           NewVal->takeName(I);
1405           return InsertNewInstBefore(NewVal, *I);
1406         }
1407           
1408         // TODO: Could compute known zero/one bits based on the input.
1409         break;
1410       }
1411       }
1412     }
1413     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1414     break;
1415   }
1416   
1417   // If the client is only demanding bits that we know, return the known
1418   // constant.
1419   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1420     Constant *C = ConstantInt::get(*Context, RHSKnownOne);
1421     if (isa<PointerType>(V->getType()))
1422       C = Context->getConstantExprIntToPtr(C, V->getType());
1423     return C;
1424   }
1425   return false;
1426 }
1427
1428
1429 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1430 /// any number of elements. DemandedElts contains the set of elements that are
1431 /// actually used by the caller.  This method analyzes which elements of the
1432 /// operand are undef and returns that information in UndefElts.
1433 ///
1434 /// If the information about demanded elements can be used to simplify the
1435 /// operation, the operation is simplified, then the resultant value is
1436 /// returned.  This returns null if no change was made.
1437 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1438                                                 APInt& UndefElts,
1439                                                 unsigned Depth) {
1440   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1441   APInt EltMask(APInt::getAllOnesValue(VWidth));
1442   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1443
1444   if (isa<UndefValue>(V)) {
1445     // If the entire vector is undefined, just return this info.
1446     UndefElts = EltMask;
1447     return 0;
1448   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1449     UndefElts = EltMask;
1450     return Context->getUndef(V->getType());
1451   }
1452
1453   UndefElts = 0;
1454   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1455     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1456     Constant *Undef = Context->getUndef(EltTy);
1457
1458     std::vector<Constant*> Elts;
1459     for (unsigned i = 0; i != VWidth; ++i)
1460       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1461         Elts.push_back(Undef);
1462         UndefElts.set(i);
1463       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1464         Elts.push_back(Undef);
1465         UndefElts.set(i);
1466       } else {                               // Otherwise, defined.
1467         Elts.push_back(CP->getOperand(i));
1468       }
1469
1470     // If we changed the constant, return it.
1471     Constant *NewCP = Context->getConstantVector(Elts);
1472     return NewCP != CP ? NewCP : 0;
1473   } else if (isa<ConstantAggregateZero>(V)) {
1474     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1475     // set to undef.
1476     
1477     // Check if this is identity. If so, return 0 since we are not simplifying
1478     // anything.
1479     if (DemandedElts == ((1ULL << VWidth) -1))
1480       return 0;
1481     
1482     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1483     Constant *Zero = Context->getNullValue(EltTy);
1484     Constant *Undef = Context->getUndef(EltTy);
1485     std::vector<Constant*> Elts;
1486     for (unsigned i = 0; i != VWidth; ++i) {
1487       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1488       Elts.push_back(Elt);
1489     }
1490     UndefElts = DemandedElts ^ EltMask;
1491     return Context->getConstantVector(Elts);
1492   }
1493   
1494   // Limit search depth.
1495   if (Depth == 10)
1496     return 0;
1497
1498   // If multiple users are using the root value, procede with
1499   // simplification conservatively assuming that all elements
1500   // are needed.
1501   if (!V->hasOneUse()) {
1502     // Quit if we find multiple users of a non-root value though.
1503     // They'll be handled when it's their turn to be visited by
1504     // the main instcombine process.
1505     if (Depth != 0)
1506       // TODO: Just compute the UndefElts information recursively.
1507       return 0;
1508
1509     // Conservatively assume that all elements are needed.
1510     DemandedElts = EltMask;
1511   }
1512   
1513   Instruction *I = dyn_cast<Instruction>(V);
1514   if (!I) return 0;        // Only analyze instructions.
1515   
1516   bool MadeChange = false;
1517   APInt UndefElts2(VWidth, 0);
1518   Value *TmpV;
1519   switch (I->getOpcode()) {
1520   default: break;
1521     
1522   case Instruction::InsertElement: {
1523     // If this is a variable index, we don't know which element it overwrites.
1524     // demand exactly the same input as we produce.
1525     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1526     if (Idx == 0) {
1527       // Note that we can't propagate undef elt info, because we don't know
1528       // which elt is getting updated.
1529       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530                                         UndefElts2, Depth+1);
1531       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532       break;
1533     }
1534     
1535     // If this is inserting an element that isn't demanded, remove this
1536     // insertelement.
1537     unsigned IdxNo = Idx->getZExtValue();
1538     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1539       return AddSoonDeadInstToWorklist(*I, 0);
1540     
1541     // Otherwise, the element inserted overwrites whatever was there, so the
1542     // input demanded set is simpler than the output set.
1543     APInt DemandedElts2 = DemandedElts;
1544     DemandedElts2.clear(IdxNo);
1545     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1546                                       UndefElts, Depth+1);
1547     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1548
1549     // The inserted element is defined.
1550     UndefElts.clear(IdxNo);
1551     break;
1552   }
1553   case Instruction::ShuffleVector: {
1554     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1555     uint64_t LHSVWidth =
1556       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1557     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1558     for (unsigned i = 0; i < VWidth; i++) {
1559       if (DemandedElts[i]) {
1560         unsigned MaskVal = Shuffle->getMaskValue(i);
1561         if (MaskVal != -1u) {
1562           assert(MaskVal < LHSVWidth * 2 &&
1563                  "shufflevector mask index out of range!");
1564           if (MaskVal < LHSVWidth)
1565             LeftDemanded.set(MaskVal);
1566           else
1567             RightDemanded.set(MaskVal - LHSVWidth);
1568         }
1569       }
1570     }
1571
1572     APInt UndefElts4(LHSVWidth, 0);
1573     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1574                                       UndefElts4, Depth+1);
1575     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1576
1577     APInt UndefElts3(LHSVWidth, 0);
1578     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1579                                       UndefElts3, Depth+1);
1580     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1581
1582     bool NewUndefElts = false;
1583     for (unsigned i = 0; i < VWidth; i++) {
1584       unsigned MaskVal = Shuffle->getMaskValue(i);
1585       if (MaskVal == -1u) {
1586         UndefElts.set(i);
1587       } else if (MaskVal < LHSVWidth) {
1588         if (UndefElts4[MaskVal]) {
1589           NewUndefElts = true;
1590           UndefElts.set(i);
1591         }
1592       } else {
1593         if (UndefElts3[MaskVal - LHSVWidth]) {
1594           NewUndefElts = true;
1595           UndefElts.set(i);
1596         }
1597       }
1598     }
1599
1600     if (NewUndefElts) {
1601       // Add additional discovered undefs.
1602       std::vector<Constant*> Elts;
1603       for (unsigned i = 0; i < VWidth; ++i) {
1604         if (UndefElts[i])
1605           Elts.push_back(Context->getUndef(Type::Int32Ty));
1606         else
1607           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1608                                           Shuffle->getMaskValue(i)));
1609       }
1610       I->setOperand(2, Context->getConstantVector(Elts));
1611       MadeChange = true;
1612     }
1613     break;
1614   }
1615   case Instruction::BitCast: {
1616     // Vector->vector casts only.
1617     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1618     if (!VTy) break;
1619     unsigned InVWidth = VTy->getNumElements();
1620     APInt InputDemandedElts(InVWidth, 0);
1621     unsigned Ratio;
1622
1623     if (VWidth == InVWidth) {
1624       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1625       // elements as are demanded of us.
1626       Ratio = 1;
1627       InputDemandedElts = DemandedElts;
1628     } else if (VWidth > InVWidth) {
1629       // Untested so far.
1630       break;
1631       
1632       // If there are more elements in the result than there are in the source,
1633       // then an input element is live if any of the corresponding output
1634       // elements are live.
1635       Ratio = VWidth/InVWidth;
1636       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1637         if (DemandedElts[OutIdx])
1638           InputDemandedElts.set(OutIdx/Ratio);
1639       }
1640     } else {
1641       // Untested so far.
1642       break;
1643       
1644       // If there are more elements in the source than there are in the result,
1645       // then an input element is live if the corresponding output element is
1646       // live.
1647       Ratio = InVWidth/VWidth;
1648       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1649         if (DemandedElts[InIdx/Ratio])
1650           InputDemandedElts.set(InIdx);
1651     }
1652     
1653     // div/rem demand all inputs, because they don't want divide by zero.
1654     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1655                                       UndefElts2, Depth+1);
1656     if (TmpV) {
1657       I->setOperand(0, TmpV);
1658       MadeChange = true;
1659     }
1660     
1661     UndefElts = UndefElts2;
1662     if (VWidth > InVWidth) {
1663       llvm_unreachable("Unimp");
1664       // If there are more elements in the result than there are in the source,
1665       // then an output element is undef if the corresponding input element is
1666       // undef.
1667       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1668         if (UndefElts2[OutIdx/Ratio])
1669           UndefElts.set(OutIdx);
1670     } else if (VWidth < InVWidth) {
1671       llvm_unreachable("Unimp");
1672       // If there are more elements in the source than there are in the result,
1673       // then a result element is undef if all of the corresponding input
1674       // elements are undef.
1675       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1676       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1677         if (!UndefElts2[InIdx])            // Not undef?
1678           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1679     }
1680     break;
1681   }
1682   case Instruction::And:
1683   case Instruction::Or:
1684   case Instruction::Xor:
1685   case Instruction::Add:
1686   case Instruction::Sub:
1687   case Instruction::Mul:
1688     // div/rem demand all inputs, because they don't want divide by zero.
1689     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1690                                       UndefElts, Depth+1);
1691     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1692     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1693                                       UndefElts2, Depth+1);
1694     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1695       
1696     // Output elements are undefined if both are undefined.  Consider things
1697     // like undef&0.  The result is known zero, not undef.
1698     UndefElts &= UndefElts2;
1699     break;
1700     
1701   case Instruction::Call: {
1702     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1703     if (!II) break;
1704     switch (II->getIntrinsicID()) {
1705     default: break;
1706       
1707     // Binary vector operations that work column-wise.  A dest element is a
1708     // function of the corresponding input elements from the two inputs.
1709     case Intrinsic::x86_sse_sub_ss:
1710     case Intrinsic::x86_sse_mul_ss:
1711     case Intrinsic::x86_sse_min_ss:
1712     case Intrinsic::x86_sse_max_ss:
1713     case Intrinsic::x86_sse2_sub_sd:
1714     case Intrinsic::x86_sse2_mul_sd:
1715     case Intrinsic::x86_sse2_min_sd:
1716     case Intrinsic::x86_sse2_max_sd:
1717       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1718                                         UndefElts, Depth+1);
1719       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1720       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1721                                         UndefElts2, Depth+1);
1722       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1723
1724       // If only the low elt is demanded and this is a scalarizable intrinsic,
1725       // scalarize it now.
1726       if (DemandedElts == 1) {
1727         switch (II->getIntrinsicID()) {
1728         default: break;
1729         case Intrinsic::x86_sse_sub_ss:
1730         case Intrinsic::x86_sse_mul_ss:
1731         case Intrinsic::x86_sse2_sub_sd:
1732         case Intrinsic::x86_sse2_mul_sd:
1733           // TODO: Lower MIN/MAX/ABS/etc
1734           Value *LHS = II->getOperand(1);
1735           Value *RHS = II->getOperand(2);
1736           // Extract the element as scalars.
1737           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1738             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1739           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1740             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1741           
1742           switch (II->getIntrinsicID()) {
1743           default: llvm_unreachable("Case stmts out of sync!");
1744           case Intrinsic::x86_sse_sub_ss:
1745           case Intrinsic::x86_sse2_sub_sd:
1746             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1747                                                         II->getName()), *II);
1748             break;
1749           case Intrinsic::x86_sse_mul_ss:
1750           case Intrinsic::x86_sse2_mul_sd:
1751             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1752                                                          II->getName()), *II);
1753             break;
1754           }
1755           
1756           Instruction *New =
1757             InsertElementInst::Create(
1758               Context->getUndef(II->getType()), TmpV,
1759               ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
1760           InsertNewInstBefore(New, *II);
1761           AddSoonDeadInstToWorklist(*II, 0);
1762           return New;
1763         }            
1764       }
1765         
1766       // Output elements are undefined if both are undefined.  Consider things
1767       // like undef&0.  The result is known zero, not undef.
1768       UndefElts &= UndefElts2;
1769       break;
1770     }
1771     break;
1772   }
1773   }
1774   return MadeChange ? I : 0;
1775 }
1776
1777
1778 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1779 /// function is designed to check a chain of associative operators for a
1780 /// potential to apply a certain optimization.  Since the optimization may be
1781 /// applicable if the expression was reassociated, this checks the chain, then
1782 /// reassociates the expression as necessary to expose the optimization
1783 /// opportunity.  This makes use of a special Functor, which must define
1784 /// 'shouldApply' and 'apply' methods.
1785 ///
1786 template<typename Functor>
1787 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1788                                    LLVMContext *Context) {
1789   unsigned Opcode = Root.getOpcode();
1790   Value *LHS = Root.getOperand(0);
1791
1792   // Quick check, see if the immediate LHS matches...
1793   if (F.shouldApply(LHS))
1794     return F.apply(Root);
1795
1796   // Otherwise, if the LHS is not of the same opcode as the root, return.
1797   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1798   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1799     // Should we apply this transform to the RHS?
1800     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1801
1802     // If not to the RHS, check to see if we should apply to the LHS...
1803     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1804       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1805       ShouldApply = true;
1806     }
1807
1808     // If the functor wants to apply the optimization to the RHS of LHSI,
1809     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1810     if (ShouldApply) {
1811       // Now all of the instructions are in the current basic block, go ahead
1812       // and perform the reassociation.
1813       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1814
1815       // First move the selected RHS to the LHS of the root...
1816       Root.setOperand(0, LHSI->getOperand(1));
1817
1818       // Make what used to be the LHS of the root be the user of the root...
1819       Value *ExtraOperand = TmpLHSI->getOperand(1);
1820       if (&Root == TmpLHSI) {
1821         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1822         return 0;
1823       }
1824       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1825       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1826       BasicBlock::iterator ARI = &Root; ++ARI;
1827       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1828       ARI = Root;
1829
1830       // Now propagate the ExtraOperand down the chain of instructions until we
1831       // get to LHSI.
1832       while (TmpLHSI != LHSI) {
1833         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1834         // Move the instruction to immediately before the chain we are
1835         // constructing to avoid breaking dominance properties.
1836         NextLHSI->moveBefore(ARI);
1837         ARI = NextLHSI;
1838
1839         Value *NextOp = NextLHSI->getOperand(1);
1840         NextLHSI->setOperand(1, ExtraOperand);
1841         TmpLHSI = NextLHSI;
1842         ExtraOperand = NextOp;
1843       }
1844
1845       // Now that the instructions are reassociated, have the functor perform
1846       // the transformation...
1847       return F.apply(Root);
1848     }
1849
1850     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1851   }
1852   return 0;
1853 }
1854
1855 namespace {
1856
1857 // AddRHS - Implements: X + X --> X << 1
1858 struct AddRHS {
1859   Value *RHS;
1860   LLVMContext *Context;
1861   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1862   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1863   Instruction *apply(BinaryOperator &Add) const {
1864     return BinaryOperator::CreateShl(Add.getOperand(0),
1865                                      ConstantInt::get(Add.getType(), 1));
1866   }
1867 };
1868
1869 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1870 //                 iff C1&C2 == 0
1871 struct AddMaskingAnd {
1872   Constant *C2;
1873   LLVMContext *Context;
1874   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1875   bool shouldApply(Value *LHS) const {
1876     ConstantInt *C1;
1877     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1878            Context->getConstantExprAnd(C1, C2)->isNullValue();
1879   }
1880   Instruction *apply(BinaryOperator &Add) const {
1881     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1882   }
1883 };
1884
1885 }
1886
1887 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1888                                              InstCombiner *IC) {
1889   LLVMContext *Context = IC->getContext();
1890   
1891   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1892     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1893   }
1894
1895   // Figure out if the constant is the left or the right argument.
1896   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1898
1899   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1900     if (ConstIsRHS)
1901       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1902     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1903   }
1904
1905   Value *Op0 = SO, *Op1 = ConstOperand;
1906   if (!ConstIsRHS)
1907     std::swap(Op0, Op1);
1908   Instruction *New;
1909   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1910     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1911   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1912     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1913                           Op0, Op1, SO->getName()+".cmp");
1914   else {
1915     llvm_unreachable("Unknown binary instruction type!");
1916   }
1917   return IC->InsertNewInstBefore(New, I);
1918 }
1919
1920 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1921 // constant as the other operand, try to fold the binary operator into the
1922 // select arguments.  This also works for Cast instructions, which obviously do
1923 // not have a second operand.
1924 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1925                                      InstCombiner *IC) {
1926   // Don't modify shared select instructions
1927   if (!SI->hasOneUse()) return 0;
1928   Value *TV = SI->getOperand(1);
1929   Value *FV = SI->getOperand(2);
1930
1931   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1932     // Bool selects with constant operands can be folded to logical ops.
1933     if (SI->getType() == Type::Int1Ty) return 0;
1934
1935     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1936     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1937
1938     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1939                               SelectFalseVal);
1940   }
1941   return 0;
1942 }
1943
1944
1945 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1946 /// node as operand #0, see if we can fold the instruction into the PHI (which
1947 /// is only possible if all operands to the PHI are constants).
1948 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1949   PHINode *PN = cast<PHINode>(I.getOperand(0));
1950   unsigned NumPHIValues = PN->getNumIncomingValues();
1951   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1952
1953   // Check to see if all of the operands of the PHI are constants.  If there is
1954   // one non-constant value, remember the BB it is.  If there is more than one
1955   // or if *it* is a PHI, bail out.
1956   BasicBlock *NonConstBB = 0;
1957   for (unsigned i = 0; i != NumPHIValues; ++i)
1958     if (!isa<Constant>(PN->getIncomingValue(i))) {
1959       if (NonConstBB) return 0;  // More than one non-const value.
1960       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1961       NonConstBB = PN->getIncomingBlock(i);
1962       
1963       // If the incoming non-constant value is in I's block, we have an infinite
1964       // loop.
1965       if (NonConstBB == I.getParent())
1966         return 0;
1967     }
1968   
1969   // If there is exactly one non-constant value, we can insert a copy of the
1970   // operation in that block.  However, if this is a critical edge, we would be
1971   // inserting the computation one some other paths (e.g. inside a loop).  Only
1972   // do this if the pred block is unconditionally branching into the phi block.
1973   if (NonConstBB) {
1974     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1975     if (!BI || !BI->isUnconditional()) return 0;
1976   }
1977
1978   // Okay, we can do the transformation: create the new PHI node.
1979   PHINode *NewPN = PHINode::Create(I.getType(), "");
1980   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1981   InsertNewInstBefore(NewPN, *PN);
1982   NewPN->takeName(PN);
1983
1984   // Next, add all of the operands to the PHI.
1985   if (I.getNumOperands() == 2) {
1986     Constant *C = cast<Constant>(I.getOperand(1));
1987     for (unsigned i = 0; i != NumPHIValues; ++i) {
1988       Value *InV = 0;
1989       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1990         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1991           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
1992         else
1993           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
1994       } else {
1995         assert(PN->getIncomingBlock(i) == NonConstBB);
1996         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1997           InV = BinaryOperator::Create(BO->getOpcode(),
1998                                        PN->getIncomingValue(i), C, "phitmp",
1999                                        NonConstBB->getTerminator());
2000         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2001           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2002                                 CI->getPredicate(),
2003                                 PN->getIncomingValue(i), C, "phitmp",
2004                                 NonConstBB->getTerminator());
2005         else
2006           llvm_unreachable("Unknown binop!");
2007         
2008         AddToWorkList(cast<Instruction>(InV));
2009       }
2010       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2011     }
2012   } else { 
2013     CastInst *CI = cast<CastInst>(&I);
2014     const Type *RetTy = CI->getType();
2015     for (unsigned i = 0; i != NumPHIValues; ++i) {
2016       Value *InV;
2017       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2018         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2019       } else {
2020         assert(PN->getIncomingBlock(i) == NonConstBB);
2021         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2022                                I.getType(), "phitmp", 
2023                                NonConstBB->getTerminator());
2024         AddToWorkList(cast<Instruction>(InV));
2025       }
2026       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2027     }
2028   }
2029   return ReplaceInstUsesWith(I, NewPN);
2030 }
2031
2032
2033 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2034 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2035 /// This basically requires proving that the add in the original type would not
2036 /// overflow to change the sign bit or have a carry out.
2037 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2038   // There are different heuristics we can use for this.  Here are some simple
2039   // ones.
2040   
2041   // Add has the property that adding any two 2's complement numbers can only 
2042   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2043   // have at least two sign bits, we know that the addition of the two values will
2044   // sign extend fine.
2045   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2046     return true;
2047   
2048   
2049   // If one of the operands only has one non-zero bit, and if the other operand
2050   // has a known-zero bit in a more significant place than it (not including the
2051   // sign bit) the ripple may go up to and fill the zero, but won't change the
2052   // sign.  For example, (X & ~4) + 1.
2053   
2054   // TODO: Implement.
2055   
2056   return false;
2057 }
2058
2059
2060 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2061   bool Changed = SimplifyCommutative(I);
2062   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2063
2064   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2065     // X + undef -> undef
2066     if (isa<UndefValue>(RHS))
2067       return ReplaceInstUsesWith(I, RHS);
2068
2069     // X + 0 --> X
2070     if (RHSC->isNullValue())
2071       return ReplaceInstUsesWith(I, LHS);
2072
2073     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2074       // X + (signbit) --> X ^ signbit
2075       const APInt& Val = CI->getValue();
2076       uint32_t BitWidth = Val.getBitWidth();
2077       if (Val == APInt::getSignBit(BitWidth))
2078         return BinaryOperator::CreateXor(LHS, RHS);
2079       
2080       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2081       // (X & 254)+1 -> (X&254)|1
2082       if (SimplifyDemandedInstructionBits(I))
2083         return &I;
2084
2085       // zext(bool) + C -> bool ? C + 1 : C
2086       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2087         if (ZI->getSrcTy() == Type::Int1Ty)
2088           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2089     }
2090
2091     if (isa<PHINode>(LHS))
2092       if (Instruction *NV = FoldOpIntoPhi(I))
2093         return NV;
2094     
2095     ConstantInt *XorRHS = 0;
2096     Value *XorLHS = 0;
2097     if (isa<ConstantInt>(RHSC) &&
2098         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2099       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2100       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2101       
2102       uint32_t Size = TySizeBits / 2;
2103       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2104       APInt CFF80Val(-C0080Val);
2105       do {
2106         if (TySizeBits > Size) {
2107           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2108           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2109           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2110               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2111             // This is a sign extend if the top bits are known zero.
2112             if (!MaskedValueIsZero(XorLHS, 
2113                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2114               Size = 0;  // Not a sign ext, but can't be any others either.
2115             break;
2116           }
2117         }
2118         Size >>= 1;
2119         C0080Val = APIntOps::lshr(C0080Val, Size);
2120         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2121       } while (Size >= 1);
2122       
2123       // FIXME: This shouldn't be necessary. When the backends can handle types
2124       // with funny bit widths then this switch statement should be removed. It
2125       // is just here to get the size of the "middle" type back up to something
2126       // that the back ends can handle.
2127       const Type *MiddleType = 0;
2128       switch (Size) {
2129         default: break;
2130         case 32: MiddleType = Type::Int32Ty; break;
2131         case 16: MiddleType = Type::Int16Ty; break;
2132         case  8: MiddleType = Type::Int8Ty; break;
2133       }
2134       if (MiddleType) {
2135         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2136         InsertNewInstBefore(NewTrunc, I);
2137         return new SExtInst(NewTrunc, I.getType(), I.getName());
2138       }
2139     }
2140   }
2141
2142   if (I.getType() == Type::Int1Ty)
2143     return BinaryOperator::CreateXor(LHS, RHS);
2144
2145   // X + X --> X << 1
2146   if (I.getType()->isInteger()) {
2147     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2148       return Result;
2149
2150     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2151       if (RHSI->getOpcode() == Instruction::Sub)
2152         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2153           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2154     }
2155     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2156       if (LHSI->getOpcode() == Instruction::Sub)
2157         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2158           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2159     }
2160   }
2161
2162   // -A + B  -->  B - A
2163   // -A + -B  -->  -(A + B)
2164   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2165     if (LHS->getType()->isIntOrIntVector()) {
2166       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2167         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2168         InsertNewInstBefore(NewAdd, I);
2169         return BinaryOperator::CreateNeg(*Context, NewAdd);
2170       }
2171     }
2172     
2173     return BinaryOperator::CreateSub(RHS, LHSV);
2174   }
2175
2176   // A + -B  -->  A - B
2177   if (!isa<Constant>(RHS))
2178     if (Value *V = dyn_castNegVal(RHS, Context))
2179       return BinaryOperator::CreateSub(LHS, V);
2180
2181
2182   ConstantInt *C2;
2183   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2184     if (X == RHS)   // X*C + X --> X * (C+1)
2185       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2186
2187     // X*C1 + X*C2 --> X * (C1+C2)
2188     ConstantInt *C1;
2189     if (X == dyn_castFoldableMul(RHS, C1, Context))
2190       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2191   }
2192
2193   // X + X*C --> X * (C+1)
2194   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2195     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2196
2197   // X + ~X --> -1   since   ~X = -X-1
2198   if (dyn_castNotVal(LHS, Context) == RHS ||
2199       dyn_castNotVal(RHS, Context) == LHS)
2200     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2201   
2202
2203   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2204   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2205     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2206       return R;
2207   
2208   // A+B --> A|B iff A and B have no bits set in common.
2209   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2210     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2211     APInt LHSKnownOne(IT->getBitWidth(), 0);
2212     APInt LHSKnownZero(IT->getBitWidth(), 0);
2213     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2214     if (LHSKnownZero != 0) {
2215       APInt RHSKnownOne(IT->getBitWidth(), 0);
2216       APInt RHSKnownZero(IT->getBitWidth(), 0);
2217       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2218       
2219       // No bits in common -> bitwise or.
2220       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2221         return BinaryOperator::CreateOr(LHS, RHS);
2222     }
2223   }
2224
2225   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2226   if (I.getType()->isIntOrIntVector()) {
2227     Value *W, *X, *Y, *Z;
2228     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2229         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2230       if (W != Y) {
2231         if (W == Z) {
2232           std::swap(Y, Z);
2233         } else if (Y == X) {
2234           std::swap(W, X);
2235         } else if (X == Z) {
2236           std::swap(Y, Z);
2237           std::swap(W, X);
2238         }
2239       }
2240
2241       if (W == Y) {
2242         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2243                                                             LHS->getName()), I);
2244         return BinaryOperator::CreateMul(W, NewAdd);
2245       }
2246     }
2247   }
2248
2249   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2250     Value *X = 0;
2251     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2252       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2253
2254     // (X & FF00) + xx00  -> (X+xx00) & FF00
2255     if (LHS->hasOneUse() &&
2256         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2257       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2258       if (Anded == CRHS) {
2259         // See if all bits from the first bit set in the Add RHS up are included
2260         // in the mask.  First, get the rightmost bit.
2261         const APInt& AddRHSV = CRHS->getValue();
2262
2263         // Form a mask of all bits from the lowest bit added through the top.
2264         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2265
2266         // See if the and mask includes all of these bits.
2267         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2268
2269         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2270           // Okay, the xform is safe.  Insert the new add pronto.
2271           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2272                                                             LHS->getName()), I);
2273           return BinaryOperator::CreateAnd(NewAdd, C2);
2274         }
2275       }
2276     }
2277
2278     // Try to fold constant add into select arguments.
2279     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2280       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2281         return R;
2282   }
2283
2284   // add (select X 0 (sub n A)) A  -->  select X A n
2285   {
2286     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2287     Value *A = RHS;
2288     if (!SI) {
2289       SI = dyn_cast<SelectInst>(RHS);
2290       A = LHS;
2291     }
2292     if (SI && SI->hasOneUse()) {
2293       Value *TV = SI->getTrueValue();
2294       Value *FV = SI->getFalseValue();
2295       Value *N;
2296
2297       // Can we fold the add into the argument of the select?
2298       // We check both true and false select arguments for a matching subtract.
2299       if (match(FV, m_Zero(), *Context) &&
2300           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2301         // Fold the add into the true select value.
2302         return SelectInst::Create(SI->getCondition(), N, A);
2303       if (match(TV, m_Zero(), *Context) &&
2304           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2305         // Fold the add into the false select value.
2306         return SelectInst::Create(SI->getCondition(), A, N);
2307     }
2308   }
2309
2310   // Check for (add (sext x), y), see if we can merge this into an
2311   // integer add followed by a sext.
2312   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2313     // (add (sext x), cst) --> (sext (add x, cst'))
2314     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2315       Constant *CI = 
2316         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2317       if (LHSConv->hasOneUse() &&
2318           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2319           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2320         // Insert the new, smaller add.
2321         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2322                                                         CI, "addconv");
2323         InsertNewInstBefore(NewAdd, I);
2324         return new SExtInst(NewAdd, I.getType());
2325       }
2326     }
2327     
2328     // (add (sext x), (sext y)) --> (sext (add int x, y))
2329     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2330       // Only do this if x/y have the same type, if at last one of them has a
2331       // single use (so we don't increase the number of sexts), and if the
2332       // integer add will not overflow.
2333       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2334           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2335           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2336                                    RHSConv->getOperand(0))) {
2337         // Insert the new integer add.
2338         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2339                                                         RHSConv->getOperand(0),
2340                                                         "addconv");
2341         InsertNewInstBefore(NewAdd, I);
2342         return new SExtInst(NewAdd, I.getType());
2343       }
2344     }
2345   }
2346
2347   return Changed ? &I : 0;
2348 }
2349
2350 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2351   bool Changed = SimplifyCommutative(I);
2352   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2353
2354   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2355     // X + 0 --> X
2356     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2357       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2358                               (I.getType())->getValueAPF()))
2359         return ReplaceInstUsesWith(I, LHS);
2360     }
2361
2362     if (isa<PHINode>(LHS))
2363       if (Instruction *NV = FoldOpIntoPhi(I))
2364         return NV;
2365   }
2366
2367   // -A + B  -->  B - A
2368   // -A + -B  -->  -(A + B)
2369   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2370     return BinaryOperator::CreateFSub(RHS, LHSV);
2371
2372   // A + -B  -->  A - B
2373   if (!isa<Constant>(RHS))
2374     if (Value *V = dyn_castFNegVal(RHS, Context))
2375       return BinaryOperator::CreateFSub(LHS, V);
2376
2377   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2378   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2379     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2380       return ReplaceInstUsesWith(I, LHS);
2381
2382   // Check for (add double (sitofp x), y), see if we can merge this into an
2383   // integer add followed by a promotion.
2384   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2385     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2386     // ... if the constant fits in the integer value.  This is useful for things
2387     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2388     // requires a constant pool load, and generally allows the add to be better
2389     // instcombined.
2390     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2391       Constant *CI = 
2392       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2393       if (LHSConv->hasOneUse() &&
2394           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2395           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2396         // Insert the new integer add.
2397         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2398                                                         CI, "addconv");
2399         InsertNewInstBefore(NewAdd, I);
2400         return new SIToFPInst(NewAdd, I.getType());
2401       }
2402     }
2403     
2404     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2405     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2406       // Only do this if x/y have the same type, if at last one of them has a
2407       // single use (so we don't increase the number of int->fp conversions),
2408       // and if the integer add will not overflow.
2409       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2410           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2411           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2412                                    RHSConv->getOperand(0))) {
2413         // Insert the new integer add.
2414         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2415                                                         RHSConv->getOperand(0),
2416                                                         "addconv");
2417         InsertNewInstBefore(NewAdd, I);
2418         return new SIToFPInst(NewAdd, I.getType());
2419       }
2420     }
2421   }
2422   
2423   return Changed ? &I : 0;
2424 }
2425
2426 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2427   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2428
2429   if (Op0 == Op1)                        // sub X, X  -> 0
2430     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2431
2432   // If this is a 'B = x-(-A)', change to B = x+A...
2433   if (Value *V = dyn_castNegVal(Op1, Context))
2434     return BinaryOperator::CreateAdd(Op0, V);
2435
2436   if (isa<UndefValue>(Op0))
2437     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2438   if (isa<UndefValue>(Op1))
2439     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2440
2441   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2442     // Replace (-1 - A) with (~A)...
2443     if (C->isAllOnesValue())
2444       return BinaryOperator::CreateNot(*Context, Op1);
2445
2446     // C - ~X == X + (1+C)
2447     Value *X = 0;
2448     if (match(Op1, m_Not(m_Value(X)), *Context))
2449       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2450
2451     // -(X >>u 31) -> (X >>s 31)
2452     // -(X >>s 31) -> (X >>u 31)
2453     if (C->isZero()) {
2454       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2455         if (SI->getOpcode() == Instruction::LShr) {
2456           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2457             // Check to see if we are shifting out everything but the sign bit.
2458             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2459                 SI->getType()->getPrimitiveSizeInBits()-1) {
2460               // Ok, the transformation is safe.  Insert AShr.
2461               return BinaryOperator::Create(Instruction::AShr, 
2462                                           SI->getOperand(0), CU, SI->getName());
2463             }
2464           }
2465         }
2466         else if (SI->getOpcode() == Instruction::AShr) {
2467           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2468             // Check to see if we are shifting out everything but the sign bit.
2469             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2470                 SI->getType()->getPrimitiveSizeInBits()-1) {
2471               // Ok, the transformation is safe.  Insert LShr. 
2472               return BinaryOperator::CreateLShr(
2473                                           SI->getOperand(0), CU, SI->getName());
2474             }
2475           }
2476         }
2477       }
2478     }
2479
2480     // Try to fold constant sub into select arguments.
2481     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2482       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2483         return R;
2484
2485     // C - zext(bool) -> bool ? C - 1 : C
2486     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2487       if (ZI->getSrcTy() == Type::Int1Ty)
2488         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2489   }
2490
2491   if (I.getType() == Type::Int1Ty)
2492     return BinaryOperator::CreateXor(Op0, Op1);
2493
2494   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2495     if (Op1I->getOpcode() == Instruction::Add) {
2496       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2497         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2498                                          I.getName());
2499       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2500         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2501                                          I.getName());
2502       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2503         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2504           // C1-(X+C2) --> (C1-C2)-X
2505           return BinaryOperator::CreateSub(
2506             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2507       }
2508     }
2509
2510     if (Op1I->hasOneUse()) {
2511       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2512       // is not used by anyone else...
2513       //
2514       if (Op1I->getOpcode() == Instruction::Sub) {
2515         // Swap the two operands of the subexpr...
2516         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2517         Op1I->setOperand(0, IIOp1);
2518         Op1I->setOperand(1, IIOp0);
2519
2520         // Create the new top level add instruction...
2521         return BinaryOperator::CreateAdd(Op0, Op1);
2522       }
2523
2524       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2525       //
2526       if (Op1I->getOpcode() == Instruction::And &&
2527           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2528         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2529
2530         Value *NewNot =
2531           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2532                                                         OtherOp, "B.not"), I);
2533         return BinaryOperator::CreateAnd(Op0, NewNot);
2534       }
2535
2536       // 0 - (X sdiv C)  -> (X sdiv -C)
2537       if (Op1I->getOpcode() == Instruction::SDiv)
2538         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2539           if (CSI->isZero())
2540             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2541               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2542                                           Context->getConstantExprNeg(DivRHS));
2543
2544       // X - X*C --> X * (1-C)
2545       ConstantInt *C2 = 0;
2546       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2547         Constant *CP1 = 
2548           Context->getConstantExprSub(ConstantInt::get(I.getType(), 1),
2549                                              C2);
2550         return BinaryOperator::CreateMul(Op0, CP1);
2551       }
2552     }
2553   }
2554
2555   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2556     if (Op0I->getOpcode() == Instruction::Add) {
2557       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2558         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2559       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2560         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2561     } else if (Op0I->getOpcode() == Instruction::Sub) {
2562       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2563         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2564                                          I.getName());
2565     }
2566   }
2567
2568   ConstantInt *C1;
2569   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2570     if (X == Op1)  // X*C - X --> X * (C-1)
2571       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2572
2573     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2574     if (X == dyn_castFoldableMul(Op1, C2, Context))
2575       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2576   }
2577   return 0;
2578 }
2579
2580 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2581   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2582
2583   // If this is a 'B = x-(-A)', change to B = x+A...
2584   if (Value *V = dyn_castFNegVal(Op1, Context))
2585     return BinaryOperator::CreateFAdd(Op0, V);
2586
2587   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2588     if (Op1I->getOpcode() == Instruction::FAdd) {
2589       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2590         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2591                                           I.getName());
2592       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2593         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2594                                           I.getName());
2595     }
2596   }
2597
2598   return 0;
2599 }
2600
2601 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2602 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2603 /// TrueIfSigned if the result of the comparison is true when the input value is
2604 /// signed.
2605 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2606                            bool &TrueIfSigned) {
2607   switch (pred) {
2608   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2609     TrueIfSigned = true;
2610     return RHS->isZero();
2611   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2612     TrueIfSigned = true;
2613     return RHS->isAllOnesValue();
2614   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2615     TrueIfSigned = false;
2616     return RHS->isAllOnesValue();
2617   case ICmpInst::ICMP_UGT:
2618     // True if LHS u> RHS and RHS == high-bit-mask - 1
2619     TrueIfSigned = true;
2620     return RHS->getValue() ==
2621       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2622   case ICmpInst::ICMP_UGE: 
2623     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2624     TrueIfSigned = true;
2625     return RHS->getValue().isSignBit();
2626   default:
2627     return false;
2628   }
2629 }
2630
2631 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2632   bool Changed = SimplifyCommutative(I);
2633   Value *Op0 = I.getOperand(0);
2634
2635   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2636     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2637
2638   // Simplify mul instructions with a constant RHS...
2639   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2640     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2641
2642       // ((X << C1)*C2) == (X * (C2 << C1))
2643       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2644         if (SI->getOpcode() == Instruction::Shl)
2645           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2646             return BinaryOperator::CreateMul(SI->getOperand(0),
2647                                         Context->getConstantExprShl(CI, ShOp));
2648
2649       if (CI->isZero())
2650         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2651       if (CI->equalsInt(1))                  // X * 1  == X
2652         return ReplaceInstUsesWith(I, Op0);
2653       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2654         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2655
2656       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2657       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2658         return BinaryOperator::CreateShl(Op0,
2659                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2660       }
2661     } else if (isa<VectorType>(Op1->getType())) {
2662       if (Op1->isNullValue())
2663         return ReplaceInstUsesWith(I, Op1);
2664
2665       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2666         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2667           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2668
2669         // As above, vector X*splat(1.0) -> X in all defined cases.
2670         if (Constant *Splat = Op1V->getSplatValue()) {
2671           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2672             if (CI->equalsInt(1))
2673               return ReplaceInstUsesWith(I, Op0);
2674         }
2675       }
2676     }
2677     
2678     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2679       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2680           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2681         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2682         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2683                                                      Op1, "tmp");
2684         InsertNewInstBefore(Add, I);
2685         Value *C1C2 = Context->getConstantExprMul(Op1, 
2686                                            cast<Constant>(Op0I->getOperand(1)));
2687         return BinaryOperator::CreateAdd(Add, C1C2);
2688         
2689       }
2690
2691     // Try to fold constant mul into select arguments.
2692     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2693       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2694         return R;
2695
2696     if (isa<PHINode>(Op0))
2697       if (Instruction *NV = FoldOpIntoPhi(I))
2698         return NV;
2699   }
2700
2701   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2702     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2703       return BinaryOperator::CreateMul(Op0v, Op1v);
2704
2705   // (X / Y) *  Y = X - (X % Y)
2706   // (X / Y) * -Y = (X % Y) - X
2707   {
2708     Value *Op1 = I.getOperand(1);
2709     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2710     if (!BO ||
2711         (BO->getOpcode() != Instruction::UDiv && 
2712          BO->getOpcode() != Instruction::SDiv)) {
2713       Op1 = Op0;
2714       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2715     }
2716     Value *Neg = dyn_castNegVal(Op1, Context);
2717     if (BO && BO->hasOneUse() &&
2718         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2719         (BO->getOpcode() == Instruction::UDiv ||
2720          BO->getOpcode() == Instruction::SDiv)) {
2721       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2722
2723       Instruction *Rem;
2724       if (BO->getOpcode() == Instruction::UDiv)
2725         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2726       else
2727         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2728
2729       InsertNewInstBefore(Rem, I);
2730       Rem->takeName(BO);
2731
2732       if (Op1BO == Op1)
2733         return BinaryOperator::CreateSub(Op0BO, Rem);
2734       else
2735         return BinaryOperator::CreateSub(Rem, Op0BO);
2736     }
2737   }
2738
2739   if (I.getType() == Type::Int1Ty)
2740     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2741
2742   // If one of the operands of the multiply is a cast from a boolean value, then
2743   // we know the bool is either zero or one, so this is a 'masking' multiply.
2744   // See if we can simplify things based on how the boolean was originally
2745   // formed.
2746   CastInst *BoolCast = 0;
2747   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2748     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2749       BoolCast = CI;
2750   if (!BoolCast)
2751     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2752       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2753         BoolCast = CI;
2754   if (BoolCast) {
2755     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2756       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2757       const Type *SCOpTy = SCIOp0->getType();
2758       bool TIS = false;
2759       
2760       // If the icmp is true iff the sign bit of X is set, then convert this
2761       // multiply into a shift/and combination.
2762       if (isa<ConstantInt>(SCIOp1) &&
2763           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2764           TIS) {
2765         // Shift the X value right to turn it into "all signbits".
2766         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2767                                           SCOpTy->getPrimitiveSizeInBits()-1);
2768         Value *V =
2769           InsertNewInstBefore(
2770             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2771                                             BoolCast->getOperand(0)->getName()+
2772                                             ".mask"), I);
2773
2774         // If the multiply type is not the same as the source type, sign extend
2775         // or truncate to the multiply type.
2776         if (I.getType() != V->getType()) {
2777           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2778           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2779           Instruction::CastOps opcode = 
2780             (SrcBits == DstBits ? Instruction::BitCast : 
2781              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2782           V = InsertCastBefore(opcode, V, I.getType(), I);
2783         }
2784
2785         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2786         return BinaryOperator::CreateAnd(V, OtherOp);
2787       }
2788     }
2789   }
2790
2791   return Changed ? &I : 0;
2792 }
2793
2794 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2795   bool Changed = SimplifyCommutative(I);
2796   Value *Op0 = I.getOperand(0);
2797
2798   // Simplify mul instructions with a constant RHS...
2799   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2800     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2801       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2802       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2803       if (Op1F->isExactlyValue(1.0))
2804         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2805     } else if (isa<VectorType>(Op1->getType())) {
2806       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2807         // As above, vector X*splat(1.0) -> X in all defined cases.
2808         if (Constant *Splat = Op1V->getSplatValue()) {
2809           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2810             if (F->isExactlyValue(1.0))
2811               return ReplaceInstUsesWith(I, Op0);
2812         }
2813       }
2814     }
2815
2816     // Try to fold constant mul into select arguments.
2817     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2818       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2819         return R;
2820
2821     if (isa<PHINode>(Op0))
2822       if (Instruction *NV = FoldOpIntoPhi(I))
2823         return NV;
2824   }
2825
2826   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2827     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2828       return BinaryOperator::CreateFMul(Op0v, Op1v);
2829
2830   return Changed ? &I : 0;
2831 }
2832
2833 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2834 /// instruction.
2835 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2836   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2837   
2838   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2839   int NonNullOperand = -1;
2840   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2841     if (ST->isNullValue())
2842       NonNullOperand = 2;
2843   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2844   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2845     if (ST->isNullValue())
2846       NonNullOperand = 1;
2847   
2848   if (NonNullOperand == -1)
2849     return false;
2850   
2851   Value *SelectCond = SI->getOperand(0);
2852   
2853   // Change the div/rem to use 'Y' instead of the select.
2854   I.setOperand(1, SI->getOperand(NonNullOperand));
2855   
2856   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2857   // problem.  However, the select, or the condition of the select may have
2858   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2859   // propagate the known value for the select into other uses of it, and
2860   // propagate a known value of the condition into its other users.
2861   
2862   // If the select and condition only have a single use, don't bother with this,
2863   // early exit.
2864   if (SI->use_empty() && SelectCond->hasOneUse())
2865     return true;
2866   
2867   // Scan the current block backward, looking for other uses of SI.
2868   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2869   
2870   while (BBI != BBFront) {
2871     --BBI;
2872     // If we found a call to a function, we can't assume it will return, so
2873     // information from below it cannot be propagated above it.
2874     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2875       break;
2876     
2877     // Replace uses of the select or its condition with the known values.
2878     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2879          I != E; ++I) {
2880       if (*I == SI) {
2881         *I = SI->getOperand(NonNullOperand);
2882         AddToWorkList(BBI);
2883       } else if (*I == SelectCond) {
2884         *I = NonNullOperand == 1 ? Context->getTrue() :
2885                                    Context->getFalse();
2886         AddToWorkList(BBI);
2887       }
2888     }
2889     
2890     // If we past the instruction, quit looking for it.
2891     if (&*BBI == SI)
2892       SI = 0;
2893     if (&*BBI == SelectCond)
2894       SelectCond = 0;
2895     
2896     // If we ran out of things to eliminate, break out of the loop.
2897     if (SelectCond == 0 && SI == 0)
2898       break;
2899     
2900   }
2901   return true;
2902 }
2903
2904
2905 /// This function implements the transforms on div instructions that work
2906 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2907 /// used by the visitors to those instructions.
2908 /// @brief Transforms common to all three div instructions
2909 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2910   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2911
2912   // undef / X -> 0        for integer.
2913   // undef / X -> undef    for FP (the undef could be a snan).
2914   if (isa<UndefValue>(Op0)) {
2915     if (Op0->getType()->isFPOrFPVector())
2916       return ReplaceInstUsesWith(I, Op0);
2917     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2918   }
2919
2920   // X / undef -> undef
2921   if (isa<UndefValue>(Op1))
2922     return ReplaceInstUsesWith(I, Op1);
2923
2924   return 0;
2925 }
2926
2927 /// This function implements the transforms common to both integer division
2928 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2929 /// division instructions.
2930 /// @brief Common integer divide transforms
2931 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2932   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2933
2934   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2935   if (Op0 == Op1) {
2936     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2937       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2938       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2939       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2940     }
2941
2942     Constant *CI = ConstantInt::get(I.getType(), 1);
2943     return ReplaceInstUsesWith(I, CI);
2944   }
2945   
2946   if (Instruction *Common = commonDivTransforms(I))
2947     return Common;
2948   
2949   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2950   // This does not apply for fdiv.
2951   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2952     return &I;
2953
2954   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2955     // div X, 1 == X
2956     if (RHS->equalsInt(1))
2957       return ReplaceInstUsesWith(I, Op0);
2958
2959     // (X / C1) / C2  -> X / (C1*C2)
2960     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2961       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2962         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2963           if (MultiplyOverflows(RHS, LHSRHS,
2964                                 I.getOpcode()==Instruction::SDiv, Context))
2965             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2966           else 
2967             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2968                                       Context->getConstantExprMul(RHS, LHSRHS));
2969         }
2970
2971     if (!RHS->isZero()) { // avoid X udiv 0
2972       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2973         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2974           return R;
2975       if (isa<PHINode>(Op0))
2976         if (Instruction *NV = FoldOpIntoPhi(I))
2977           return NV;
2978     }
2979   }
2980
2981   // 0 / X == 0, we don't need to preserve faults!
2982   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2983     if (LHS->equalsInt(0))
2984       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2985
2986   // It can't be division by zero, hence it must be division by one.
2987   if (I.getType() == Type::Int1Ty)
2988     return ReplaceInstUsesWith(I, Op0);
2989
2990   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2991     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2992       // div X, 1 == X
2993       if (X->isOne())
2994         return ReplaceInstUsesWith(I, Op0);
2995   }
2996
2997   return 0;
2998 }
2999
3000 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3001   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3002
3003   // Handle the integer div common cases
3004   if (Instruction *Common = commonIDivTransforms(I))
3005     return Common;
3006
3007   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3008     // X udiv C^2 -> X >> C
3009     // Check to see if this is an unsigned division with an exact power of 2,
3010     // if so, convert to a right shift.
3011     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3012       return BinaryOperator::CreateLShr(Op0, 
3013             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3014
3015     // X udiv C, where C >= signbit
3016     if (C->getValue().isNegative()) {
3017       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3018                                                     ICmpInst::ICMP_ULT, Op0, C),
3019                                       I);
3020       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3021                                 ConstantInt::get(I.getType(), 1));
3022     }
3023   }
3024
3025   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3026   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3027     if (RHSI->getOpcode() == Instruction::Shl &&
3028         isa<ConstantInt>(RHSI->getOperand(0))) {
3029       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3030       if (C1.isPowerOf2()) {
3031         Value *N = RHSI->getOperand(1);
3032         const Type *NTy = N->getType();
3033         if (uint32_t C2 = C1.logBase2()) {
3034           Constant *C2V = ConstantInt::get(NTy, C2);
3035           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3036         }
3037         return BinaryOperator::CreateLShr(Op0, N);
3038       }
3039     }
3040   }
3041   
3042   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3043   // where C1&C2 are powers of two.
3044   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3045     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3046       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3047         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3048         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3049           // Compute the shift amounts
3050           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3051           // Construct the "on true" case of the select
3052           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3053           Instruction *TSI = BinaryOperator::CreateLShr(
3054                                                  Op0, TC, SI->getName()+".t");
3055           TSI = InsertNewInstBefore(TSI, I);
3056   
3057           // Construct the "on false" case of the select
3058           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3059           Instruction *FSI = BinaryOperator::CreateLShr(
3060                                                  Op0, FC, SI->getName()+".f");
3061           FSI = InsertNewInstBefore(FSI, I);
3062
3063           // construct the select instruction and return it.
3064           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3065         }
3066       }
3067   return 0;
3068 }
3069
3070 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3071   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3072
3073   // Handle the integer div common cases
3074   if (Instruction *Common = commonIDivTransforms(I))
3075     return Common;
3076
3077   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3078     // sdiv X, -1 == -X
3079     if (RHS->isAllOnesValue())
3080       return BinaryOperator::CreateNeg(*Context, Op0);
3081   }
3082
3083   // If the sign bits of both operands are zero (i.e. we can prove they are
3084   // unsigned inputs), turn this into a udiv.
3085   if (I.getType()->isInteger()) {
3086     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3087     if (MaskedValueIsZero(Op0, Mask)) {
3088       if (MaskedValueIsZero(Op1, Mask)) {
3089         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3090         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3091       }
3092       ConstantInt *ShiftedInt;
3093       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3094           ShiftedInt->getValue().isPowerOf2()) {
3095         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3096         // Safe because the only negative value (1 << Y) can take on is
3097         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3098         // the sign bit set.
3099         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3100       }
3101     }
3102   }
3103   
3104   return 0;
3105 }
3106
3107 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108   return commonDivTransforms(I);
3109 }
3110
3111 /// This function implements the transforms on rem instructions that work
3112 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3113 /// is used by the visitors to those instructions.
3114 /// @brief Transforms common to all three rem instructions
3115 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
3118   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3119     if (I.getType()->isFPOrFPVector())
3120       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3121     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3122   }
3123   if (isa<UndefValue>(Op1))
3124     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3125
3126   // Handle cases involving: rem X, (select Cond, Y, Z)
3127   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128     return &I;
3129
3130   return 0;
3131 }
3132
3133 /// This function implements the transforms common to both integer remainder
3134 /// instructions (urem and srem). It is called by the visitors to those integer
3135 /// remainder instructions.
3136 /// @brief Common integer remainder transforms
3137 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140   if (Instruction *common = commonRemTransforms(I))
3141     return common;
3142
3143   // 0 % X == 0 for integer, we don't need to preserve faults!
3144   if (Constant *LHS = dyn_cast<Constant>(Op0))
3145     if (LHS->isNullValue())
3146       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3147
3148   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3149     // X % 0 == undef, we don't need to preserve faults!
3150     if (RHS->equalsInt(0))
3151       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3152     
3153     if (RHS->equalsInt(1))  // X % 1 == 0
3154       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3155
3156     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159           return R;
3160       } else if (isa<PHINode>(Op0I)) {
3161         if (Instruction *NV = FoldOpIntoPhi(I))
3162           return NV;
3163       }
3164
3165       // See if we can fold away this rem instruction.
3166       if (SimplifyDemandedInstructionBits(I))
3167         return &I;
3168     }
3169   }
3170
3171   return 0;
3172 }
3173
3174 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177   if (Instruction *common = commonIRemTransforms(I))
3178     return common;
3179   
3180   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181     // X urem C^2 -> X and C
3182     // Check to see if this is an unsigned remainder with an exact power of 2,
3183     // if so, convert to a bitwise and.
3184     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3185       if (C->getValue().isPowerOf2())
3186         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3187   }
3188
3189   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3190     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3191     if (RHSI->getOpcode() == Instruction::Shl &&
3192         isa<ConstantInt>(RHSI->getOperand(0))) {
3193       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3194         Constant *N1 = Context->getAllOnesValue(I.getType());
3195         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3196                                                                    "tmp"), I);
3197         return BinaryOperator::CreateAnd(Op0, Add);
3198       }
3199     }
3200   }
3201
3202   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3203   // where C1&C2 are powers of two.
3204   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3205     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3206       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3207         // STO == 0 and SFO == 0 handled above.
3208         if ((STO->getValue().isPowerOf2()) && 
3209             (SFO->getValue().isPowerOf2())) {
3210           Value *TrueAnd = InsertNewInstBefore(
3211             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3212                                       SI->getName()+".t"), I);
3213           Value *FalseAnd = InsertNewInstBefore(
3214             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3215                                       SI->getName()+".f"), I);
3216           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3217         }
3218       }
3219   }
3220   
3221   return 0;
3222 }
3223
3224 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3225   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3226
3227   // Handle the integer rem common cases
3228   if (Instruction *common = commonIRemTransforms(I))
3229     return common;
3230   
3231   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3232     if (!isa<Constant>(RHSNeg) ||
3233         (isa<ConstantInt>(RHSNeg) &&
3234          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3235       // X % -Y -> X % Y
3236       AddUsesToWorkList(I);
3237       I.setOperand(1, RHSNeg);
3238       return &I;
3239     }
3240
3241   // If the sign bits of both operands are zero (i.e. we can prove they are
3242   // unsigned inputs), turn this into a urem.
3243   if (I.getType()->isInteger()) {
3244     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3245     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3246       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3247       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3248     }
3249   }
3250
3251   // If it's a constant vector, flip any negative values positive.
3252   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3253     unsigned VWidth = RHSV->getNumOperands();
3254
3255     bool hasNegative = false;
3256     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3257       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3258         if (RHS->getValue().isNegative())
3259           hasNegative = true;
3260
3261     if (hasNegative) {
3262       std::vector<Constant *> Elts(VWidth);
3263       for (unsigned i = 0; i != VWidth; ++i) {
3264         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3265           if (RHS->getValue().isNegative())
3266             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3267           else
3268             Elts[i] = RHS;
3269         }
3270       }
3271
3272       Constant *NewRHSV = Context->getConstantVector(Elts);
3273       if (NewRHSV != RHSV) {
3274         AddUsesToWorkList(I);
3275         I.setOperand(1, NewRHSV);
3276         return &I;
3277       }
3278     }
3279   }
3280
3281   return 0;
3282 }
3283
3284 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3285   return commonRemTransforms(I);
3286 }
3287
3288 // isOneBitSet - Return true if there is exactly one bit set in the specified
3289 // constant.
3290 static bool isOneBitSet(const ConstantInt *CI) {
3291   return CI->getValue().isPowerOf2();
3292 }
3293
3294 // isHighOnes - Return true if the constant is of the form 1+0+.
3295 // This is the same as lowones(~X).
3296 static bool isHighOnes(const ConstantInt *CI) {
3297   return (~CI->getValue() + 1).isPowerOf2();
3298 }
3299
3300 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3301 /// are carefully arranged to allow folding of expressions such as:
3302 ///
3303 ///      (A < B) | (A > B) --> (A != B)
3304 ///
3305 /// Note that this is only valid if the first and second predicates have the
3306 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3307 ///
3308 /// Three bits are used to represent the condition, as follows:
3309 ///   0  A > B
3310 ///   1  A == B
3311 ///   2  A < B
3312 ///
3313 /// <=>  Value  Definition
3314 /// 000     0   Always false
3315 /// 001     1   A >  B
3316 /// 010     2   A == B
3317 /// 011     3   A >= B
3318 /// 100     4   A <  B
3319 /// 101     5   A != B
3320 /// 110     6   A <= B
3321 /// 111     7   Always true
3322 ///  
3323 static unsigned getICmpCode(const ICmpInst *ICI) {
3324   switch (ICI->getPredicate()) {
3325     // False -> 0
3326   case ICmpInst::ICMP_UGT: return 1;  // 001
3327   case ICmpInst::ICMP_SGT: return 1;  // 001
3328   case ICmpInst::ICMP_EQ:  return 2;  // 010
3329   case ICmpInst::ICMP_UGE: return 3;  // 011
3330   case ICmpInst::ICMP_SGE: return 3;  // 011
3331   case ICmpInst::ICMP_ULT: return 4;  // 100
3332   case ICmpInst::ICMP_SLT: return 4;  // 100
3333   case ICmpInst::ICMP_NE:  return 5;  // 101
3334   case ICmpInst::ICMP_ULE: return 6;  // 110
3335   case ICmpInst::ICMP_SLE: return 6;  // 110
3336     // True -> 7
3337   default:
3338     llvm_unreachable("Invalid ICmp predicate!");
3339     return 0;
3340   }
3341 }
3342
3343 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3344 /// predicate into a three bit mask. It also returns whether it is an ordered
3345 /// predicate by reference.
3346 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3347   isOrdered = false;
3348   switch (CC) {
3349   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3350   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3351   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3352   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3353   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3354   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3355   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3356   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3357   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3358   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3359   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3360   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3361   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3362   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3363     // True -> 7
3364   default:
3365     // Not expecting FCMP_FALSE and FCMP_TRUE;
3366     llvm_unreachable("Unexpected FCmp predicate!");
3367     return 0;
3368   }
3369 }
3370
3371 /// getICmpValue - This is the complement of getICmpCode, which turns an
3372 /// opcode and two operands into either a constant true or false, or a brand 
3373 /// new ICmp instruction. The sign is passed in to determine which kind
3374 /// of predicate to use in the new icmp instruction.
3375 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3376                            LLVMContext *Context) {
3377   switch (code) {
3378   default: llvm_unreachable("Illegal ICmp code!");
3379   case  0: return Context->getFalse();
3380   case  1: 
3381     if (sign)
3382       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3383     else
3384       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3385   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3386   case  3: 
3387     if (sign)
3388       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3389     else
3390       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3391   case  4: 
3392     if (sign)
3393       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3394     else
3395       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3396   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3397   case  6: 
3398     if (sign)
3399       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3400     else
3401       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3402   case  7: return Context->getTrue();
3403   }
3404 }
3405
3406 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3407 /// opcode and two operands into either a FCmp instruction. isordered is passed
3408 /// in to determine which kind of predicate to use in the new fcmp instruction.
3409 static Value *getFCmpValue(bool isordered, unsigned code,
3410                            Value *LHS, Value *RHS, LLVMContext *Context) {
3411   switch (code) {
3412   default: llvm_unreachable("Illegal FCmp code!");
3413   case  0:
3414     if (isordered)
3415       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3416     else
3417       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3418   case  1: 
3419     if (isordered)
3420       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3421     else
3422       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3423   case  2: 
3424     if (isordered)
3425       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3426     else
3427       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3428   case  3: 
3429     if (isordered)
3430       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3431     else
3432       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3433   case  4: 
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3438   case  5: 
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3443   case  6: 
3444     if (isordered)
3445       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3446     else
3447       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3448   case  7: return Context->getTrue();
3449   }
3450 }
3451
3452 /// PredicatesFoldable - Return true if both predicates match sign or if at
3453 /// least one of them is an equality comparison (which is signless).
3454 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3455   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3456          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3457          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3458 }
3459
3460 namespace { 
3461 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3462 struct FoldICmpLogical {
3463   InstCombiner &IC;
3464   Value *LHS, *RHS;
3465   ICmpInst::Predicate pred;
3466   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3467     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3468       pred(ICI->getPredicate()) {}
3469   bool shouldApply(Value *V) const {
3470     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3471       if (PredicatesFoldable(pred, ICI->getPredicate()))
3472         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3473                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3474     return false;
3475   }
3476   Instruction *apply(Instruction &Log) const {
3477     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3478     if (ICI->getOperand(0) != LHS) {
3479       assert(ICI->getOperand(1) == LHS);
3480       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3481     }
3482
3483     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3484     unsigned LHSCode = getICmpCode(ICI);
3485     unsigned RHSCode = getICmpCode(RHSICI);
3486     unsigned Code;
3487     switch (Log.getOpcode()) {
3488     case Instruction::And: Code = LHSCode & RHSCode; break;
3489     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3490     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3491     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3492     }
3493
3494     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3495                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3496       
3497     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3498     if (Instruction *I = dyn_cast<Instruction>(RV))
3499       return I;
3500     // Otherwise, it's a constant boolean value...
3501     return IC.ReplaceInstUsesWith(Log, RV);
3502   }
3503 };
3504 } // end anonymous namespace
3505
3506 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3507 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3508 // guaranteed to be a binary operator.
3509 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3510                                     ConstantInt *OpRHS,
3511                                     ConstantInt *AndRHS,
3512                                     BinaryOperator &TheAnd) {
3513   Value *X = Op->getOperand(0);
3514   Constant *Together = 0;
3515   if (!Op->isShift())
3516     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3517
3518   switch (Op->getOpcode()) {
3519   case Instruction::Xor:
3520     if (Op->hasOneUse()) {
3521       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3522       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3523       InsertNewInstBefore(And, TheAnd);
3524       And->takeName(Op);
3525       return BinaryOperator::CreateXor(And, Together);
3526     }
3527     break;
3528   case Instruction::Or:
3529     if (Together == AndRHS) // (X | C) & C --> C
3530       return ReplaceInstUsesWith(TheAnd, AndRHS);
3531
3532     if (Op->hasOneUse() && Together != OpRHS) {
3533       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3534       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3535       InsertNewInstBefore(Or, TheAnd);
3536       Or->takeName(Op);
3537       return BinaryOperator::CreateAnd(Or, AndRHS);
3538     }
3539     break;
3540   case Instruction::Add:
3541     if (Op->hasOneUse()) {
3542       // Adding a one to a single bit bit-field should be turned into an XOR
3543       // of the bit.  First thing to check is to see if this AND is with a
3544       // single bit constant.
3545       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3546
3547       // If there is only one bit set...
3548       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3549         // Ok, at this point, we know that we are masking the result of the
3550         // ADD down to exactly one bit.  If the constant we are adding has
3551         // no bits set below this bit, then we can eliminate the ADD.
3552         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3553
3554         // Check to see if any bits below the one bit set in AndRHSV are set.
3555         if ((AddRHS & (AndRHSV-1)) == 0) {
3556           // If not, the only thing that can effect the output of the AND is
3557           // the bit specified by AndRHSV.  If that bit is set, the effect of
3558           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3559           // no effect.
3560           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3561             TheAnd.setOperand(0, X);
3562             return &TheAnd;
3563           } else {
3564             // Pull the XOR out of the AND.
3565             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3566             InsertNewInstBefore(NewAnd, TheAnd);
3567             NewAnd->takeName(Op);
3568             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3569           }
3570         }
3571       }
3572     }
3573     break;
3574
3575   case Instruction::Shl: {
3576     // We know that the AND will not produce any of the bits shifted in, so if
3577     // the anded constant includes them, clear them now!
3578     //
3579     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3580     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3581     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3582     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3583
3584     if (CI->getValue() == ShlMask) { 
3585     // Masking out bits that the shift already masks
3586       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3587     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3588       TheAnd.setOperand(1, CI);
3589       return &TheAnd;
3590     }
3591     break;
3592   }
3593   case Instruction::LShr:
3594   {
3595     // We know that the AND will not produce any of the bits shifted in, so if
3596     // the anded constant includes them, clear them now!  This only applies to
3597     // unsigned shifts, because a signed shr may bring in set bits!
3598     //
3599     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3602     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3603
3604     if (CI->getValue() == ShrMask) {   
3605     // Masking out bits that the shift already masks.
3606       return ReplaceInstUsesWith(TheAnd, Op);
3607     } else if (CI != AndRHS) {
3608       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3609       return &TheAnd;
3610     }
3611     break;
3612   }
3613   case Instruction::AShr:
3614     // Signed shr.
3615     // See if this is shifting in some sign extension, then masking it out
3616     // with an and.
3617     if (Op->hasOneUse()) {
3618       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3619       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3620       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3621       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3622       if (C == AndRHS) {          // Masking out bits shifted in.
3623         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3624         // Make the argument unsigned.
3625         Value *ShVal = Op->getOperand(0);
3626         ShVal = InsertNewInstBefore(
3627             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3628                                    Op->getName()), TheAnd);
3629         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3630       }
3631     }
3632     break;
3633   }
3634   return 0;
3635 }
3636
3637
3638 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3639 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3640 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3641 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3642 /// insert new instructions.
3643 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3644                                            bool isSigned, bool Inside, 
3645                                            Instruction &IB) {
3646   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3647             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3648          "Lo is not <= Hi in range emission code!");
3649     
3650   if (Inside) {
3651     if (Lo == Hi)  // Trivially false.
3652       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3653
3654     // V >= Min && V < Hi --> V < Hi
3655     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3656       ICmpInst::Predicate pred = (isSigned ? 
3657         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3658       return new ICmpInst(*Context, pred, V, Hi);
3659     }
3660
3661     // Emit V-Lo <u Hi-Lo
3662     Constant *NegLo = Context->getConstantExprNeg(Lo);
3663     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3664     InsertNewInstBefore(Add, IB);
3665     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3666     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3667   }
3668
3669   if (Lo == Hi)  // Trivially true.
3670     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3671
3672   // V < Min || V >= Hi -> V > Hi-1
3673   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3674   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3675     ICmpInst::Predicate pred = (isSigned ? 
3676         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3677     return new ICmpInst(*Context, pred, V, Hi);
3678   }
3679
3680   // Emit V-Lo >u Hi-1-Lo
3681   // Note that Hi has already had one subtracted from it, above.
3682   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3683   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3684   InsertNewInstBefore(Add, IB);
3685   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3686   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3687 }
3688
3689 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3690 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3691 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3692 // not, since all 1s are not contiguous.
3693 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3694   const APInt& V = Val->getValue();
3695   uint32_t BitWidth = Val->getType()->getBitWidth();
3696   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3697
3698   // look for the first zero bit after the run of ones
3699   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3700   // look for the first non-zero bit
3701   ME = V.getActiveBits(); 
3702   return true;
3703 }
3704
3705 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3706 /// where isSub determines whether the operator is a sub.  If we can fold one of
3707 /// the following xforms:
3708 /// 
3709 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3710 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3711 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3712 ///
3713 /// return (A +/- B).
3714 ///
3715 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3716                                         ConstantInt *Mask, bool isSub,
3717                                         Instruction &I) {
3718   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3719   if (!LHSI || LHSI->getNumOperands() != 2 ||
3720       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3721
3722   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3723
3724   switch (LHSI->getOpcode()) {
3725   default: return 0;
3726   case Instruction::And:
3727     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3728       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3729       if ((Mask->getValue().countLeadingZeros() + 
3730            Mask->getValue().countPopulation()) == 
3731           Mask->getValue().getBitWidth())
3732         break;
3733
3734       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3735       // part, we don't need any explicit masks to take them out of A.  If that
3736       // is all N is, ignore it.
3737       uint32_t MB = 0, ME = 0;
3738       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3739         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3740         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3741         if (MaskedValueIsZero(RHS, Mask))
3742           break;
3743       }
3744     }
3745     return 0;
3746   case Instruction::Or:
3747   case Instruction::Xor:
3748     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3749     if ((Mask->getValue().countLeadingZeros() + 
3750          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3751         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3752       break;
3753     return 0;
3754   }
3755   
3756   Instruction *New;
3757   if (isSub)
3758     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3759   else
3760     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3761   return InsertNewInstBefore(New, I);
3762 }
3763
3764 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3765 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3766                                           ICmpInst *LHS, ICmpInst *RHS) {
3767   Value *Val, *Val2;
3768   ConstantInt *LHSCst, *RHSCst;
3769   ICmpInst::Predicate LHSCC, RHSCC;
3770   
3771   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3772   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3773                          m_ConstantInt(LHSCst)), *Context) ||
3774       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3775                          m_ConstantInt(RHSCst)), *Context))
3776     return 0;
3777   
3778   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3779   // where C is a power of 2
3780   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3781       LHSCst->getValue().isPowerOf2()) {
3782     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3783     InsertNewInstBefore(NewOr, I);
3784     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3785   }
3786   
3787   // From here on, we only handle:
3788   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3789   if (Val != Val2) return 0;
3790   
3791   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3792   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3793       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3794       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3795       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3796     return 0;
3797   
3798   // We can't fold (ugt x, C) & (sgt x, C2).
3799   if (!PredicatesFoldable(LHSCC, RHSCC))
3800     return 0;
3801     
3802   // Ensure that the larger constant is on the RHS.
3803   bool ShouldSwap;
3804   if (ICmpInst::isSignedPredicate(LHSCC) ||
3805       (ICmpInst::isEquality(LHSCC) && 
3806        ICmpInst::isSignedPredicate(RHSCC)))
3807     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3808   else
3809     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3810     
3811   if (ShouldSwap) {
3812     std::swap(LHS, RHS);
3813     std::swap(LHSCst, RHSCst);
3814     std::swap(LHSCC, RHSCC);
3815   }
3816
3817   // At this point, we know we have have two icmp instructions
3818   // comparing a value against two constants and and'ing the result
3819   // together.  Because of the above check, we know that we only have
3820   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3821   // (from the FoldICmpLogical check above), that the two constants 
3822   // are not equal and that the larger constant is on the RHS
3823   assert(LHSCst != RHSCst && "Compares not folded above?");
3824
3825   switch (LHSCC) {
3826   default: llvm_unreachable("Unknown integer condition code!");
3827   case ICmpInst::ICMP_EQ:
3828     switch (RHSCC) {
3829     default: llvm_unreachable("Unknown integer condition code!");
3830     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3831     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3832     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3833       return ReplaceInstUsesWith(I, Context->getFalse());
3834     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3835     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3836     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3837       return ReplaceInstUsesWith(I, LHS);
3838     }
3839   case ICmpInst::ICMP_NE:
3840     switch (RHSCC) {
3841     default: llvm_unreachable("Unknown integer condition code!");
3842     case ICmpInst::ICMP_ULT:
3843       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3844         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3845       break;                        // (X != 13 & X u< 15) -> no change
3846     case ICmpInst::ICMP_SLT:
3847       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3848         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3849       break;                        // (X != 13 & X s< 15) -> no change
3850     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3851     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3852     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3853       return ReplaceInstUsesWith(I, RHS);
3854     case ICmpInst::ICMP_NE:
3855       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3856         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3857         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3858                                                      Val->getName()+".off");
3859         InsertNewInstBefore(Add, I);
3860         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3861                             ConstantInt::get(Add->getType(), 1));
3862       }
3863       break;                        // (X != 13 & X != 15) -> no change
3864     }
3865     break;
3866   case ICmpInst::ICMP_ULT:
3867     switch (RHSCC) {
3868     default: llvm_unreachable("Unknown integer condition code!");
3869     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3870     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3871       return ReplaceInstUsesWith(I, Context->getFalse());
3872     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3873       break;
3874     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3875     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3876       return ReplaceInstUsesWith(I, LHS);
3877     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3878       break;
3879     }
3880     break;
3881   case ICmpInst::ICMP_SLT:
3882     switch (RHSCC) {
3883     default: llvm_unreachable("Unknown integer condition code!");
3884     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3885     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3886       return ReplaceInstUsesWith(I, Context->getFalse());
3887     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3888       break;
3889     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3890     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3891       return ReplaceInstUsesWith(I, LHS);
3892     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3893       break;
3894     }
3895     break;
3896   case ICmpInst::ICMP_UGT:
3897     switch (RHSCC) {
3898     default: llvm_unreachable("Unknown integer condition code!");
3899     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3900     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3901       return ReplaceInstUsesWith(I, RHS);
3902     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3903       break;
3904     case ICmpInst::ICMP_NE:
3905       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3906         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3907       break;                        // (X u> 13 & X != 15) -> no change
3908     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3909       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3910                              RHSCst, false, true, I);
3911     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3912       break;
3913     }
3914     break;
3915   case ICmpInst::ICMP_SGT:
3916     switch (RHSCC) {
3917     default: llvm_unreachable("Unknown integer condition code!");
3918     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3919     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3920       return ReplaceInstUsesWith(I, RHS);
3921     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3922       break;
3923     case ICmpInst::ICMP_NE:
3924       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3925         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3926       break;                        // (X s> 13 & X != 15) -> no change
3927     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3928       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3929                              RHSCst, true, true, I);
3930     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3931       break;
3932     }
3933     break;
3934   }
3935  
3936   return 0;
3937 }
3938
3939 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3940                                           FCmpInst *RHS) {
3941   
3942   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3943       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3944     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3945     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3946       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3947         // If either of the constants are nans, then the whole thing returns
3948         // false.
3949         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3950           return ReplaceInstUsesWith(I, Context->getFalse());
3951         return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3952                             LHS->getOperand(0), RHS->getOperand(0));
3953       }
3954     
3955     // Handle vector zeros.  This occurs because the canonical form of
3956     // "fcmp ord x,x" is "fcmp ord x, 0".
3957     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3958         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3959       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3960                           LHS->getOperand(0), RHS->getOperand(0));
3961     return 0;
3962   }
3963   
3964   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3965   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3966   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3967   
3968   
3969   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3970     // Swap RHS operands to match LHS.
3971     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3972     std::swap(Op1LHS, Op1RHS);
3973   }
3974   
3975   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3976     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3977     if (Op0CC == Op1CC)
3978       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3979     
3980     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3981       return ReplaceInstUsesWith(I, Context->getFalse());
3982     if (Op0CC == FCmpInst::FCMP_TRUE)
3983       return ReplaceInstUsesWith(I, RHS);
3984     if (Op1CC == FCmpInst::FCMP_TRUE)
3985       return ReplaceInstUsesWith(I, LHS);
3986     
3987     bool Op0Ordered;
3988     bool Op1Ordered;
3989     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3990     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3991     if (Op1Pred == 0) {
3992       std::swap(LHS, RHS);
3993       std::swap(Op0Pred, Op1Pred);
3994       std::swap(Op0Ordered, Op1Ordered);
3995     }
3996     if (Op0Pred == 0) {
3997       // uno && ueq -> uno && (uno || eq) -> ueq
3998       // ord && olt -> ord && (ord && lt) -> olt
3999       if (Op0Ordered == Op1Ordered)
4000         return ReplaceInstUsesWith(I, RHS);
4001       
4002       // uno && oeq -> uno && (ord && eq) -> false
4003       // uno && ord -> false
4004       if (!Op0Ordered)
4005         return ReplaceInstUsesWith(I, Context->getFalse());
4006       // ord && ueq -> ord && (uno || eq) -> oeq
4007       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4008                                             Op0LHS, Op0RHS, Context));
4009     }
4010   }
4011
4012   return 0;
4013 }
4014
4015
4016 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4017   bool Changed = SimplifyCommutative(I);
4018   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4019
4020   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4021     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4022
4023   // and X, X = X
4024   if (Op0 == Op1)
4025     return ReplaceInstUsesWith(I, Op1);
4026
4027   // See if we can simplify any instructions used by the instruction whose sole 
4028   // purpose is to compute bits we don't care about.
4029   if (SimplifyDemandedInstructionBits(I))
4030     return &I;
4031   if (isa<VectorType>(I.getType())) {
4032     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4033       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4034         return ReplaceInstUsesWith(I, I.getOperand(0));
4035     } else if (isa<ConstantAggregateZero>(Op1)) {
4036       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4037     }
4038   }
4039
4040   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4041     const APInt& AndRHSMask = AndRHS->getValue();
4042     APInt NotAndRHS(~AndRHSMask);
4043
4044     // Optimize a variety of ((val OP C1) & C2) combinations...
4045     if (isa<BinaryOperator>(Op0)) {
4046       Instruction *Op0I = cast<Instruction>(Op0);
4047       Value *Op0LHS = Op0I->getOperand(0);
4048       Value *Op0RHS = Op0I->getOperand(1);
4049       switch (Op0I->getOpcode()) {
4050       case Instruction::Xor:
4051       case Instruction::Or:
4052         // If the mask is only needed on one incoming arm, push it up.
4053         if (Op0I->hasOneUse()) {
4054           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4055             // Not masking anything out for the LHS, move to RHS.
4056             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4057                                                    Op0RHS->getName()+".masked");
4058             InsertNewInstBefore(NewRHS, I);
4059             return BinaryOperator::Create(
4060                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4061           }
4062           if (!isa<Constant>(Op0RHS) &&
4063               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4064             // Not masking anything out for the RHS, move to LHS.
4065             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4066                                                    Op0LHS->getName()+".masked");
4067             InsertNewInstBefore(NewLHS, I);
4068             return BinaryOperator::Create(
4069                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4070           }
4071         }
4072
4073         break;
4074       case Instruction::Add:
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, false, I))
4079           return BinaryOperator::CreateAnd(V, AndRHS);
4080         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4081           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4082         break;
4083
4084       case Instruction::Sub:
4085         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4086         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4087         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4088         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4089           return BinaryOperator::CreateAnd(V, AndRHS);
4090
4091         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4092         // has 1's for all bits that the subtraction with A might affect.
4093         if (Op0I->hasOneUse()) {
4094           uint32_t BitWidth = AndRHSMask.getBitWidth();
4095           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4096           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4097
4098           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4099           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4100               MaskedValueIsZero(Op0LHS, Mask)) {
4101             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4102             InsertNewInstBefore(NewNeg, I);
4103             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4104           }
4105         }
4106         break;
4107
4108       case Instruction::Shl:
4109       case Instruction::LShr:
4110         // (1 << x) & 1 --> zext(x == 0)
4111         // (1 >> x) & 1 --> zext(x == 0)
4112         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4113           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4114                                     Op0RHS, Context->getNullValue(I.getType()));
4115           InsertNewInstBefore(NewICmp, I);
4116           return new ZExtInst(NewICmp, I.getType());
4117         }
4118         break;
4119       }
4120
4121       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4122         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4123           return Res;
4124     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4125       // If this is an integer truncation or change from signed-to-unsigned, and
4126       // if the source is an and/or with immediate, transform it.  This
4127       // frequently occurs for bitfield accesses.
4128       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4129         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4130             CastOp->getNumOperands() == 2)
4131           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4132             if (CastOp->getOpcode() == Instruction::And) {
4133               // Change: and (cast (and X, C1) to T), C2
4134               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4135               // This will fold the two constants together, which may allow 
4136               // other simplifications.
4137               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4138                 CastOp->getOperand(0), I.getType(), 
4139                 CastOp->getName()+".shrunk");
4140               NewCast = InsertNewInstBefore(NewCast, I);
4141               // trunc_or_bitcast(C1)&C2
4142               Constant *C3 =
4143                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4144               C3 = Context->getConstantExprAnd(C3, AndRHS);
4145               return BinaryOperator::CreateAnd(NewCast, C3);
4146             } else if (CastOp->getOpcode() == Instruction::Or) {
4147               // Change: and (cast (or X, C1) to T), C2
4148               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4149               Constant *C3 =
4150                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4151               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4152                 // trunc(C1)&C2
4153                 return ReplaceInstUsesWith(I, AndRHS);
4154             }
4155           }
4156       }
4157     }
4158
4159     // Try to fold constant and into select arguments.
4160     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4161       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4162         return R;
4163     if (isa<PHINode>(Op0))
4164       if (Instruction *NV = FoldOpIntoPhi(I))
4165         return NV;
4166   }
4167
4168   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4169   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4170
4171   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4172     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4173
4174   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4175   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4176     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4177                                                I.getName()+".demorgan");
4178     InsertNewInstBefore(Or, I);
4179     return BinaryOperator::CreateNot(*Context, Or);
4180   }
4181   
4182   {
4183     Value *A = 0, *B = 0, *C = 0, *D = 0;
4184     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4185       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4186         return ReplaceInstUsesWith(I, Op1);
4187     
4188       // (A|B) & ~(A&B) -> A^B
4189       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4190         if ((A == C && B == D) || (A == D && B == C))
4191           return BinaryOperator::CreateXor(A, B);
4192       }
4193     }
4194     
4195     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4196       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4197         return ReplaceInstUsesWith(I, Op0);
4198
4199       // ~(A&B) & (A|B) -> A^B
4200       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4201         if ((A == C && B == D) || (A == D && B == C))
4202           return BinaryOperator::CreateXor(A, B);
4203       }
4204     }
4205     
4206     if (Op0->hasOneUse() &&
4207         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4208       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4209         I.swapOperands();     // Simplify below
4210         std::swap(Op0, Op1);
4211       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4212         cast<BinaryOperator>(Op0)->swapOperands();
4213         I.swapOperands();     // Simplify below
4214         std::swap(Op0, Op1);
4215       }
4216     }
4217
4218     if (Op1->hasOneUse() &&
4219         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4220       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4221         cast<BinaryOperator>(Op1)->swapOperands();
4222         std::swap(A, B);
4223       }
4224       if (A == Op0) {                                // A&(A^B) -> A & ~B
4225         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4226         InsertNewInstBefore(NotB, I);
4227         return BinaryOperator::CreateAnd(A, NotB);
4228       }
4229     }
4230
4231     // (A&((~A)|B)) -> A&B
4232     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4233         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4234       return BinaryOperator::CreateAnd(A, Op1);
4235     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4236         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4237       return BinaryOperator::CreateAnd(A, Op0);
4238   }
4239   
4240   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4241     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4242     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4243       return R;
4244
4245     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4246       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4247         return Res;
4248   }
4249
4250   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4251   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4252     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4253       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4254         const Type *SrcTy = Op0C->getOperand(0)->getType();
4255         if (SrcTy == Op1C->getOperand(0)->getType() &&
4256             SrcTy->isIntOrIntVector() &&
4257             // Only do this if the casts both really cause code to be generated.
4258             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4259                               I.getType(), TD) &&
4260             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4261                               I.getType(), TD)) {
4262           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4263                                                          Op1C->getOperand(0),
4264                                                          I.getName());
4265           InsertNewInstBefore(NewOp, I);
4266           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4267         }
4268       }
4269     
4270   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4271   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4272     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4273       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4274           SI0->getOperand(1) == SI1->getOperand(1) &&
4275           (SI0->hasOneUse() || SI1->hasOneUse())) {
4276         Instruction *NewOp =
4277           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4278                                                         SI1->getOperand(0),
4279                                                         SI0->getName()), I);
4280         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4281                                       SI1->getOperand(1));
4282       }
4283   }
4284
4285   // If and'ing two fcmp, try combine them into one.
4286   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4287     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4288       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4289         return Res;
4290   }
4291
4292   return Changed ? &I : 0;
4293 }
4294
4295 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4296 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4297 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4298 /// the expression came from the corresponding "byte swapped" byte in some other
4299 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4300 /// we know that the expression deposits the low byte of %X into the high byte
4301 /// of the bswap result and that all other bytes are zero.  This expression is
4302 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4303 /// match.
4304 ///
4305 /// This function returns true if the match was unsuccessful and false if so.
4306 /// On entry to the function the "OverallLeftShift" is a signed integer value
4307 /// indicating the number of bytes that the subexpression is later shifted.  For
4308 /// example, if the expression is later right shifted by 16 bits, the
4309 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4310 /// byte of ByteValues is actually being set.
4311 ///
4312 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4313 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4314 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4315 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4316 /// always in the local (OverallLeftShift) coordinate space.
4317 ///
4318 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4319                               SmallVector<Value*, 8> &ByteValues) {
4320   if (Instruction *I = dyn_cast<Instruction>(V)) {
4321     // If this is an or instruction, it may be an inner node of the bswap.
4322     if (I->getOpcode() == Instruction::Or) {
4323       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4324                                ByteValues) ||
4325              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4326                                ByteValues);
4327     }
4328   
4329     // If this is a logical shift by a constant multiple of 8, recurse with
4330     // OverallLeftShift and ByteMask adjusted.
4331     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4332       unsigned ShAmt = 
4333         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4334       // Ensure the shift amount is defined and of a byte value.
4335       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4336         return true;
4337
4338       unsigned ByteShift = ShAmt >> 3;
4339       if (I->getOpcode() == Instruction::Shl) {
4340         // X << 2 -> collect(X, +2)
4341         OverallLeftShift += ByteShift;
4342         ByteMask >>= ByteShift;
4343       } else {
4344         // X >>u 2 -> collect(X, -2)
4345         OverallLeftShift -= ByteShift;
4346         ByteMask <<= ByteShift;
4347         ByteMask &= (~0U >> (32-ByteValues.size()));
4348       }
4349
4350       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4351       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4352
4353       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4354                                ByteValues);
4355     }
4356
4357     // If this is a logical 'and' with a mask that clears bytes, clear the
4358     // corresponding bytes in ByteMask.
4359     if (I->getOpcode() == Instruction::And &&
4360         isa<ConstantInt>(I->getOperand(1))) {
4361       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4362       unsigned NumBytes = ByteValues.size();
4363       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4364       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4365       
4366       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4367         // If this byte is masked out by a later operation, we don't care what
4368         // the and mask is.
4369         if ((ByteMask & (1 << i)) == 0)
4370           continue;
4371         
4372         // If the AndMask is all zeros for this byte, clear the bit.
4373         APInt MaskB = AndMask & Byte;
4374         if (MaskB == 0) {
4375           ByteMask &= ~(1U << i);
4376           continue;
4377         }
4378         
4379         // If the AndMask is not all ones for this byte, it's not a bytezap.
4380         if (MaskB != Byte)
4381           return true;
4382
4383         // Otherwise, this byte is kept.
4384       }
4385
4386       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4387                                ByteValues);
4388     }
4389   }
4390   
4391   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4392   // the input value to the bswap.  Some observations: 1) if more than one byte
4393   // is demanded from this input, then it could not be successfully assembled
4394   // into a byteswap.  At least one of the two bytes would not be aligned with
4395   // their ultimate destination.
4396   if (!isPowerOf2_32(ByteMask)) return true;
4397   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4398   
4399   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4400   // is demanded, it needs to go into byte 0 of the result.  This means that the
4401   // byte needs to be shifted until it lands in the right byte bucket.  The
4402   // shift amount depends on the position: if the byte is coming from the high
4403   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4404   // low part, it must be shifted left.
4405   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4406   if (InputByteNo < ByteValues.size()/2) {
4407     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4408       return true;
4409   } else {
4410     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411       return true;
4412   }
4413   
4414   // If the destination byte value is already defined, the values are or'd
4415   // together, which isn't a bswap (unless it's an or of the same bits).
4416   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4417     return true;
4418   ByteValues[DestByteNo] = V;
4419   return false;
4420 }
4421
4422 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4423 /// If so, insert the new bswap intrinsic and return it.
4424 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4425   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4426   if (!ITy || ITy->getBitWidth() % 16 || 
4427       // ByteMask only allows up to 32-byte values.
4428       ITy->getBitWidth() > 32*8) 
4429     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4430   
4431   /// ByteValues - For each byte of the result, we keep track of which value
4432   /// defines each byte.
4433   SmallVector<Value*, 8> ByteValues;
4434   ByteValues.resize(ITy->getBitWidth()/8);
4435     
4436   // Try to find all the pieces corresponding to the bswap.
4437   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4438   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4439     return 0;
4440   
4441   // Check to see if all of the bytes come from the same value.
4442   Value *V = ByteValues[0];
4443   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4444   
4445   // Check to make sure that all of the bytes come from the same value.
4446   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4447     if (ByteValues[i] != V)
4448       return 0;
4449   const Type *Tys[] = { ITy };
4450   Module *M = I.getParent()->getParent()->getParent();
4451   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4452   return CallInst::Create(F, V);
4453 }
4454
4455 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4456 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4457 /// we can simplify this expression to "cond ? C : D or B".
4458 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4459                                          Value *C, Value *D,
4460                                          LLVMContext *Context) {
4461   // If A is not a select of -1/0, this cannot match.
4462   Value *Cond = 0;
4463   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4464     return 0;
4465
4466   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4467   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4468     return SelectInst::Create(Cond, C, B);
4469   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4470     return SelectInst::Create(Cond, C, B);
4471   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4472   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4473     return SelectInst::Create(Cond, C, D);
4474   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4475     return SelectInst::Create(Cond, C, D);
4476   return 0;
4477 }
4478
4479 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4480 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4481                                          ICmpInst *LHS, ICmpInst *RHS) {
4482   Value *Val, *Val2;
4483   ConstantInt *LHSCst, *RHSCst;
4484   ICmpInst::Predicate LHSCC, RHSCC;
4485   
4486   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4487   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4488              m_ConstantInt(LHSCst)), *Context) ||
4489       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4490              m_ConstantInt(RHSCst)), *Context))
4491     return 0;
4492   
4493   // From here on, we only handle:
4494   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4495   if (Val != Val2) return 0;
4496   
4497   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4498   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4499       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4500       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4501       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4502     return 0;
4503   
4504   // We can't fold (ugt x, C) | (sgt x, C2).
4505   if (!PredicatesFoldable(LHSCC, RHSCC))
4506     return 0;
4507   
4508   // Ensure that the larger constant is on the RHS.
4509   bool ShouldSwap;
4510   if (ICmpInst::isSignedPredicate(LHSCC) ||
4511       (ICmpInst::isEquality(LHSCC) && 
4512        ICmpInst::isSignedPredicate(RHSCC)))
4513     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4514   else
4515     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4516   
4517   if (ShouldSwap) {
4518     std::swap(LHS, RHS);
4519     std::swap(LHSCst, RHSCst);
4520     std::swap(LHSCC, RHSCC);
4521   }
4522   
4523   // At this point, we know we have have two icmp instructions
4524   // comparing a value against two constants and or'ing the result
4525   // together.  Because of the above check, we know that we only have
4526   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4527   // FoldICmpLogical check above), that the two constants are not
4528   // equal.
4529   assert(LHSCst != RHSCst && "Compares not folded above?");
4530
4531   switch (LHSCC) {
4532   default: llvm_unreachable("Unknown integer condition code!");
4533   case ICmpInst::ICMP_EQ:
4534     switch (RHSCC) {
4535     default: llvm_unreachable("Unknown integer condition code!");
4536     case ICmpInst::ICMP_EQ:
4537       if (LHSCst == SubOne(RHSCst, Context)) {
4538         // (X == 13 | X == 14) -> X-13 <u 2
4539         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4540         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4541                                                      Val->getName()+".off");
4542         InsertNewInstBefore(Add, I);
4543         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4544         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4545       }
4546       break;                         // (X == 13 | X == 15) -> no change
4547     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4548     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4549       break;
4550     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4551     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4552     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4553       return ReplaceInstUsesWith(I, RHS);
4554     }
4555     break;
4556   case ICmpInst::ICMP_NE:
4557     switch (RHSCC) {
4558     default: llvm_unreachable("Unknown integer condition code!");
4559     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4560     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4561     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4562       return ReplaceInstUsesWith(I, LHS);
4563     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4564     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4565     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4566       return ReplaceInstUsesWith(I, Context->getTrue());
4567     }
4568     break;
4569   case ICmpInst::ICMP_ULT:
4570     switch (RHSCC) {
4571     default: llvm_unreachable("Unknown integer condition code!");
4572     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4573       break;
4574     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4575       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4576       // this can cause overflow.
4577       if (RHSCst->isMaxValue(false))
4578         return ReplaceInstUsesWith(I, LHS);
4579       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4580                              false, false, I);
4581     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4582       break;
4583     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4584     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4585       return ReplaceInstUsesWith(I, RHS);
4586     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4587       break;
4588     }
4589     break;
4590   case ICmpInst::ICMP_SLT:
4591     switch (RHSCC) {
4592     default: llvm_unreachable("Unknown integer condition code!");
4593     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4594       break;
4595     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4596       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4597       // this can cause overflow.
4598       if (RHSCst->isMaxValue(true))
4599         return ReplaceInstUsesWith(I, LHS);
4600       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4601                              true, false, I);
4602     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4603       break;
4604     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4605     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4606       return ReplaceInstUsesWith(I, RHS);
4607     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4608       break;
4609     }
4610     break;
4611   case ICmpInst::ICMP_UGT:
4612     switch (RHSCC) {
4613     default: llvm_unreachable("Unknown integer condition code!");
4614     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4615     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4616       return ReplaceInstUsesWith(I, LHS);
4617     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4618       break;
4619     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4620     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4621       return ReplaceInstUsesWith(I, Context->getTrue());
4622     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4623       break;
4624     }
4625     break;
4626   case ICmpInst::ICMP_SGT:
4627     switch (RHSCC) {
4628     default: llvm_unreachable("Unknown integer condition code!");
4629     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4630     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4631       return ReplaceInstUsesWith(I, LHS);
4632     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4633       break;
4634     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4635     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4636       return ReplaceInstUsesWith(I, Context->getTrue());
4637     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4638       break;
4639     }
4640     break;
4641   }
4642   return 0;
4643 }
4644
4645 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4646                                          FCmpInst *RHS) {
4647   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4648       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4649       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4650     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4651       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4652         // If either of the constants are nans, then the whole thing returns
4653         // true.
4654         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4655           return ReplaceInstUsesWith(I, Context->getTrue());
4656         
4657         // Otherwise, no need to compare the two constants, compare the
4658         // rest.
4659         return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4660                             LHS->getOperand(0), RHS->getOperand(0));
4661       }
4662     
4663     // Handle vector zeros.  This occurs because the canonical form of
4664     // "fcmp uno x,x" is "fcmp uno x, 0".
4665     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4666         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4667       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4668                           LHS->getOperand(0), RHS->getOperand(0));
4669     
4670     return 0;
4671   }
4672   
4673   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4674   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4675   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4676   
4677   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4678     // Swap RHS operands to match LHS.
4679     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4680     std::swap(Op1LHS, Op1RHS);
4681   }
4682   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4683     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4684     if (Op0CC == Op1CC)
4685       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4686                           Op0LHS, Op0RHS);
4687     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4688       return ReplaceInstUsesWith(I, Context->getTrue());
4689     if (Op0CC == FCmpInst::FCMP_FALSE)
4690       return ReplaceInstUsesWith(I, RHS);
4691     if (Op1CC == FCmpInst::FCMP_FALSE)
4692       return ReplaceInstUsesWith(I, LHS);
4693     bool Op0Ordered;
4694     bool Op1Ordered;
4695     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4696     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4697     if (Op0Ordered == Op1Ordered) {
4698       // If both are ordered or unordered, return a new fcmp with
4699       // or'ed predicates.
4700       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4701                                Op0LHS, Op0RHS, Context);
4702       if (Instruction *I = dyn_cast<Instruction>(RV))
4703         return I;
4704       // Otherwise, it's a constant boolean value...
4705       return ReplaceInstUsesWith(I, RV);
4706     }
4707   }
4708   return 0;
4709 }
4710
4711 /// FoldOrWithConstants - This helper function folds:
4712 ///
4713 ///     ((A | B) & C1) | (B & C2)
4714 ///
4715 /// into:
4716 /// 
4717 ///     (A & C1) | B
4718 ///
4719 /// when the XOR of the two constants is "all ones" (-1).
4720 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4721                                                Value *A, Value *B, Value *C) {
4722   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4723   if (!CI1) return 0;
4724
4725   Value *V1 = 0;
4726   ConstantInt *CI2 = 0;
4727   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4728
4729   APInt Xor = CI1->getValue() ^ CI2->getValue();
4730   if (!Xor.isAllOnesValue()) return 0;
4731
4732   if (V1 == A || V1 == B) {
4733     Instruction *NewOp =
4734       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4735     return BinaryOperator::CreateOr(NewOp, V1);
4736   }
4737
4738   return 0;
4739 }
4740
4741 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4742   bool Changed = SimplifyCommutative(I);
4743   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4744
4745   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4746     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4747
4748   // or X, X = X
4749   if (Op0 == Op1)
4750     return ReplaceInstUsesWith(I, Op0);
4751
4752   // See if we can simplify any instructions used by the instruction whose sole 
4753   // purpose is to compute bits we don't care about.
4754   if (SimplifyDemandedInstructionBits(I))
4755     return &I;
4756   if (isa<VectorType>(I.getType())) {
4757     if (isa<ConstantAggregateZero>(Op1)) {
4758       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4759     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4760       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4761         return ReplaceInstUsesWith(I, I.getOperand(1));
4762     }
4763   }
4764
4765   // or X, -1 == -1
4766   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4767     ConstantInt *C1 = 0; Value *X = 0;
4768     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4769     if (match(Op0, m_And(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::CreateAnd(Or, 
4775                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4776     }
4777
4778     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4779     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4780         isOnlyUse(Op0)) {
4781       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4782       InsertNewInstBefore(Or, I);
4783       Or->takeName(Op0);
4784       return BinaryOperator::CreateXor(Or,
4785                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4786     }
4787
4788     // Try to fold constant and into select arguments.
4789     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4790       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4791         return R;
4792     if (isa<PHINode>(Op0))
4793       if (Instruction *NV = FoldOpIntoPhi(I))
4794         return NV;
4795   }
4796
4797   Value *A = 0, *B = 0;
4798   ConstantInt *C1 = 0, *C2 = 0;
4799
4800   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4801     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4802       return ReplaceInstUsesWith(I, Op1);
4803   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4804     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4805       return ReplaceInstUsesWith(I, Op0);
4806
4807   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4808   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4809   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4810       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4811       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4812        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4813     if (Instruction *BSwap = MatchBSwap(I))
4814       return BSwap;
4815   }
4816   
4817   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4818   if (Op0->hasOneUse() &&
4819       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4820       MaskedValueIsZero(Op1, C1->getValue())) {
4821     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4822     InsertNewInstBefore(NOr, I);
4823     NOr->takeName(Op0);
4824     return BinaryOperator::CreateXor(NOr, C1);
4825   }
4826
4827   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4828   if (Op1->hasOneUse() &&
4829       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4830       MaskedValueIsZero(Op0, C1->getValue())) {
4831     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4832     InsertNewInstBefore(NOr, I);
4833     NOr->takeName(Op0);
4834     return BinaryOperator::CreateXor(NOr, C1);
4835   }
4836
4837   // (A & C)|(B & D)
4838   Value *C = 0, *D = 0;
4839   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4840       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4841     Value *V1 = 0, *V2 = 0, *V3 = 0;
4842     C1 = dyn_cast<ConstantInt>(C);
4843     C2 = dyn_cast<ConstantInt>(D);
4844     if (C1 && C2) {  // (A & C1)|(B & C2)
4845       // If we have: ((V + N) & C1) | (V & C2)
4846       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4847       // replace with V+N.
4848       if (C1->getValue() == ~C2->getValue()) {
4849         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4850             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4851           // Add commutes, try both ways.
4852           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4853             return ReplaceInstUsesWith(I, A);
4854           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4855             return ReplaceInstUsesWith(I, A);
4856         }
4857         // Or commutes, try both ways.
4858         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4859             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4860           // Add commutes, try both ways.
4861           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4862             return ReplaceInstUsesWith(I, B);
4863           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4864             return ReplaceInstUsesWith(I, B);
4865         }
4866       }
4867       V1 = 0; V2 = 0; V3 = 0;
4868     }
4869     
4870     // Check to see if we have any common things being and'ed.  If so, find the
4871     // terms for V1 & (V2|V3).
4872     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4873       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4874         V1 = A, V2 = C, V3 = D;
4875       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4876         V1 = A, V2 = B, V3 = C;
4877       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4878         V1 = C, V2 = A, V3 = D;
4879       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4880         V1 = C, V2 = A, V3 = B;
4881       
4882       if (V1) {
4883         Value *Or =
4884           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4885         return BinaryOperator::CreateAnd(V1, Or);
4886       }
4887     }
4888
4889     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4890     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4891       return Match;
4892     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4893       return Match;
4894     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4895       return Match;
4896     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4897       return Match;
4898
4899     // ((A&~B)|(~A&B)) -> A^B
4900     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4901          match(B, m_Not(m_Specific(A)), *Context)))
4902       return BinaryOperator::CreateXor(A, D);
4903     // ((~B&A)|(~A&B)) -> A^B
4904     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4905          match(B, m_Not(m_Specific(C)), *Context)))
4906       return BinaryOperator::CreateXor(C, D);
4907     // ((A&~B)|(B&~A)) -> A^B
4908     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4909          match(D, m_Not(m_Specific(A)), *Context)))
4910       return BinaryOperator::CreateXor(A, B);
4911     // ((~B&A)|(B&~A)) -> A^B
4912     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4913          match(D, m_Not(m_Specific(C)), *Context)))
4914       return BinaryOperator::CreateXor(C, B);
4915   }
4916   
4917   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4918   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4919     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4920       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4921           SI0->getOperand(1) == SI1->getOperand(1) &&
4922           (SI0->hasOneUse() || SI1->hasOneUse())) {
4923         Instruction *NewOp =
4924         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4925                                                      SI1->getOperand(0),
4926                                                      SI0->getName()), I);
4927         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4928                                       SI1->getOperand(1));
4929       }
4930   }
4931
4932   // ((A|B)&1)|(B&-2) -> (A&1) | B
4933   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4934       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4935     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4936     if (Ret) return Ret;
4937   }
4938   // (B&-2)|((A|B)&1) -> (A&1) | B
4939   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4940       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4941     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4942     if (Ret) return Ret;
4943   }
4944
4945   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4946     if (A == Op1)   // ~A | A == -1
4947       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4948   } else {
4949     A = 0;
4950   }
4951   // Note, A is still live here!
4952   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4953     if (Op0 == B)
4954       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4955
4956     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4957     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4958       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4959                                               I.getName()+".demorgan"), I);
4960       return BinaryOperator::CreateNot(*Context, And);
4961     }
4962   }
4963
4964   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4965   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4966     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4967       return R;
4968
4969     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4970       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4971         return Res;
4972   }
4973     
4974   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4975   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4976     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4977       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4978         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4979             !isa<ICmpInst>(Op1C->getOperand(0))) {
4980           const Type *SrcTy = Op0C->getOperand(0)->getType();
4981           if (SrcTy == Op1C->getOperand(0)->getType() &&
4982               SrcTy->isIntOrIntVector() &&
4983               // Only do this if the casts both really cause code to be
4984               // generated.
4985               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4986                                 I.getType(), TD) &&
4987               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4988                                 I.getType(), TD)) {
4989             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4990                                                           Op1C->getOperand(0),
4991                                                           I.getName());
4992             InsertNewInstBefore(NewOp, I);
4993             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4994           }
4995         }
4996       }
4997   }
4998   
4999     
5000   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5001   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5002     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5003       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5004         return Res;
5005   }
5006
5007   return Changed ? &I : 0;
5008 }
5009
5010 namespace {
5011
5012 // XorSelf - Implements: X ^ X --> 0
5013 struct XorSelf {
5014   Value *RHS;
5015   XorSelf(Value *rhs) : RHS(rhs) {}
5016   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5017   Instruction *apply(BinaryOperator &Xor) const {
5018     return &Xor;
5019   }
5020 };
5021
5022 }
5023
5024 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5025   bool Changed = SimplifyCommutative(I);
5026   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5027
5028   if (isa<UndefValue>(Op1)) {
5029     if (isa<UndefValue>(Op0))
5030       // Handle undef ^ undef -> 0 special case. This is a common
5031       // idiom (misuse).
5032       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5033     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5034   }
5035
5036   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5037   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5038     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5039     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5040   }
5041   
5042   // See if we can simplify any instructions used by the instruction whose sole 
5043   // purpose is to compute bits we don't care about.
5044   if (SimplifyDemandedInstructionBits(I))
5045     return &I;
5046   if (isa<VectorType>(I.getType()))
5047     if (isa<ConstantAggregateZero>(Op1))
5048       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5049
5050   // Is this a ~ operation?
5051   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5052     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5053     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5054     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5055       if (Op0I->getOpcode() == Instruction::And || 
5056           Op0I->getOpcode() == Instruction::Or) {
5057         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5058         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5059           Instruction *NotY =
5060             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5061                                       Op0I->getOperand(1)->getName()+".not");
5062           InsertNewInstBefore(NotY, I);
5063           if (Op0I->getOpcode() == Instruction::And)
5064             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5065           else
5066             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5067         }
5068       }
5069     }
5070   }
5071   
5072   
5073   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5074     if (RHS == Context->getTrue() && Op0->hasOneUse()) {
5075       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5076       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5077         return new ICmpInst(*Context, ICI->getInversePredicate(),
5078                             ICI->getOperand(0), ICI->getOperand(1));
5079
5080       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5081         return new FCmpInst(*Context, FCI->getInversePredicate(),
5082                             FCI->getOperand(0), FCI->getOperand(1));
5083     }
5084
5085     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5086     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5087       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5088         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5089           Instruction::CastOps Opcode = Op0C->getOpcode();
5090           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5091             if (RHS == Context->getConstantExprCast(Opcode, 
5092                                              Context->getTrue(),
5093                                              Op0C->getDestTy())) {
5094               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5095                                      *Context,
5096                                      CI->getOpcode(), CI->getInversePredicate(),
5097                                      CI->getOperand(0), CI->getOperand(1)), I);
5098               NewCI->takeName(CI);
5099               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5100             }
5101           }
5102         }
5103       }
5104     }
5105
5106     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5107       // ~(c-X) == X-c-1 == X+(-c-1)
5108       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5109         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5110           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5111           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5112                                       ConstantInt::get(I.getType(), 1));
5113           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5114         }
5115           
5116       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5117         if (Op0I->getOpcode() == Instruction::Add) {
5118           // ~(X-c) --> (-c-1)-X
5119           if (RHS->isAllOnesValue()) {
5120             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5121             return BinaryOperator::CreateSub(
5122                            Context->getConstantExprSub(NegOp0CI,
5123                                       ConstantInt::get(I.getType(), 1)),
5124                                       Op0I->getOperand(0));
5125           } else if (RHS->getValue().isSignBit()) {
5126             // (X + C) ^ signbit -> (X + C + signbit)
5127             Constant *C = ConstantInt::get(*Context,
5128                                            RHS->getValue() + Op0CI->getValue());
5129             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5130
5131           }
5132         } else if (Op0I->getOpcode() == Instruction::Or) {
5133           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5134           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5135             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5136             // Anything in both C1 and C2 is known to be zero, remove it from
5137             // NewRHS.
5138             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5139             NewRHS = Context->getConstantExprAnd(NewRHS, 
5140                                        Context->getConstantExprNot(CommonBits));
5141             AddToWorkList(Op0I);
5142             I.setOperand(0, Op0I->getOperand(0));
5143             I.setOperand(1, NewRHS);
5144             return &I;
5145           }
5146         }
5147       }
5148     }
5149
5150     // Try to fold constant and into select arguments.
5151     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5152       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5153         return R;
5154     if (isa<PHINode>(Op0))
5155       if (Instruction *NV = FoldOpIntoPhi(I))
5156         return NV;
5157   }
5158
5159   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5160     if (X == Op1)
5161       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5162
5163   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5164     if (X == Op0)
5165       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5166
5167   
5168   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5169   if (Op1I) {
5170     Value *A, *B;
5171     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5172       if (A == Op0) {              // B^(B|A) == (A|B)^B
5173         Op1I->swapOperands();
5174         I.swapOperands();
5175         std::swap(Op0, Op1);
5176       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5177         I.swapOperands();     // Simplified below.
5178         std::swap(Op0, Op1);
5179       }
5180     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5181       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5182     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5183       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5184     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5185                Op1I->hasOneUse()){
5186       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5187         Op1I->swapOperands();
5188         std::swap(A, B);
5189       }
5190       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5191         I.swapOperands();     // Simplified below.
5192         std::swap(Op0, Op1);
5193       }
5194     }
5195   }
5196   
5197   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5198   if (Op0I) {
5199     Value *A, *B;
5200     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5201         Op0I->hasOneUse()) {
5202       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5203         std::swap(A, B);
5204       if (B == Op1) {                                // (A|B)^B == A & ~B
5205         Instruction *NotB =
5206           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5207                                                         Op1, "tmp"), I);
5208         return BinaryOperator::CreateAnd(A, NotB);
5209       }
5210     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5211       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5212     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5213       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5214     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5215                Op0I->hasOneUse()){
5216       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5217         std::swap(A, B);
5218       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5219           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5220         Instruction *N =
5221           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5222         return BinaryOperator::CreateAnd(N, Op1);
5223       }
5224     }
5225   }
5226   
5227   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5228   if (Op0I && Op1I && Op0I->isShift() && 
5229       Op0I->getOpcode() == Op1I->getOpcode() && 
5230       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5231       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5232     Instruction *NewOp =
5233       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5234                                                     Op1I->getOperand(0),
5235                                                     Op0I->getName()), I);
5236     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5237                                   Op1I->getOperand(1));
5238   }
5239     
5240   if (Op0I && Op1I) {
5241     Value *A, *B, *C, *D;
5242     // (A & B)^(A | B) -> A ^ B
5243     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5245       if ((A == C && B == D) || (A == D && B == C)) 
5246         return BinaryOperator::CreateXor(A, B);
5247     }
5248     // (A | B)^(A & B) -> A ^ B
5249     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5250         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5251       if ((A == C && B == D) || (A == D && B == C)) 
5252         return BinaryOperator::CreateXor(A, B);
5253     }
5254     
5255     // (A & B)^(C & D)
5256     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5257         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5258         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5259       // (X & Y)^(X & Y) -> (Y^Z) & X
5260       Value *X = 0, *Y = 0, *Z = 0;
5261       if (A == C)
5262         X = A, Y = B, Z = D;
5263       else if (A == D)
5264         X = A, Y = B, Z = C;
5265       else if (B == C)
5266         X = B, Y = A, Z = D;
5267       else if (B == D)
5268         X = B, Y = A, Z = C;
5269       
5270       if (X) {
5271         Instruction *NewOp =
5272         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5273         return BinaryOperator::CreateAnd(NewOp, X);
5274       }
5275     }
5276   }
5277     
5278   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5280     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5281       return R;
5282
5283   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5284   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5285     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5286       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287         const Type *SrcTy = Op0C->getOperand(0)->getType();
5288         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5289             // Only do this if the casts both really cause code to be generated.
5290             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5291                               I.getType(), TD) &&
5292             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5293                               I.getType(), TD)) {
5294           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5295                                                          Op1C->getOperand(0),
5296                                                          I.getName());
5297           InsertNewInstBefore(NewOp, I);
5298           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5299         }
5300       }
5301   }
5302
5303   return Changed ? &I : 0;
5304 }
5305
5306 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5307                                    LLVMContext *Context) {
5308   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5309 }
5310
5311 static bool HasAddOverflow(ConstantInt *Result,
5312                            ConstantInt *In1, ConstantInt *In2,
5313                            bool IsSigned) {
5314   if (IsSigned)
5315     if (In2->getValue().isNegative())
5316       return Result->getValue().sgt(In1->getValue());
5317     else
5318       return Result->getValue().slt(In1->getValue());
5319   else
5320     return Result->getValue().ult(In1->getValue());
5321 }
5322
5323 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5324 /// overflowed for this type.
5325 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5326                             Constant *In2, LLVMContext *Context,
5327                             bool IsSigned = false) {
5328   Result = Context->getConstantExprAdd(In1, In2);
5329
5330   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5331     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5332       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5333       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5334                          ExtractElement(In1, Idx, Context),
5335                          ExtractElement(In2, Idx, Context),
5336                          IsSigned))
5337         return true;
5338     }
5339     return false;
5340   }
5341
5342   return HasAddOverflow(cast<ConstantInt>(Result),
5343                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5344                         IsSigned);
5345 }
5346
5347 static bool HasSubOverflow(ConstantInt *Result,
5348                            ConstantInt *In1, ConstantInt *In2,
5349                            bool IsSigned) {
5350   if (IsSigned)
5351     if (In2->getValue().isNegative())
5352       return Result->getValue().slt(In1->getValue());
5353     else
5354       return Result->getValue().sgt(In1->getValue());
5355   else
5356     return Result->getValue().ugt(In1->getValue());
5357 }
5358
5359 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5360 /// overflowed for this type.
5361 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5362                             Constant *In2, LLVMContext *Context,
5363                             bool IsSigned = false) {
5364   Result = Context->getConstantExprSub(In1, In2);
5365
5366   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5368       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5369       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5370                          ExtractElement(In1, Idx, Context),
5371                          ExtractElement(In2, Idx, Context),
5372                          IsSigned))
5373         return true;
5374     }
5375     return false;
5376   }
5377
5378   return HasSubOverflow(cast<ConstantInt>(Result),
5379                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380                         IsSigned);
5381 }
5382
5383 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5384 /// code necessary to compute the offset from the base pointer (without adding
5385 /// in the base pointer).  Return the result as a signed integer of intptr size.
5386 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5387   TargetData &TD = *IC.getTargetData();
5388   gep_type_iterator GTI = gep_type_begin(GEP);
5389   const Type *IntPtrTy = TD.getIntPtrType();
5390   LLVMContext *Context = IC.getContext();
5391   Value *Result = Context->getNullValue(IntPtrTy);
5392
5393   // Build a mask for high order bits.
5394   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5395   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5396
5397   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5398        ++i, ++GTI) {
5399     Value *Op = *i;
5400     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5401     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5402       if (OpC->isZero()) continue;
5403       
5404       // Handle a struct index, which adds its field offset to the pointer.
5405       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5407         
5408         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5409           Result = 
5410              ConstantInt::get(*Context, 
5411                               RC->getValue() + APInt(IntPtrWidth, Size));
5412         else
5413           Result = IC.InsertNewInstBefore(
5414                    BinaryOperator::CreateAdd(Result,
5415                                         ConstantInt::get(IntPtrTy, Size),
5416                                              GEP->getName()+".offs"), I);
5417         continue;
5418       }
5419       
5420       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5421       Constant *OC =
5422               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5423       Scale = Context->getConstantExprMul(OC, Scale);
5424       if (Constant *RC = dyn_cast<Constant>(Result))
5425         Result = Context->getConstantExprAdd(RC, Scale);
5426       else {
5427         // Emit an add instruction.
5428         Result = IC.InsertNewInstBefore(
5429            BinaryOperator::CreateAdd(Result, Scale,
5430                                      GEP->getName()+".offs"), I);
5431       }
5432       continue;
5433     }
5434     // Convert to correct type.
5435     if (Op->getType() != IntPtrTy) {
5436       if (Constant *OpC = dyn_cast<Constant>(Op))
5437         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5438       else
5439         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5440                                                                 true,
5441                                                       Op->getName()+".c"), I);
5442     }
5443     if (Size != 1) {
5444       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5445       if (Constant *OpC = dyn_cast<Constant>(Op))
5446         Op = Context->getConstantExprMul(OpC, Scale);
5447       else    // We'll let instcombine(mul) convert this to a shl if possible.
5448         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5449                                                   GEP->getName()+".idx"), I);
5450     }
5451
5452     // Emit an add instruction.
5453     if (isa<Constant>(Op) && isa<Constant>(Result))
5454       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5455                                     cast<Constant>(Result));
5456     else
5457       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5458                                                   GEP->getName()+".offs"), I);
5459   }
5460   return Result;
5461 }
5462
5463
5464 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5465 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5466 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5467 /// be complex, and scales are involved.  The above expression would also be
5468 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5469 /// This later form is less amenable to optimization though, and we are allowed
5470 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5471 ///
5472 /// If we can't emit an optimized form for this expression, this returns null.
5473 /// 
5474 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5475                                           InstCombiner &IC) {
5476   TargetData &TD = *IC.getTargetData();
5477   gep_type_iterator GTI = gep_type_begin(GEP);
5478
5479   // Check to see if this gep only has a single variable index.  If so, and if
5480   // any constant indices are a multiple of its scale, then we can compute this
5481   // in terms of the scale of the variable index.  For example, if the GEP
5482   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5483   // because the expression will cross zero at the same point.
5484   unsigned i, e = GEP->getNumOperands();
5485   int64_t Offset = 0;
5486   for (i = 1; i != e; ++i, ++GTI) {
5487     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5488       // Compute the aggregate offset of constant indices.
5489       if (CI->isZero()) continue;
5490
5491       // Handle a struct index, which adds its field offset to the pointer.
5492       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5493         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5494       } else {
5495         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5496         Offset += Size*CI->getSExtValue();
5497       }
5498     } else {
5499       // Found our variable index.
5500       break;
5501     }
5502   }
5503   
5504   // If there are no variable indices, we must have a constant offset, just
5505   // evaluate it the general way.
5506   if (i == e) return 0;
5507   
5508   Value *VariableIdx = GEP->getOperand(i);
5509   // Determine the scale factor of the variable element.  For example, this is
5510   // 4 if the variable index is into an array of i32.
5511   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5512   
5513   // Verify that there are no other variable indices.  If so, emit the hard way.
5514   for (++i, ++GTI; i != e; ++i, ++GTI) {
5515     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5516     if (!CI) return 0;
5517    
5518     // Compute the aggregate offset of constant indices.
5519     if (CI->isZero()) continue;
5520     
5521     // Handle a struct index, which adds its field offset to the pointer.
5522     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5523       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5524     } else {
5525       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5526       Offset += Size*CI->getSExtValue();
5527     }
5528   }
5529   
5530   // Okay, we know we have a single variable index, which must be a
5531   // pointer/array/vector index.  If there is no offset, life is simple, return
5532   // the index.
5533   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5534   if (Offset == 0) {
5535     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5536     // we don't need to bother extending: the extension won't affect where the
5537     // computation crosses zero.
5538     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5539       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5540                                   VariableIdx->getNameStart(), &I);
5541     return VariableIdx;
5542   }
5543   
5544   // Otherwise, there is an index.  The computation we will do will be modulo
5545   // the pointer size, so get it.
5546   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5547   
5548   Offset &= PtrSizeMask;
5549   VariableScale &= PtrSizeMask;
5550
5551   // To do this transformation, any constant index must be a multiple of the
5552   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5553   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5554   // multiple of the variable scale.
5555   int64_t NewOffs = Offset / (int64_t)VariableScale;
5556   if (Offset != NewOffs*(int64_t)VariableScale)
5557     return 0;
5558
5559   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5560   const Type *IntPtrTy = TD.getIntPtrType();
5561   if (VariableIdx->getType() != IntPtrTy)
5562     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5563                                               true /*SExt*/, 
5564                                               VariableIdx->getNameStart(), &I);
5565   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5566   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5567 }
5568
5569
5570 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5571 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5572 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5573                                        ICmpInst::Predicate Cond,
5574                                        Instruction &I) {
5575   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5576
5577   // Look through bitcasts.
5578   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5579     RHS = BCI->getOperand(0);
5580
5581   Value *PtrBase = GEPLHS->getOperand(0);
5582   if (TD && PtrBase == RHS) {
5583     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5584     // This transformation (ignoring the base and scales) is valid because we
5585     // know pointers can't overflow.  See if we can output an optimized form.
5586     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5587     
5588     // If not, synthesize the offset the hard way.
5589     if (Offset == 0)
5590       Offset = EmitGEPOffset(GEPLHS, I, *this);
5591     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5592                         Context->getNullValue(Offset->getType()));
5593   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5594     // If the base pointers are different, but the indices are the same, just
5595     // compare the base pointer.
5596     if (PtrBase != GEPRHS->getOperand(0)) {
5597       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5598       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5599                         GEPRHS->getOperand(0)->getType();
5600       if (IndicesTheSame)
5601         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5602           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5603             IndicesTheSame = false;
5604             break;
5605           }
5606
5607       // If all indices are the same, just compare the base pointers.
5608       if (IndicesTheSame)
5609         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5610                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5611
5612       // Otherwise, the base pointers are different and the indices are
5613       // different, bail out.
5614       return 0;
5615     }
5616
5617     // If one of the GEPs has all zero indices, recurse.
5618     bool AllZeros = true;
5619     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5620       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5621           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5622         AllZeros = false;
5623         break;
5624       }
5625     if (AllZeros)
5626       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5627                           ICmpInst::getSwappedPredicate(Cond), I);
5628
5629     // If the other GEP has all zero indices, recurse.
5630     AllZeros = true;
5631     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5632       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5633           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5634         AllZeros = false;
5635         break;
5636       }
5637     if (AllZeros)
5638       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5639
5640     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5641       // If the GEPs only differ by one index, compare it.
5642       unsigned NumDifferences = 0;  // Keep track of # differences.
5643       unsigned DiffOperand = 0;     // The operand that differs.
5644       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5645         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5646           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5647                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5648             // Irreconcilable differences.
5649             NumDifferences = 2;
5650             break;
5651           } else {
5652             if (NumDifferences++) break;
5653             DiffOperand = i;
5654           }
5655         }
5656
5657       if (NumDifferences == 0)   // SAME GEP?
5658         return ReplaceInstUsesWith(I, // No comparison is needed here.
5659                                    ConstantInt::get(Type::Int1Ty,
5660                                              ICmpInst::isTrueWhenEqual(Cond)));
5661
5662       else if (NumDifferences == 1) {
5663         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5664         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5665         // Make sure we do a signed comparison here.
5666         return new ICmpInst(*Context,
5667                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5668       }
5669     }
5670
5671     // Only lower this if the icmp is the only user of the GEP or if we expect
5672     // the result to fold to a constant!
5673     if (TD &&
5674         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5675         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5676       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5677       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5678       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5679       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5680     }
5681   }
5682   return 0;
5683 }
5684
5685 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5686 ///
5687 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5688                                                 Instruction *LHSI,
5689                                                 Constant *RHSC) {
5690   if (!isa<ConstantFP>(RHSC)) return 0;
5691   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5692   
5693   // Get the width of the mantissa.  We don't want to hack on conversions that
5694   // might lose information from the integer, e.g. "i64 -> float"
5695   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5696   if (MantissaWidth == -1) return 0;  // Unknown.
5697   
5698   // Check to see that the input is converted from an integer type that is small
5699   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5700   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5701   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5702   
5703   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5704   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5705   if (LHSUnsigned)
5706     ++InputSize;
5707   
5708   // If the conversion would lose info, don't hack on this.
5709   if ((int)InputSize > MantissaWidth)
5710     return 0;
5711   
5712   // Otherwise, we can potentially simplify the comparison.  We know that it
5713   // will always come through as an integer value and we know the constant is
5714   // not a NAN (it would have been previously simplified).
5715   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5716   
5717   ICmpInst::Predicate Pred;
5718   switch (I.getPredicate()) {
5719   default: llvm_unreachable("Unexpected predicate!");
5720   case FCmpInst::FCMP_UEQ:
5721   case FCmpInst::FCMP_OEQ:
5722     Pred = ICmpInst::ICMP_EQ;
5723     break;
5724   case FCmpInst::FCMP_UGT:
5725   case FCmpInst::FCMP_OGT:
5726     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5727     break;
5728   case FCmpInst::FCMP_UGE:
5729   case FCmpInst::FCMP_OGE:
5730     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5731     break;
5732   case FCmpInst::FCMP_ULT:
5733   case FCmpInst::FCMP_OLT:
5734     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5735     break;
5736   case FCmpInst::FCMP_ULE:
5737   case FCmpInst::FCMP_OLE:
5738     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5739     break;
5740   case FCmpInst::FCMP_UNE:
5741   case FCmpInst::FCMP_ONE:
5742     Pred = ICmpInst::ICMP_NE;
5743     break;
5744   case FCmpInst::FCMP_ORD:
5745     return ReplaceInstUsesWith(I, Context->getTrue());
5746   case FCmpInst::FCMP_UNO:
5747     return ReplaceInstUsesWith(I, Context->getFalse());
5748   }
5749   
5750   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5751   
5752   // Now we know that the APFloat is a normal number, zero or inf.
5753   
5754   // See if the FP constant is too large for the integer.  For example,
5755   // comparing an i8 to 300.0.
5756   unsigned IntWidth = IntTy->getScalarSizeInBits();
5757   
5758   if (!LHSUnsigned) {
5759     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5760     // and large values.
5761     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5762     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5763                           APFloat::rmNearestTiesToEven);
5764     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5765       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5766           Pred == ICmpInst::ICMP_SLE)
5767         return ReplaceInstUsesWith(I, Context->getTrue());
5768       return ReplaceInstUsesWith(I, Context->getFalse());
5769     }
5770   } else {
5771     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5772     // +INF and large values.
5773     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5774     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5775                           APFloat::rmNearestTiesToEven);
5776     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5777       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5778           Pred == ICmpInst::ICMP_ULE)
5779         return ReplaceInstUsesWith(I, Context->getTrue());
5780       return ReplaceInstUsesWith(I, Context->getFalse());
5781     }
5782   }
5783   
5784   if (!LHSUnsigned) {
5785     // See if the RHS value is < SignedMin.
5786     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5787     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5788                           APFloat::rmNearestTiesToEven);
5789     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5790       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5791           Pred == ICmpInst::ICMP_SGE)
5792         return ReplaceInstUsesWith(I, Context->getTrue());
5793       return ReplaceInstUsesWith(I, Context->getFalse());
5794     }
5795   }
5796
5797   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5798   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5799   // casting the FP value to the integer value and back, checking for equality.
5800   // Don't do this for zero, because -0.0 is not fractional.
5801   Constant *RHSInt = LHSUnsigned
5802     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5803     : Context->getConstantExprFPToSI(RHSC, IntTy);
5804   if (!RHS.isZero()) {
5805     bool Equal = LHSUnsigned
5806       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5807       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5808     if (!Equal) {
5809       // If we had a comparison against a fractional value, we have to adjust
5810       // the compare predicate and sometimes the value.  RHSC is rounded towards
5811       // zero at this point.
5812       switch (Pred) {
5813       default: llvm_unreachable("Unexpected integer comparison!");
5814       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5815         return ReplaceInstUsesWith(I, Context->getTrue());
5816       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5817         return ReplaceInstUsesWith(I, Context->getFalse());
5818       case ICmpInst::ICMP_ULE:
5819         // (float)int <= 4.4   --> int <= 4
5820         // (float)int <= -4.4  --> false
5821         if (RHS.isNegative())
5822           return ReplaceInstUsesWith(I, Context->getFalse());
5823         break;
5824       case ICmpInst::ICMP_SLE:
5825         // (float)int <= 4.4   --> int <= 4
5826         // (float)int <= -4.4  --> int < -4
5827         if (RHS.isNegative())
5828           Pred = ICmpInst::ICMP_SLT;
5829         break;
5830       case ICmpInst::ICMP_ULT:
5831         // (float)int < -4.4   --> false
5832         // (float)int < 4.4    --> int <= 4
5833         if (RHS.isNegative())
5834           return ReplaceInstUsesWith(I, Context->getFalse());
5835         Pred = ICmpInst::ICMP_ULE;
5836         break;
5837       case ICmpInst::ICMP_SLT:
5838         // (float)int < -4.4   --> int < -4
5839         // (float)int < 4.4    --> int <= 4
5840         if (!RHS.isNegative())
5841           Pred = ICmpInst::ICMP_SLE;
5842         break;
5843       case ICmpInst::ICMP_UGT:
5844         // (float)int > 4.4    --> int > 4
5845         // (float)int > -4.4   --> true
5846         if (RHS.isNegative())
5847           return ReplaceInstUsesWith(I, Context->getTrue());
5848         break;
5849       case ICmpInst::ICMP_SGT:
5850         // (float)int > 4.4    --> int > 4
5851         // (float)int > -4.4   --> int >= -4
5852         if (RHS.isNegative())
5853           Pred = ICmpInst::ICMP_SGE;
5854         break;
5855       case ICmpInst::ICMP_UGE:
5856         // (float)int >= -4.4   --> true
5857         // (float)int >= 4.4    --> int > 4
5858         if (!RHS.isNegative())
5859           return ReplaceInstUsesWith(I, Context->getTrue());
5860         Pred = ICmpInst::ICMP_UGT;
5861         break;
5862       case ICmpInst::ICMP_SGE:
5863         // (float)int >= -4.4   --> int >= -4
5864         // (float)int >= 4.4    --> int > 4
5865         if (!RHS.isNegative())
5866           Pred = ICmpInst::ICMP_SGT;
5867         break;
5868       }
5869     }
5870   }
5871
5872   // Lower this FP comparison into an appropriate integer version of the
5873   // comparison.
5874   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5875 }
5876
5877 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5878   bool Changed = SimplifyCompare(I);
5879   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5880
5881   // Fold trivial predicates.
5882   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5883     return ReplaceInstUsesWith(I, Context->getFalse());
5884   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5885     return ReplaceInstUsesWith(I, Context->getTrue());
5886   
5887   // Simplify 'fcmp pred X, X'
5888   if (Op0 == Op1) {
5889     switch (I.getPredicate()) {
5890     default: llvm_unreachable("Unknown predicate!");
5891     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5892     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5893     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5894       return ReplaceInstUsesWith(I, Context->getTrue());
5895     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5896     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5897     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5898       return ReplaceInstUsesWith(I, Context->getFalse());
5899       
5900     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5901     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5902     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5903     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5904       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5905       I.setPredicate(FCmpInst::FCMP_UNO);
5906       I.setOperand(1, Context->getNullValue(Op0->getType()));
5907       return &I;
5908       
5909     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5910     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5911     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5912     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5913       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5914       I.setPredicate(FCmpInst::FCMP_ORD);
5915       I.setOperand(1, Context->getNullValue(Op0->getType()));
5916       return &I;
5917     }
5918   }
5919     
5920   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5921     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5922
5923   // Handle fcmp with constant RHS
5924   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5925     // If the constant is a nan, see if we can fold the comparison based on it.
5926     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5927       if (CFP->getValueAPF().isNaN()) {
5928         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5929           return ReplaceInstUsesWith(I, Context->getFalse());
5930         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5931                "Comparison must be either ordered or unordered!");
5932         // True if unordered.
5933         return ReplaceInstUsesWith(I, Context->getTrue());
5934       }
5935     }
5936     
5937     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5938       switch (LHSI->getOpcode()) {
5939       case Instruction::PHI:
5940         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5941         // block.  If in the same block, we're encouraging jump threading.  If
5942         // not, we are just pessimizing the code by making an i1 phi.
5943         if (LHSI->getParent() == I.getParent())
5944           if (Instruction *NV = FoldOpIntoPhi(I))
5945             return NV;
5946         break;
5947       case Instruction::SIToFP:
5948       case Instruction::UIToFP:
5949         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5950           return NV;
5951         break;
5952       case Instruction::Select:
5953         // If either operand of the select is a constant, we can fold the
5954         // comparison into the select arms, which will cause one to be
5955         // constant folded and the select turned into a bitwise or.
5956         Value *Op1 = 0, *Op2 = 0;
5957         if (LHSI->hasOneUse()) {
5958           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5959             // Fold the known value into the constant operand.
5960             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5961             // Insert a new FCmp of the other select operand.
5962             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5963                                                       LHSI->getOperand(2), RHSC,
5964                                                       I.getName()), I);
5965           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5966             // Fold the known value into the constant operand.
5967             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5968             // Insert a new FCmp of the other select operand.
5969             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5970                                                       LHSI->getOperand(1), RHSC,
5971                                                       I.getName()), I);
5972           }
5973         }
5974
5975         if (Op1)
5976           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5977         break;
5978       }
5979   }
5980
5981   return Changed ? &I : 0;
5982 }
5983
5984 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5985   bool Changed = SimplifyCompare(I);
5986   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5987   const Type *Ty = Op0->getType();
5988
5989   // icmp X, X
5990   if (Op0 == Op1)
5991     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5992                                                    I.isTrueWhenEqual()));
5993
5994   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5995     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5996   
5997   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5998   // addresses never equal each other!  We already know that Op0 != Op1.
5999   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6000        isa<ConstantPointerNull>(Op0)) &&
6001       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6002        isa<ConstantPointerNull>(Op1)))
6003     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
6004                                                    !I.isTrueWhenEqual()));
6005
6006   // icmp's with boolean values can always be turned into bitwise operations
6007   if (Ty == Type::Int1Ty) {
6008     switch (I.getPredicate()) {
6009     default: llvm_unreachable("Invalid icmp instruction!");
6010     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6011       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6012       InsertNewInstBefore(Xor, I);
6013       return BinaryOperator::CreateNot(*Context, Xor);
6014     }
6015     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6016       return BinaryOperator::CreateXor(Op0, Op1);
6017
6018     case ICmpInst::ICMP_UGT:
6019       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6020       // FALL THROUGH
6021     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6022       Instruction *Not = BinaryOperator::CreateNot(*Context,
6023                                                    Op0, I.getName()+"tmp");
6024       InsertNewInstBefore(Not, I);
6025       return BinaryOperator::CreateAnd(Not, Op1);
6026     }
6027     case ICmpInst::ICMP_SGT:
6028       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6029       // FALL THROUGH
6030     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6031       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6032                                                    Op1, I.getName()+"tmp");
6033       InsertNewInstBefore(Not, I);
6034       return BinaryOperator::CreateAnd(Not, Op0);
6035     }
6036     case ICmpInst::ICMP_UGE:
6037       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6038       // FALL THROUGH
6039     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6040       Instruction *Not = BinaryOperator::CreateNot(*Context,
6041                                                    Op0, I.getName()+"tmp");
6042       InsertNewInstBefore(Not, I);
6043       return BinaryOperator::CreateOr(Not, Op1);
6044     }
6045     case ICmpInst::ICMP_SGE:
6046       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6047       // FALL THROUGH
6048     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6049       Instruction *Not = BinaryOperator::CreateNot(*Context,
6050                                                    Op1, I.getName()+"tmp");
6051       InsertNewInstBefore(Not, I);
6052       return BinaryOperator::CreateOr(Not, Op0);
6053     }
6054     }
6055   }
6056
6057   unsigned BitWidth = 0;
6058   if (TD)
6059     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6060   else if (Ty->isIntOrIntVector())
6061     BitWidth = Ty->getScalarSizeInBits();
6062
6063   bool isSignBit = false;
6064
6065   // See if we are doing a comparison with a constant.
6066   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6067     Value *A = 0, *B = 0;
6068     
6069     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6070     if (I.isEquality() && CI->isNullValue() &&
6071         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6072       // (icmp cond A B) if cond is equality
6073       return new ICmpInst(*Context, I.getPredicate(), A, B);
6074     }
6075     
6076     // If we have an icmp le or icmp ge instruction, turn it into the
6077     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6078     // them being folded in the code below.
6079     switch (I.getPredicate()) {
6080     default: break;
6081     case ICmpInst::ICMP_ULE:
6082       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6083         return ReplaceInstUsesWith(I, Context->getTrue());
6084       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6085                           AddOne(CI, Context));
6086     case ICmpInst::ICMP_SLE:
6087       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6088         return ReplaceInstUsesWith(I, Context->getTrue());
6089       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6090                           AddOne(CI, Context));
6091     case ICmpInst::ICMP_UGE:
6092       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6093         return ReplaceInstUsesWith(I, Context->getTrue());
6094       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6095                           SubOne(CI, Context));
6096     case ICmpInst::ICMP_SGE:
6097       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6098         return ReplaceInstUsesWith(I, Context->getTrue());
6099       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6100                           SubOne(CI, Context));
6101     }
6102     
6103     // If this comparison is a normal comparison, it demands all
6104     // bits, if it is a sign bit comparison, it only demands the sign bit.
6105     bool UnusedBit;
6106     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6107   }
6108
6109   // See if we can fold the comparison based on range information we can get
6110   // by checking whether bits are known to be zero or one in the input.
6111   if (BitWidth != 0) {
6112     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6113     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6114
6115     if (SimplifyDemandedBits(I.getOperandUse(0),
6116                              isSignBit ? APInt::getSignBit(BitWidth)
6117                                        : APInt::getAllOnesValue(BitWidth),
6118                              Op0KnownZero, Op0KnownOne, 0))
6119       return &I;
6120     if (SimplifyDemandedBits(I.getOperandUse(1),
6121                              APInt::getAllOnesValue(BitWidth),
6122                              Op1KnownZero, Op1KnownOne, 0))
6123       return &I;
6124
6125     // Given the known and unknown bits, compute a range that the LHS could be
6126     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6127     // EQ and NE we use unsigned values.
6128     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6129     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6130     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6131       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6132                                              Op0Min, Op0Max);
6133       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6134                                              Op1Min, Op1Max);
6135     } else {
6136       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6137                                                Op0Min, Op0Max);
6138       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6139                                                Op1Min, Op1Max);
6140     }
6141
6142     // If Min and Max are known to be the same, then SimplifyDemandedBits
6143     // figured out that the LHS is a constant.  Just constant fold this now so
6144     // that code below can assume that Min != Max.
6145     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6146       return new ICmpInst(*Context, I.getPredicate(),
6147                           ConstantInt::get(*Context, Op0Min), Op1);
6148     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6149       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6150                           ConstantInt::get(*Context, Op1Min));
6151
6152     // Based on the range information we know about the LHS, see if we can
6153     // simplify this comparison.  For example, (x&4) < 8  is always true.
6154     switch (I.getPredicate()) {
6155     default: llvm_unreachable("Unknown icmp opcode!");
6156     case ICmpInst::ICMP_EQ:
6157       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6158         return ReplaceInstUsesWith(I, Context->getFalse());
6159       break;
6160     case ICmpInst::ICMP_NE:
6161       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6162         return ReplaceInstUsesWith(I, Context->getTrue());
6163       break;
6164     case ICmpInst::ICMP_ULT:
6165       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6166         return ReplaceInstUsesWith(I, Context->getTrue());
6167       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6168         return ReplaceInstUsesWith(I, Context->getFalse());
6169       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6170         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6171       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6172         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6173           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6174                               SubOne(CI, Context));
6175
6176         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6177         if (CI->isMinValue(true))
6178           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6179                            Context->getAllOnesValue(Op0->getType()));
6180       }
6181       break;
6182     case ICmpInst::ICMP_UGT:
6183       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6184         return ReplaceInstUsesWith(I, Context->getTrue());
6185       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6186         return ReplaceInstUsesWith(I, Context->getFalse());
6187
6188       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6189         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6190       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6191         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6192           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6193                               AddOne(CI, Context));
6194
6195         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6196         if (CI->isMaxValue(true))
6197           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6198                               Context->getNullValue(Op0->getType()));
6199       }
6200       break;
6201     case ICmpInst::ICMP_SLT:
6202       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6203         return ReplaceInstUsesWith(I, Context->getTrue());
6204       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6205         return ReplaceInstUsesWith(I, Context->getFalse());
6206       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6207         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6208       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6209         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6210           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6211                               SubOne(CI, Context));
6212       }
6213       break;
6214     case ICmpInst::ICMP_SGT:
6215       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6216         return ReplaceInstUsesWith(I, Context->getTrue());
6217       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6218         return ReplaceInstUsesWith(I, Context->getFalse());
6219
6220       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6221         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6222       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6224           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6225                               AddOne(CI, Context));
6226       }
6227       break;
6228     case ICmpInst::ICMP_SGE:
6229       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6230       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6231         return ReplaceInstUsesWith(I, Context->getTrue());
6232       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6233         return ReplaceInstUsesWith(I, Context->getFalse());
6234       break;
6235     case ICmpInst::ICMP_SLE:
6236       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6237       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6238         return ReplaceInstUsesWith(I, Context->getTrue());
6239       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6240         return ReplaceInstUsesWith(I, Context->getFalse());
6241       break;
6242     case ICmpInst::ICMP_UGE:
6243       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6244       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6245         return ReplaceInstUsesWith(I, Context->getTrue());
6246       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6247         return ReplaceInstUsesWith(I, Context->getFalse());
6248       break;
6249     case ICmpInst::ICMP_ULE:
6250       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6251       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6252         return ReplaceInstUsesWith(I, Context->getTrue());
6253       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6254         return ReplaceInstUsesWith(I, Context->getFalse());
6255       break;
6256     }
6257
6258     // Turn a signed comparison into an unsigned one if both operands
6259     // are known to have the same sign.
6260     if (I.isSignedPredicate() &&
6261         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6262          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6263       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6264   }
6265
6266   // Test if the ICmpInst instruction is used exclusively by a select as
6267   // part of a minimum or maximum operation. If so, refrain from doing
6268   // any other folding. This helps out other analyses which understand
6269   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6270   // and CodeGen. And in this case, at least one of the comparison
6271   // operands has at least one user besides the compare (the select),
6272   // which would often largely negate the benefit of folding anyway.
6273   if (I.hasOneUse())
6274     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6275       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6276           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6277         return 0;
6278
6279   // See if we are doing a comparison between a constant and an instruction that
6280   // can be folded into the comparison.
6281   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6282     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6283     // instruction, see if that instruction also has constants so that the 
6284     // instruction can be folded into the icmp 
6285     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6286       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6287         return Res;
6288   }
6289
6290   // Handle icmp with constant (but not simple integer constant) RHS
6291   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6292     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6293       switch (LHSI->getOpcode()) {
6294       case Instruction::GetElementPtr:
6295         if (RHSC->isNullValue()) {
6296           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6297           bool isAllZeros = true;
6298           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6299             if (!isa<Constant>(LHSI->getOperand(i)) ||
6300                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6301               isAllZeros = false;
6302               break;
6303             }
6304           if (isAllZeros)
6305             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6306                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6307         }
6308         break;
6309
6310       case Instruction::PHI:
6311         // Only fold icmp into the PHI if the phi and fcmp are in the same
6312         // block.  If in the same block, we're encouraging jump threading.  If
6313         // not, we are just pessimizing the code by making an i1 phi.
6314         if (LHSI->getParent() == I.getParent())
6315           if (Instruction *NV = FoldOpIntoPhi(I))
6316             return NV;
6317         break;
6318       case Instruction::Select: {
6319         // If either operand of the select is a constant, we can fold the
6320         // comparison into the select arms, which will cause one to be
6321         // constant folded and the select turned into a bitwise or.
6322         Value *Op1 = 0, *Op2 = 0;
6323         if (LHSI->hasOneUse()) {
6324           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6325             // Fold the known value into the constant operand.
6326             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6327             // Insert a new ICmp of the other select operand.
6328             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6329                                                    LHSI->getOperand(2), RHSC,
6330                                                    I.getName()), I);
6331           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6332             // Fold the known value into the constant operand.
6333             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6334             // Insert a new ICmp of the other select operand.
6335             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6336                                                    LHSI->getOperand(1), RHSC,
6337                                                    I.getName()), I);
6338           }
6339         }
6340
6341         if (Op1)
6342           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6343         break;
6344       }
6345       case Instruction::Malloc:
6346         // If we have (malloc != null), and if the malloc has a single use, we
6347         // can assume it is successful and remove the malloc.
6348         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6349           AddToWorkList(LHSI);
6350           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6351                                                          !I.isTrueWhenEqual()));
6352         }
6353         break;
6354       }
6355   }
6356
6357   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6358   if (User *GEP = dyn_castGetElementPtr(Op0))
6359     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6360       return NI;
6361   if (User *GEP = dyn_castGetElementPtr(Op1))
6362     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6363                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6364       return NI;
6365
6366   // Test to see if the operands of the icmp are casted versions of other
6367   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6368   // now.
6369   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6370     if (isa<PointerType>(Op0->getType()) && 
6371         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6372       // We keep moving the cast from the left operand over to the right
6373       // operand, where it can often be eliminated completely.
6374       Op0 = CI->getOperand(0);
6375
6376       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6377       // so eliminate it as well.
6378       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6379         Op1 = CI2->getOperand(0);
6380
6381       // If Op1 is a constant, we can fold the cast into the constant.
6382       if (Op0->getType() != Op1->getType()) {
6383         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6384           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6385         } else {
6386           // Otherwise, cast the RHS right before the icmp
6387           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6388         }
6389       }
6390       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6391     }
6392   }
6393   
6394   if (isa<CastInst>(Op0)) {
6395     // Handle the special case of: icmp (cast bool to X), <cst>
6396     // This comes up when you have code like
6397     //   int X = A < B;
6398     //   if (X) ...
6399     // For generality, we handle any zero-extension of any operand comparison
6400     // with a constant or another cast from the same type.
6401     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6402       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6403         return R;
6404   }
6405   
6406   // See if it's the same type of instruction on the left and right.
6407   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6408     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6409       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6410           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6411         switch (Op0I->getOpcode()) {
6412         default: break;
6413         case Instruction::Add:
6414         case Instruction::Sub:
6415         case Instruction::Xor:
6416           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6417             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6418                                 Op1I->getOperand(0));
6419           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6420           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6421             if (CI->getValue().isSignBit()) {
6422               ICmpInst::Predicate Pred = I.isSignedPredicate()
6423                                              ? I.getUnsignedPredicate()
6424                                              : I.getSignedPredicate();
6425               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6426                                   Op1I->getOperand(0));
6427             }
6428             
6429             if (CI->getValue().isMaxSignedValue()) {
6430               ICmpInst::Predicate Pred = I.isSignedPredicate()
6431                                              ? I.getUnsignedPredicate()
6432                                              : I.getSignedPredicate();
6433               Pred = I.getSwappedPredicate(Pred);
6434               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6435                                   Op1I->getOperand(0));
6436             }
6437           }
6438           break;
6439         case Instruction::Mul:
6440           if (!I.isEquality())
6441             break;
6442
6443           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6444             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6445             // Mask = -1 >> count-trailing-zeros(Cst).
6446             if (!CI->isZero() && !CI->isOne()) {
6447               const APInt &AP = CI->getValue();
6448               ConstantInt *Mask = ConstantInt::get(*Context, 
6449                                       APInt::getLowBitsSet(AP.getBitWidth(),
6450                                                            AP.getBitWidth() -
6451                                                       AP.countTrailingZeros()));
6452               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6453                                                             Mask);
6454               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6455                                                             Mask);
6456               InsertNewInstBefore(And1, I);
6457               InsertNewInstBefore(And2, I);
6458               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6459             }
6460           }
6461           break;
6462         }
6463       }
6464     }
6465   }
6466   
6467   // ~x < ~y --> y < x
6468   { Value *A, *B;
6469     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6470         match(Op1, m_Not(m_Value(B)), *Context))
6471       return new ICmpInst(*Context, I.getPredicate(), B, A);
6472   }
6473   
6474   if (I.isEquality()) {
6475     Value *A, *B, *C, *D;
6476     
6477     // -x == -y --> x == y
6478     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6479         match(Op1, m_Neg(m_Value(B)), *Context))
6480       return new ICmpInst(*Context, I.getPredicate(), A, B);
6481     
6482     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6483       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6484         Value *OtherVal = A == Op1 ? B : A;
6485         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6486                             Context->getNullValue(A->getType()));
6487       }
6488
6489       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6490         // A^c1 == C^c2 --> A == C^(c1^c2)
6491         ConstantInt *C1, *C2;
6492         if (match(B, m_ConstantInt(C1), *Context) &&
6493             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6494           Constant *NC = 
6495                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6496           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6497           return new ICmpInst(*Context, I.getPredicate(), A,
6498                               InsertNewInstBefore(Xor, I));
6499         }
6500         
6501         // A^B == A^D -> B == D
6502         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6503         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6504         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6505         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6506       }
6507     }
6508     
6509     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6510         (A == Op0 || B == Op0)) {
6511       // A == (A^B)  ->  B == 0
6512       Value *OtherVal = A == Op0 ? B : A;
6513       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6514                           Context->getNullValue(A->getType()));
6515     }
6516
6517     // (A-B) == A  ->  B == 0
6518     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6519       return new ICmpInst(*Context, I.getPredicate(), B, 
6520                           Context->getNullValue(B->getType()));
6521
6522     // A == (A-B)  ->  B == 0
6523     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6524       return new ICmpInst(*Context, I.getPredicate(), B,
6525                           Context->getNullValue(B->getType()));
6526     
6527     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6528     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6529         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6530         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6531       Value *X = 0, *Y = 0, *Z = 0;
6532       
6533       if (A == C) {
6534         X = B; Y = D; Z = A;
6535       } else if (A == D) {
6536         X = B; Y = C; Z = A;
6537       } else if (B == C) {
6538         X = A; Y = D; Z = B;
6539       } else if (B == D) {
6540         X = A; Y = C; Z = B;
6541       }
6542       
6543       if (X) {   // Build (X^Y) & Z
6544         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6545         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6546         I.setOperand(0, Op1);
6547         I.setOperand(1, Context->getNullValue(Op1->getType()));
6548         return &I;
6549       }
6550     }
6551   }
6552   return Changed ? &I : 0;
6553 }
6554
6555
6556 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6557 /// and CmpRHS are both known to be integer constants.
6558 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6559                                           ConstantInt *DivRHS) {
6560   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6561   const APInt &CmpRHSV = CmpRHS->getValue();
6562   
6563   // FIXME: If the operand types don't match the type of the divide 
6564   // then don't attempt this transform. The code below doesn't have the
6565   // logic to deal with a signed divide and an unsigned compare (and
6566   // vice versa). This is because (x /s C1) <s C2  produces different 
6567   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6568   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6569   // work. :(  The if statement below tests that condition and bails 
6570   // if it finds it. 
6571   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6572   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6573     return 0;
6574   if (DivRHS->isZero())
6575     return 0; // The ProdOV computation fails on divide by zero.
6576   if (DivIsSigned && DivRHS->isAllOnesValue())
6577     return 0; // The overflow computation also screws up here
6578   if (DivRHS->isOne())
6579     return 0; // Not worth bothering, and eliminates some funny cases
6580               // with INT_MIN.
6581
6582   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6583   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6584   // C2 (CI). By solving for X we can turn this into a range check 
6585   // instead of computing a divide. 
6586   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6587
6588   // Determine if the product overflows by seeing if the product is
6589   // not equal to the divide. Make sure we do the same kind of divide
6590   // as in the LHS instruction that we're folding. 
6591   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6592                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6593
6594   // Get the ICmp opcode
6595   ICmpInst::Predicate Pred = ICI.getPredicate();
6596
6597   // Figure out the interval that is being checked.  For example, a comparison
6598   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6599   // Compute this interval based on the constants involved and the signedness of
6600   // the compare/divide.  This computes a half-open interval, keeping track of
6601   // whether either value in the interval overflows.  After analysis each
6602   // overflow variable is set to 0 if it's corresponding bound variable is valid
6603   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6604   int LoOverflow = 0, HiOverflow = 0;
6605   Constant *LoBound = 0, *HiBound = 0;
6606   
6607   if (!DivIsSigned) {  // udiv
6608     // e.g. X/5 op 3  --> [15, 20)
6609     LoBound = Prod;
6610     HiOverflow = LoOverflow = ProdOV;
6611     if (!HiOverflow)
6612       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6613   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6614     if (CmpRHSV == 0) {       // (X / pos) op 0
6615       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6616       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6617                                                                     Context)));
6618       HiBound = DivRHS;
6619     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6620       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6621       HiOverflow = LoOverflow = ProdOV;
6622       if (!HiOverflow)
6623         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6624     } else {                       // (X / pos) op neg
6625       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6626       HiBound = AddOne(Prod, Context);
6627       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6628       if (!LoOverflow) {
6629         ConstantInt* DivNeg =
6630                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6631         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6632                                      true) ? -1 : 0;
6633        }
6634     }
6635   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6636     if (CmpRHSV == 0) {       // (X / neg) op 0
6637       // e.g. X/-5 op 0  --> [-4, 5)
6638       LoBound = AddOne(DivRHS, Context);
6639       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6640       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6641         HiOverflow = 1;            // [INTMIN+1, overflow)
6642         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6643       }
6644     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6645       // e.g. X/-5 op 3  --> [-19, -14)
6646       HiBound = AddOne(Prod, Context);
6647       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6648       if (!LoOverflow)
6649         LoOverflow = AddWithOverflow(LoBound, HiBound,
6650                                      DivRHS, Context, true) ? -1 : 0;
6651     } else {                       // (X / neg) op neg
6652       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6653       LoOverflow = HiOverflow = ProdOV;
6654       if (!HiOverflow)
6655         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6656     }
6657     
6658     // Dividing by a negative swaps the condition.  LT <-> GT
6659     Pred = ICmpInst::getSwappedPredicate(Pred);
6660   }
6661
6662   Value *X = DivI->getOperand(0);
6663   switch (Pred) {
6664   default: llvm_unreachable("Unhandled icmp opcode!");
6665   case ICmpInst::ICMP_EQ:
6666     if (LoOverflow && HiOverflow)
6667       return ReplaceInstUsesWith(ICI, Context->getFalse());
6668     else if (HiOverflow)
6669       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6670                           ICmpInst::ICMP_UGE, X, LoBound);
6671     else if (LoOverflow)
6672       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6673                           ICmpInst::ICMP_ULT, X, HiBound);
6674     else
6675       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6676   case ICmpInst::ICMP_NE:
6677     if (LoOverflow && HiOverflow)
6678       return ReplaceInstUsesWith(ICI, Context->getTrue());
6679     else if (HiOverflow)
6680       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6681                           ICmpInst::ICMP_ULT, X, LoBound);
6682     else if (LoOverflow)
6683       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6684                           ICmpInst::ICMP_UGE, X, HiBound);
6685     else
6686       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6687   case ICmpInst::ICMP_ULT:
6688   case ICmpInst::ICMP_SLT:
6689     if (LoOverflow == +1)   // Low bound is greater than input range.
6690       return ReplaceInstUsesWith(ICI, Context->getTrue());
6691     if (LoOverflow == -1)   // Low bound is less than input range.
6692       return ReplaceInstUsesWith(ICI, Context->getFalse());
6693     return new ICmpInst(*Context, Pred, X, LoBound);
6694   case ICmpInst::ICMP_UGT:
6695   case ICmpInst::ICMP_SGT:
6696     if (HiOverflow == +1)       // High bound greater than input range.
6697       return ReplaceInstUsesWith(ICI, Context->getFalse());
6698     else if (HiOverflow == -1)  // High bound less than input range.
6699       return ReplaceInstUsesWith(ICI, Context->getTrue());
6700     if (Pred == ICmpInst::ICMP_UGT)
6701       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6702     else
6703       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6704   }
6705 }
6706
6707
6708 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6709 ///
6710 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6711                                                           Instruction *LHSI,
6712                                                           ConstantInt *RHS) {
6713   const APInt &RHSV = RHS->getValue();
6714   
6715   switch (LHSI->getOpcode()) {
6716   case Instruction::Trunc:
6717     if (ICI.isEquality() && LHSI->hasOneUse()) {
6718       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6719       // of the high bits truncated out of x are known.
6720       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6721              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6722       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6723       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6724       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6725       
6726       // If all the high bits are known, we can do this xform.
6727       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6728         // Pull in the high bits from known-ones set.
6729         APInt NewRHS(RHS->getValue());
6730         NewRHS.zext(SrcBits);
6731         NewRHS |= KnownOne;
6732         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6733                             ConstantInt::get(*Context, NewRHS));
6734       }
6735     }
6736     break;
6737       
6738   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6739     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6740       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6741       // fold the xor.
6742       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6743           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6744         Value *CompareVal = LHSI->getOperand(0);
6745         
6746         // If the sign bit of the XorCST is not set, there is no change to
6747         // the operation, just stop using the Xor.
6748         if (!XorCST->getValue().isNegative()) {
6749           ICI.setOperand(0, CompareVal);
6750           AddToWorkList(LHSI);
6751           return &ICI;
6752         }
6753         
6754         // Was the old condition true if the operand is positive?
6755         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6756         
6757         // If so, the new one isn't.
6758         isTrueIfPositive ^= true;
6759         
6760         if (isTrueIfPositive)
6761           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6762                               SubOne(RHS, Context));
6763         else
6764           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6765                               AddOne(RHS, Context));
6766       }
6767
6768       if (LHSI->hasOneUse()) {
6769         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6770         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6771           const APInt &SignBit = XorCST->getValue();
6772           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6773                                          ? ICI.getUnsignedPredicate()
6774                                          : ICI.getSignedPredicate();
6775           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6776                               ConstantInt::get(*Context, RHSV ^ SignBit));
6777         }
6778
6779         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6780         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6781           const APInt &NotSignBit = XorCST->getValue();
6782           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6783                                          ? ICI.getUnsignedPredicate()
6784                                          : ICI.getSignedPredicate();
6785           Pred = ICI.getSwappedPredicate(Pred);
6786           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6787                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6788         }
6789       }
6790     }
6791     break;
6792   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6793     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6794         LHSI->getOperand(0)->hasOneUse()) {
6795       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6796       
6797       // If the LHS is an AND of a truncating cast, we can widen the
6798       // and/compare to be the input width without changing the value
6799       // produced, eliminating a cast.
6800       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6801         // We can do this transformation if either the AND constant does not
6802         // have its sign bit set or if it is an equality comparison. 
6803         // Extending a relational comparison when we're checking the sign
6804         // bit would not work.
6805         if (Cast->hasOneUse() &&
6806             (ICI.isEquality() ||
6807              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6808           uint32_t BitWidth = 
6809             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6810           APInt NewCST = AndCST->getValue();
6811           NewCST.zext(BitWidth);
6812           APInt NewCI = RHSV;
6813           NewCI.zext(BitWidth);
6814           Instruction *NewAnd = 
6815             BinaryOperator::CreateAnd(Cast->getOperand(0),
6816                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6817           InsertNewInstBefore(NewAnd, ICI);
6818           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6819                               ConstantInt::get(*Context, NewCI));
6820         }
6821       }
6822       
6823       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6824       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6825       // happens a LOT in code produced by the C front-end, for bitfield
6826       // access.
6827       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6828       if (Shift && !Shift->isShift())
6829         Shift = 0;
6830       
6831       ConstantInt *ShAmt;
6832       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6833       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6834       const Type *AndTy = AndCST->getType();          // Type of the and.
6835       
6836       // We can fold this as long as we can't shift unknown bits
6837       // into the mask.  This can only happen with signed shift
6838       // rights, as they sign-extend.
6839       if (ShAmt) {
6840         bool CanFold = Shift->isLogicalShift();
6841         if (!CanFold) {
6842           // To test for the bad case of the signed shr, see if any
6843           // of the bits shifted in could be tested after the mask.
6844           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6845           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6846           
6847           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6848           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6849                AndCST->getValue()) == 0)
6850             CanFold = true;
6851         }
6852         
6853         if (CanFold) {
6854           Constant *NewCst;
6855           if (Shift->getOpcode() == Instruction::Shl)
6856             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6857           else
6858             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6859           
6860           // Check to see if we are shifting out any of the bits being
6861           // compared.
6862           if (Context->getConstantExpr(Shift->getOpcode(),
6863                                        NewCst, ShAmt) != RHS) {
6864             // If we shifted bits out, the fold is not going to work out.
6865             // As a special case, check to see if this means that the
6866             // result is always true or false now.
6867             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6868               return ReplaceInstUsesWith(ICI, Context->getFalse());
6869             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6870               return ReplaceInstUsesWith(ICI, Context->getTrue());
6871           } else {
6872             ICI.setOperand(1, NewCst);
6873             Constant *NewAndCST;
6874             if (Shift->getOpcode() == Instruction::Shl)
6875               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6876             else
6877               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6878             LHSI->setOperand(1, NewAndCST);
6879             LHSI->setOperand(0, Shift->getOperand(0));
6880             AddToWorkList(Shift); // Shift is dead.
6881             AddUsesToWorkList(ICI);
6882             return &ICI;
6883           }
6884         }
6885       }
6886       
6887       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6888       // preferable because it allows the C<<Y expression to be hoisted out
6889       // of a loop if Y is invariant and X is not.
6890       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6891           ICI.isEquality() && !Shift->isArithmeticShift() &&
6892           !isa<Constant>(Shift->getOperand(0))) {
6893         // Compute C << Y.
6894         Value *NS;
6895         if (Shift->getOpcode() == Instruction::LShr) {
6896           NS = BinaryOperator::CreateShl(AndCST, 
6897                                          Shift->getOperand(1), "tmp");
6898         } else {
6899           // Insert a logical shift.
6900           NS = BinaryOperator::CreateLShr(AndCST,
6901                                           Shift->getOperand(1), "tmp");
6902         }
6903         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6904         
6905         // Compute X & (C << Y).
6906         Instruction *NewAnd = 
6907           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6908         InsertNewInstBefore(NewAnd, ICI);
6909         
6910         ICI.setOperand(0, NewAnd);
6911         return &ICI;
6912       }
6913     }
6914     break;
6915     
6916   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6917     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6918     if (!ShAmt) break;
6919     
6920     uint32_t TypeBits = RHSV.getBitWidth();
6921     
6922     // Check that the shift amount is in range.  If not, don't perform
6923     // undefined shifts.  When the shift is visited it will be
6924     // simplified.
6925     if (ShAmt->uge(TypeBits))
6926       break;
6927     
6928     if (ICI.isEquality()) {
6929       // If we are comparing against bits always shifted out, the
6930       // comparison cannot succeed.
6931       Constant *Comp =
6932         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6933                                                                  ShAmt);
6934       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6935         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6936         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6937         return ReplaceInstUsesWith(ICI, Cst);
6938       }
6939       
6940       if (LHSI->hasOneUse()) {
6941         // Otherwise strength reduce the shift into an and.
6942         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6943         Constant *Mask =
6944           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6945                                                        TypeBits-ShAmtVal));
6946         
6947         Instruction *AndI =
6948           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6949                                     Mask, LHSI->getName()+".mask");
6950         Value *And = InsertNewInstBefore(AndI, ICI);
6951         return new ICmpInst(*Context, ICI.getPredicate(), And,
6952                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6953       }
6954     }
6955     
6956     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6957     bool TrueIfSigned = false;
6958     if (LHSI->hasOneUse() &&
6959         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6960       // (X << 31) <s 0  --> (X&1) != 0
6961       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6962                                            (TypeBits-ShAmt->getZExtValue()-1));
6963       Instruction *AndI =
6964         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6965                                   Mask, LHSI->getName()+".mask");
6966       Value *And = InsertNewInstBefore(AndI, ICI);
6967       
6968       return new ICmpInst(*Context,
6969                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6970                           And, Context->getNullValue(And->getType()));
6971     }
6972     break;
6973   }
6974     
6975   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6976   case Instruction::AShr: {
6977     // Only handle equality comparisons of shift-by-constant.
6978     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6979     if (!ShAmt || !ICI.isEquality()) break;
6980
6981     // Check that the shift amount is in range.  If not, don't perform
6982     // undefined shifts.  When the shift is visited it will be
6983     // simplified.
6984     uint32_t TypeBits = RHSV.getBitWidth();
6985     if (ShAmt->uge(TypeBits))
6986       break;
6987     
6988     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6989       
6990     // If we are comparing against bits always shifted out, the
6991     // comparison cannot succeed.
6992     APInt Comp = RHSV << ShAmtVal;
6993     if (LHSI->getOpcode() == Instruction::LShr)
6994       Comp = Comp.lshr(ShAmtVal);
6995     else
6996       Comp = Comp.ashr(ShAmtVal);
6997     
6998     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6999       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7000       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
7001       return ReplaceInstUsesWith(ICI, Cst);
7002     }
7003     
7004     // Otherwise, check to see if the bits shifted out are known to be zero.
7005     // If so, we can compare against the unshifted value:
7006     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7007     if (LHSI->hasOneUse() &&
7008         MaskedValueIsZero(LHSI->getOperand(0), 
7009                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7010       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7011                           Context->getConstantExprShl(RHS, ShAmt));
7012     }
7013       
7014     if (LHSI->hasOneUse()) {
7015       // Otherwise strength reduce the shift into an and.
7016       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7017       Constant *Mask = ConstantInt::get(*Context, Val);
7018       
7019       Instruction *AndI =
7020         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7021                                   Mask, LHSI->getName()+".mask");
7022       Value *And = InsertNewInstBefore(AndI, ICI);
7023       return new ICmpInst(*Context, ICI.getPredicate(), And,
7024                           Context->getConstantExprShl(RHS, ShAmt));
7025     }
7026     break;
7027   }
7028     
7029   case Instruction::SDiv:
7030   case Instruction::UDiv:
7031     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7032     // Fold this div into the comparison, producing a range check. 
7033     // Determine, based on the divide type, what the range is being 
7034     // checked.  If there is an overflow on the low or high side, remember 
7035     // it, otherwise compute the range [low, hi) bounding the new value.
7036     // See: InsertRangeTest above for the kinds of replacements possible.
7037     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7038       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7039                                           DivRHS))
7040         return R;
7041     break;
7042
7043   case Instruction::Add:
7044     // Fold: icmp pred (add, X, C1), C2
7045
7046     if (!ICI.isEquality()) {
7047       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7048       if (!LHSC) break;
7049       const APInt &LHSV = LHSC->getValue();
7050
7051       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7052                             .subtract(LHSV);
7053
7054       if (ICI.isSignedPredicate()) {
7055         if (CR.getLower().isSignBit()) {
7056           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7057                               ConstantInt::get(*Context, CR.getUpper()));
7058         } else if (CR.getUpper().isSignBit()) {
7059           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7060                               ConstantInt::get(*Context, CR.getLower()));
7061         }
7062       } else {
7063         if (CR.getLower().isMinValue()) {
7064           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7065                               ConstantInt::get(*Context, CR.getUpper()));
7066         } else if (CR.getUpper().isMinValue()) {
7067           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7068                               ConstantInt::get(*Context, CR.getLower()));
7069         }
7070       }
7071     }
7072     break;
7073   }
7074   
7075   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7076   if (ICI.isEquality()) {
7077     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7078     
7079     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7080     // the second operand is a constant, simplify a bit.
7081     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7082       switch (BO->getOpcode()) {
7083       case Instruction::SRem:
7084         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7085         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7086           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7087           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7088             Instruction *NewRem =
7089               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7090                                          BO->getName());
7091             InsertNewInstBefore(NewRem, ICI);
7092             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7093                                 Context->getNullValue(BO->getType()));
7094           }
7095         }
7096         break;
7097       case Instruction::Add:
7098         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7099         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7100           if (BO->hasOneUse())
7101             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7102                                 Context->getConstantExprSub(RHS, BOp1C));
7103         } else if (RHSV == 0) {
7104           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7105           // efficiently invertible, or if the add has just this one use.
7106           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7107           
7108           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7109             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7110           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7111             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7112           else if (BO->hasOneUse()) {
7113             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7114             InsertNewInstBefore(Neg, ICI);
7115             Neg->takeName(BO);
7116             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7117           }
7118         }
7119         break;
7120       case Instruction::Xor:
7121         // For the xor case, we can xor two constants together, eliminating
7122         // the explicit xor.
7123         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7124           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7125                               Context->getConstantExprXor(RHS, BOC));
7126         
7127         // FALLTHROUGH
7128       case Instruction::Sub:
7129         // Replace (([sub|xor] A, B) != 0) with (A != B)
7130         if (RHSV == 0)
7131           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7132                               BO->getOperand(1));
7133         break;
7134         
7135       case Instruction::Or:
7136         // If bits are being or'd in that are not present in the constant we
7137         // are comparing against, then the comparison could never succeed!
7138         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7139           Constant *NotCI = Context->getConstantExprNot(RHS);
7140           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7141             return ReplaceInstUsesWith(ICI,
7142                                        ConstantInt::get(Type::Int1Ty, 
7143                                        isICMP_NE));
7144         }
7145         break;
7146         
7147       case Instruction::And:
7148         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7149           // If bits are being compared against that are and'd out, then the
7150           // comparison can never succeed!
7151           if ((RHSV & ~BOC->getValue()) != 0)
7152             return ReplaceInstUsesWith(ICI,
7153                                        ConstantInt::get(Type::Int1Ty,
7154                                        isICMP_NE));
7155           
7156           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7157           if (RHS == BOC && RHSV.isPowerOf2())
7158             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7159                                 ICmpInst::ICMP_NE, LHSI,
7160                                 Context->getNullValue(RHS->getType()));
7161           
7162           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7163           if (BOC->getValue().isSignBit()) {
7164             Value *X = BO->getOperand(0);
7165             Constant *Zero = Context->getNullValue(X->getType());
7166             ICmpInst::Predicate pred = isICMP_NE ? 
7167               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7168             return new ICmpInst(*Context, pred, X, Zero);
7169           }
7170           
7171           // ((X & ~7) == 0) --> X < 8
7172           if (RHSV == 0 && isHighOnes(BOC)) {
7173             Value *X = BO->getOperand(0);
7174             Constant *NegX = Context->getConstantExprNeg(BOC);
7175             ICmpInst::Predicate pred = isICMP_NE ? 
7176               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7177             return new ICmpInst(*Context, pred, X, NegX);
7178           }
7179         }
7180       default: break;
7181       }
7182     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7183       // Handle icmp {eq|ne} <intrinsic>, intcst.
7184       if (II->getIntrinsicID() == Intrinsic::bswap) {
7185         AddToWorkList(II);
7186         ICI.setOperand(0, II->getOperand(1));
7187         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7188         return &ICI;
7189       }
7190     }
7191   }
7192   return 0;
7193 }
7194
7195 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7196 /// We only handle extending casts so far.
7197 ///
7198 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7199   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7200   Value *LHSCIOp        = LHSCI->getOperand(0);
7201   const Type *SrcTy     = LHSCIOp->getType();
7202   const Type *DestTy    = LHSCI->getType();
7203   Value *RHSCIOp;
7204
7205   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7206   // integer type is the same size as the pointer type.
7207   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7208       TD->getPointerSizeInBits() ==
7209          cast<IntegerType>(DestTy)->getBitWidth()) {
7210     Value *RHSOp = 0;
7211     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7212       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7213     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7214       RHSOp = RHSC->getOperand(0);
7215       // If the pointer types don't match, insert a bitcast.
7216       if (LHSCIOp->getType() != RHSOp->getType())
7217         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7218     }
7219
7220     if (RHSOp)
7221       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7222   }
7223   
7224   // The code below only handles extension cast instructions, so far.
7225   // Enforce this.
7226   if (LHSCI->getOpcode() != Instruction::ZExt &&
7227       LHSCI->getOpcode() != Instruction::SExt)
7228     return 0;
7229
7230   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7231   bool isSignedCmp = ICI.isSignedPredicate();
7232
7233   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7234     // Not an extension from the same type?
7235     RHSCIOp = CI->getOperand(0);
7236     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7237       return 0;
7238     
7239     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7240     // and the other is a zext), then we can't handle this.
7241     if (CI->getOpcode() != LHSCI->getOpcode())
7242       return 0;
7243
7244     // Deal with equality cases early.
7245     if (ICI.isEquality())
7246       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7247
7248     // A signed comparison of sign extended values simplifies into a
7249     // signed comparison.
7250     if (isSignedCmp && isSignedExt)
7251       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7252
7253     // The other three cases all fold into an unsigned comparison.
7254     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7255   }
7256
7257   // If we aren't dealing with a constant on the RHS, exit early
7258   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7259   if (!CI)
7260     return 0;
7261
7262   // Compute the constant that would happen if we truncated to SrcTy then
7263   // reextended to DestTy.
7264   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7265   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7266                                                 Res1, DestTy);
7267
7268   // If the re-extended constant didn't change...
7269   if (Res2 == CI) {
7270     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7271     // For example, we might have:
7272     //    %A = sext i16 %X to i32
7273     //    %B = icmp ugt i32 %A, 1330
7274     // It is incorrect to transform this into 
7275     //    %B = icmp ugt i16 %X, 1330
7276     // because %A may have negative value. 
7277     //
7278     // However, we allow this when the compare is EQ/NE, because they are
7279     // signless.
7280     if (isSignedExt == isSignedCmp || ICI.isEquality())
7281       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7282     return 0;
7283   }
7284
7285   // The re-extended constant changed so the constant cannot be represented 
7286   // in the shorter type. Consequently, we cannot emit a simple comparison.
7287
7288   // First, handle some easy cases. We know the result cannot be equal at this
7289   // point so handle the ICI.isEquality() cases
7290   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7291     return ReplaceInstUsesWith(ICI, Context->getFalse());
7292   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7293     return ReplaceInstUsesWith(ICI, Context->getTrue());
7294
7295   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7296   // should have been folded away previously and not enter in here.
7297   Value *Result;
7298   if (isSignedCmp) {
7299     // We're performing a signed comparison.
7300     if (cast<ConstantInt>(CI)->getValue().isNegative())
7301       Result = Context->getFalse();          // X < (small) --> false
7302     else
7303       Result = Context->getTrue();           // X < (large) --> true
7304   } else {
7305     // We're performing an unsigned comparison.
7306     if (isSignedExt) {
7307       // We're performing an unsigned comp with a sign extended value.
7308       // This is true if the input is >= 0. [aka >s -1]
7309       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7310       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7311                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7312     } else {
7313       // Unsigned extend & unsigned compare -> always true.
7314       Result = Context->getTrue();
7315     }
7316   }
7317
7318   // Finally, return the value computed.
7319   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7320       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7321     return ReplaceInstUsesWith(ICI, Result);
7322
7323   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7324           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7325          "ICmp should be folded!");
7326   if (Constant *CI = dyn_cast<Constant>(Result))
7327     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7328   return BinaryOperator::CreateNot(*Context, Result);
7329 }
7330
7331 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7332   return commonShiftTransforms(I);
7333 }
7334
7335 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7336   return commonShiftTransforms(I);
7337 }
7338
7339 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7340   if (Instruction *R = commonShiftTransforms(I))
7341     return R;
7342   
7343   Value *Op0 = I.getOperand(0);
7344   
7345   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7346   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7347     if (CSI->isAllOnesValue())
7348       return ReplaceInstUsesWith(I, CSI);
7349
7350   // See if we can turn a signed shr into an unsigned shr.
7351   if (MaskedValueIsZero(Op0,
7352                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7353     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7354
7355   // Arithmetic shifting an all-sign-bit value is a no-op.
7356   unsigned NumSignBits = ComputeNumSignBits(Op0);
7357   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7358     return ReplaceInstUsesWith(I, Op0);
7359
7360   return 0;
7361 }
7362
7363 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7364   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7365   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7366
7367   // shl X, 0 == X and shr X, 0 == X
7368   // shl 0, X == 0 and shr 0, X == 0
7369   if (Op1 == Context->getNullValue(Op1->getType()) ||
7370       Op0 == Context->getNullValue(Op0->getType()))
7371     return ReplaceInstUsesWith(I, Op0);
7372   
7373   if (isa<UndefValue>(Op0)) {            
7374     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7375       return ReplaceInstUsesWith(I, Op0);
7376     else                                    // undef << X -> 0, undef >>u X -> 0
7377       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7378   }
7379   if (isa<UndefValue>(Op1)) {
7380     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7381       return ReplaceInstUsesWith(I, Op0);          
7382     else                                     // X << undef, X >>u undef -> 0
7383       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7384   }
7385
7386   // See if we can fold away this shift.
7387   if (SimplifyDemandedInstructionBits(I))
7388     return &I;
7389
7390   // Try to fold constant and into select arguments.
7391   if (isa<Constant>(Op0))
7392     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7393       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7394         return R;
7395
7396   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7397     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7398       return Res;
7399   return 0;
7400 }
7401
7402 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7403                                                BinaryOperator &I) {
7404   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7405
7406   // See if we can simplify any instructions used by the instruction whose sole 
7407   // purpose is to compute bits we don't care about.
7408   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7409   
7410   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7411   // a signed shift.
7412   //
7413   if (Op1->uge(TypeBits)) {
7414     if (I.getOpcode() != Instruction::AShr)
7415       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7416     else {
7417       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7418       return &I;
7419     }
7420   }
7421   
7422   // ((X*C1) << C2) == (X * (C1 << C2))
7423   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7424     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7425       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7426         return BinaryOperator::CreateMul(BO->getOperand(0),
7427                                         Context->getConstantExprShl(BOOp, Op1));
7428   
7429   // Try to fold constant and into select arguments.
7430   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7431     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7432       return R;
7433   if (isa<PHINode>(Op0))
7434     if (Instruction *NV = FoldOpIntoPhi(I))
7435       return NV;
7436   
7437   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7438   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7439     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7440     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7441     // place.  Don't try to do this transformation in this case.  Also, we
7442     // require that the input operand is a shift-by-constant so that we have
7443     // confidence that the shifts will get folded together.  We could do this
7444     // xform in more cases, but it is unlikely to be profitable.
7445     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7446         isa<ConstantInt>(TrOp->getOperand(1))) {
7447       // Okay, we'll do this xform.  Make the shift of shift.
7448       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7449       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7450                                                 I.getName());
7451       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7452
7453       // For logical shifts, the truncation has the effect of making the high
7454       // part of the register be zeros.  Emulate this by inserting an AND to
7455       // clear the top bits as needed.  This 'and' will usually be zapped by
7456       // other xforms later if dead.
7457       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7458       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7459       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7460       
7461       // The mask we constructed says what the trunc would do if occurring
7462       // between the shifts.  We want to know the effect *after* the second
7463       // shift.  We know that it is a logical shift by a constant, so adjust the
7464       // mask as appropriate.
7465       if (I.getOpcode() == Instruction::Shl)
7466         MaskV <<= Op1->getZExtValue();
7467       else {
7468         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7469         MaskV = MaskV.lshr(Op1->getZExtValue());
7470       }
7471
7472       Instruction *And =
7473         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7474                                   TI->getName());
7475       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7476
7477       // Return the value truncated to the interesting size.
7478       return new TruncInst(And, I.getType());
7479     }
7480   }
7481   
7482   if (Op0->hasOneUse()) {
7483     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7484       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7485       Value *V1, *V2;
7486       ConstantInt *CC;
7487       switch (Op0BO->getOpcode()) {
7488         default: break;
7489         case Instruction::Add:
7490         case Instruction::And:
7491         case Instruction::Or:
7492         case Instruction::Xor: {
7493           // These operators commute.
7494           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7495           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7496               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7497                     m_Specific(Op1)), *Context)){
7498             Instruction *YS = BinaryOperator::CreateShl(
7499                                             Op0BO->getOperand(0), Op1,
7500                                             Op0BO->getName());
7501             InsertNewInstBefore(YS, I); // (Y << C)
7502             Instruction *X = 
7503               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7504                                      Op0BO->getOperand(1)->getName());
7505             InsertNewInstBefore(X, I);  // (X + (Y << C))
7506             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7507             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7508                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7509           }
7510           
7511           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7512           Value *Op0BOOp1 = Op0BO->getOperand(1);
7513           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7514               match(Op0BOOp1, 
7515                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7516                           m_ConstantInt(CC)), *Context) &&
7517               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7518             Instruction *YS = BinaryOperator::CreateShl(
7519                                                      Op0BO->getOperand(0), Op1,
7520                                                      Op0BO->getName());
7521             InsertNewInstBefore(YS, I); // (Y << C)
7522             Instruction *XM =
7523               BinaryOperator::CreateAnd(V1,
7524                                         Context->getConstantExprShl(CC, Op1),
7525                                         V1->getName()+".mask");
7526             InsertNewInstBefore(XM, I); // X & (CC << C)
7527             
7528             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7529           }
7530         }
7531           
7532         // FALL THROUGH.
7533         case Instruction::Sub: {
7534           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7535           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7536               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7537                     m_Specific(Op1)), *Context)){
7538             Instruction *YS = BinaryOperator::CreateShl(
7539                                                      Op0BO->getOperand(1), Op1,
7540                                                      Op0BO->getName());
7541             InsertNewInstBefore(YS, I); // (Y << C)
7542             Instruction *X =
7543               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7544                                      Op0BO->getOperand(0)->getName());
7545             InsertNewInstBefore(X, I);  // (X + (Y << C))
7546             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7547             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7548                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7549           }
7550           
7551           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7552           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7553               match(Op0BO->getOperand(0),
7554                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7555                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7556               cast<BinaryOperator>(Op0BO->getOperand(0))
7557                   ->getOperand(0)->hasOneUse()) {
7558             Instruction *YS = BinaryOperator::CreateShl(
7559                                                      Op0BO->getOperand(1), Op1,
7560                                                      Op0BO->getName());
7561             InsertNewInstBefore(YS, I); // (Y << C)
7562             Instruction *XM =
7563               BinaryOperator::CreateAnd(V1, 
7564                                         Context->getConstantExprShl(CC, Op1),
7565                                         V1->getName()+".mask");
7566             InsertNewInstBefore(XM, I); // X & (CC << C)
7567             
7568             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7569           }
7570           
7571           break;
7572         }
7573       }
7574       
7575       
7576       // If the operand is an bitwise operator with a constant RHS, and the
7577       // shift is the only use, we can pull it out of the shift.
7578       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7579         bool isValid = true;     // Valid only for And, Or, Xor
7580         bool highBitSet = false; // Transform if high bit of constant set?
7581         
7582         switch (Op0BO->getOpcode()) {
7583           default: isValid = false; break;   // Do not perform transform!
7584           case Instruction::Add:
7585             isValid = isLeftShift;
7586             break;
7587           case Instruction::Or:
7588           case Instruction::Xor:
7589             highBitSet = false;
7590             break;
7591           case Instruction::And:
7592             highBitSet = true;
7593             break;
7594         }
7595         
7596         // If this is a signed shift right, and the high bit is modified
7597         // by the logical operation, do not perform the transformation.
7598         // The highBitSet boolean indicates the value of the high bit of
7599         // the constant which would cause it to be modified for this
7600         // operation.
7601         //
7602         if (isValid && I.getOpcode() == Instruction::AShr)
7603           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7604         
7605         if (isValid) {
7606           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7607           
7608           Instruction *NewShift =
7609             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7610           InsertNewInstBefore(NewShift, I);
7611           NewShift->takeName(Op0BO);
7612           
7613           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7614                                         NewRHS);
7615         }
7616       }
7617     }
7618   }
7619   
7620   // Find out if this is a shift of a shift by a constant.
7621   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7622   if (ShiftOp && !ShiftOp->isShift())
7623     ShiftOp = 0;
7624   
7625   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7626     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7627     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7628     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7629     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7630     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7631     Value *X = ShiftOp->getOperand(0);
7632     
7633     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7634     
7635     const IntegerType *Ty = cast<IntegerType>(I.getType());
7636     
7637     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7638     if (I.getOpcode() == ShiftOp->getOpcode()) {
7639       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7640       // saturates.
7641       if (AmtSum >= TypeBits) {
7642         if (I.getOpcode() != Instruction::AShr)
7643           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7644         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7645       }
7646       
7647       return BinaryOperator::Create(I.getOpcode(), X,
7648                                     ConstantInt::get(Ty, AmtSum));
7649     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7650                I.getOpcode() == Instruction::AShr) {
7651       if (AmtSum >= TypeBits)
7652         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7653       
7654       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7655       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7656     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7657                I.getOpcode() == Instruction::LShr) {
7658       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7659       if (AmtSum >= TypeBits)
7660         AmtSum = TypeBits-1;
7661       
7662       Instruction *Shift =
7663         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7664       InsertNewInstBefore(Shift, I);
7665
7666       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7667       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7668     }
7669     
7670     // Okay, if we get here, one shift must be left, and the other shift must be
7671     // right.  See if the amounts are equal.
7672     if (ShiftAmt1 == ShiftAmt2) {
7673       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7674       if (I.getOpcode() == Instruction::Shl) {
7675         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7676         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7677       }
7678       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7679       if (I.getOpcode() == Instruction::LShr) {
7680         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7681         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7682       }
7683       // We can simplify ((X << C) >>s C) into a trunc + sext.
7684       // NOTE: we could do this for any C, but that would make 'unusual' integer
7685       // types.  For now, just stick to ones well-supported by the code
7686       // generators.
7687       const Type *SExtType = 0;
7688       switch (Ty->getBitWidth() - ShiftAmt1) {
7689       case 1  :
7690       case 8  :
7691       case 16 :
7692       case 32 :
7693       case 64 :
7694       case 128:
7695         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7696         break;
7697       default: break;
7698       }
7699       if (SExtType) {
7700         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7701         InsertNewInstBefore(NewTrunc, I);
7702         return new SExtInst(NewTrunc, Ty);
7703       }
7704       // Otherwise, we can't handle it yet.
7705     } else if (ShiftAmt1 < ShiftAmt2) {
7706       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7707       
7708       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7709       if (I.getOpcode() == Instruction::Shl) {
7710         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7711                ShiftOp->getOpcode() == Instruction::AShr);
7712         Instruction *Shift =
7713           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7714         InsertNewInstBefore(Shift, I);
7715         
7716         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7717         return BinaryOperator::CreateAnd(Shift,
7718                                          ConstantInt::get(*Context, Mask));
7719       }
7720       
7721       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7722       if (I.getOpcode() == Instruction::LShr) {
7723         assert(ShiftOp->getOpcode() == Instruction::Shl);
7724         Instruction *Shift =
7725           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7726         InsertNewInstBefore(Shift, I);
7727         
7728         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7729         return BinaryOperator::CreateAnd(Shift,
7730                                          ConstantInt::get(*Context, Mask));
7731       }
7732       
7733       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7734     } else {
7735       assert(ShiftAmt2 < ShiftAmt1);
7736       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7737
7738       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7739       if (I.getOpcode() == Instruction::Shl) {
7740         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7741                ShiftOp->getOpcode() == Instruction::AShr);
7742         Instruction *Shift =
7743           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7744                                  ConstantInt::get(Ty, ShiftDiff));
7745         InsertNewInstBefore(Shift, I);
7746         
7747         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7748         return BinaryOperator::CreateAnd(Shift,
7749                                          ConstantInt::get(*Context, Mask));
7750       }
7751       
7752       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7753       if (I.getOpcode() == Instruction::LShr) {
7754         assert(ShiftOp->getOpcode() == Instruction::Shl);
7755         Instruction *Shift =
7756           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7757         InsertNewInstBefore(Shift, I);
7758         
7759         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7760         return BinaryOperator::CreateAnd(Shift,
7761                                          ConstantInt::get(*Context, Mask));
7762       }
7763       
7764       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7765     }
7766   }
7767   return 0;
7768 }
7769
7770
7771 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7772 /// expression.  If so, decompose it, returning some value X, such that Val is
7773 /// X*Scale+Offset.
7774 ///
7775 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7776                                         int &Offset, LLVMContext *Context) {
7777   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7778   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7779     Offset = CI->getZExtValue();
7780     Scale  = 0;
7781     return ConstantInt::get(Type::Int32Ty, 0);
7782   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7783     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7784       if (I->getOpcode() == Instruction::Shl) {
7785         // This is a value scaled by '1 << the shift amt'.
7786         Scale = 1U << RHS->getZExtValue();
7787         Offset = 0;
7788         return I->getOperand(0);
7789       } else if (I->getOpcode() == Instruction::Mul) {
7790         // This value is scaled by 'RHS'.
7791         Scale = RHS->getZExtValue();
7792         Offset = 0;
7793         return I->getOperand(0);
7794       } else if (I->getOpcode() == Instruction::Add) {
7795         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7796         // where C1 is divisible by C2.
7797         unsigned SubScale;
7798         Value *SubVal = 
7799           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7800                                     Offset, Context);
7801         Offset += RHS->getZExtValue();
7802         Scale = SubScale;
7803         return SubVal;
7804       }
7805     }
7806   }
7807
7808   // Otherwise, we can't look past this.
7809   Scale = 1;
7810   Offset = 0;
7811   return Val;
7812 }
7813
7814
7815 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7816 /// try to eliminate the cast by moving the type information into the alloc.
7817 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7818                                                    AllocationInst &AI) {
7819   const PointerType *PTy = cast<PointerType>(CI.getType());
7820   
7821   // Remove any uses of AI that are dead.
7822   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7823   
7824   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7825     Instruction *User = cast<Instruction>(*UI++);
7826     if (isInstructionTriviallyDead(User)) {
7827       while (UI != E && *UI == User)
7828         ++UI; // If this instruction uses AI more than once, don't break UI.
7829       
7830       ++NumDeadInst;
7831       DOUT << "IC: DCE: " << *User;
7832       EraseInstFromFunction(*User);
7833     }
7834   }
7835
7836   // This requires TargetData to get the alloca alignment and size information.
7837   if (!TD) return 0;
7838
7839   // Get the type really allocated and the type casted to.
7840   const Type *AllocElTy = AI.getAllocatedType();
7841   const Type *CastElTy = PTy->getElementType();
7842   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7843
7844   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7845   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7846   if (CastElTyAlign < AllocElTyAlign) return 0;
7847
7848   // If the allocation has multiple uses, only promote it if we are strictly
7849   // increasing the alignment of the resultant allocation.  If we keep it the
7850   // same, we open the door to infinite loops of various kinds.  (A reference
7851   // from a dbg.declare doesn't count as a use for this purpose.)
7852   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7853       CastElTyAlign == AllocElTyAlign) return 0;
7854
7855   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7856   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7857   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7858
7859   // See if we can satisfy the modulus by pulling a scale out of the array
7860   // size argument.
7861   unsigned ArraySizeScale;
7862   int ArrayOffset;
7863   Value *NumElements = // See if the array size is a decomposable linear expr.
7864     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7865                               ArrayOffset, Context);
7866  
7867   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7868   // do the xform.
7869   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7870       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7871
7872   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7873   Value *Amt = 0;
7874   if (Scale == 1) {
7875     Amt = NumElements;
7876   } else {
7877     // If the allocation size is constant, form a constant mul expression
7878     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7879     if (isa<ConstantInt>(NumElements))
7880       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7881                                  cast<ConstantInt>(Amt));
7882     // otherwise multiply the amount and the number of elements
7883     else {
7884       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7885       Amt = InsertNewInstBefore(Tmp, AI);
7886     }
7887   }
7888   
7889   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7890     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7891     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7892     Amt = InsertNewInstBefore(Tmp, AI);
7893   }
7894   
7895   AllocationInst *New;
7896   if (isa<MallocInst>(AI))
7897     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7898   else
7899     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7900   InsertNewInstBefore(New, AI);
7901   New->takeName(&AI);
7902   
7903   // If the allocation has one real use plus a dbg.declare, just remove the
7904   // declare.
7905   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7906     EraseInstFromFunction(*DI);
7907   }
7908   // If the allocation has multiple real uses, insert a cast and change all
7909   // things that used it to use the new cast.  This will also hack on CI, but it
7910   // will die soon.
7911   else if (!AI.hasOneUse()) {
7912     AddUsesToWorkList(AI);
7913     // New is the allocation instruction, pointer typed. AI is the original
7914     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7915     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7916     InsertNewInstBefore(NewCast, AI);
7917     AI.replaceAllUsesWith(NewCast);
7918   }
7919   return ReplaceInstUsesWith(CI, New);
7920 }
7921
7922 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7923 /// and return it as type Ty without inserting any new casts and without
7924 /// changing the computed value.  This is used by code that tries to decide
7925 /// whether promoting or shrinking integer operations to wider or smaller types
7926 /// will allow us to eliminate a truncate or extend.
7927 ///
7928 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7929 /// extension operation if Ty is larger.
7930 ///
7931 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7932 /// should return true if trunc(V) can be computed by computing V in the smaller
7933 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7934 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7935 /// efficiently truncated.
7936 ///
7937 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7938 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7939 /// the final result.
7940 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7941                                               unsigned CastOpc,
7942                                               int &NumCastsRemoved){
7943   // We can always evaluate constants in another type.
7944   if (isa<Constant>(V))
7945     return true;
7946   
7947   Instruction *I = dyn_cast<Instruction>(V);
7948   if (!I) return false;
7949   
7950   const Type *OrigTy = V->getType();
7951   
7952   // If this is an extension or truncate, we can often eliminate it.
7953   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7954     // If this is a cast from the destination type, we can trivially eliminate
7955     // it, and this will remove a cast overall.
7956     if (I->getOperand(0)->getType() == Ty) {
7957       // If the first operand is itself a cast, and is eliminable, do not count
7958       // this as an eliminable cast.  We would prefer to eliminate those two
7959       // casts first.
7960       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7961         ++NumCastsRemoved;
7962       return true;
7963     }
7964   }
7965
7966   // We can't extend or shrink something that has multiple uses: doing so would
7967   // require duplicating the instruction in general, which isn't profitable.
7968   if (!I->hasOneUse()) return false;
7969
7970   unsigned Opc = I->getOpcode();
7971   switch (Opc) {
7972   case Instruction::Add:
7973   case Instruction::Sub:
7974   case Instruction::Mul:
7975   case Instruction::And:
7976   case Instruction::Or:
7977   case Instruction::Xor:
7978     // These operators can all arbitrarily be extended or truncated.
7979     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7980                                       NumCastsRemoved) &&
7981            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7982                                       NumCastsRemoved);
7983
7984   case Instruction::UDiv:
7985   case Instruction::URem: {
7986     // UDiv and URem can be truncated if all the truncated bits are zero.
7987     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7988     uint32_t BitWidth = Ty->getScalarSizeInBits();
7989     if (BitWidth < OrigBitWidth) {
7990       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7991       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7992           MaskedValueIsZero(I->getOperand(1), Mask)) {
7993         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7994                                           NumCastsRemoved) &&
7995                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7996                                           NumCastsRemoved);
7997       }
7998     }
7999     break;
8000   }
8001   case Instruction::Shl:
8002     // If we are truncating the result of this SHL, and if it's a shift of a
8003     // constant amount, we can always perform a SHL in a smaller type.
8004     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8005       uint32_t BitWidth = Ty->getScalarSizeInBits();
8006       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8007           CI->getLimitedValue(BitWidth) < BitWidth)
8008         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8009                                           NumCastsRemoved);
8010     }
8011     break;
8012   case Instruction::LShr:
8013     // If this is a truncate of a logical shr, we can truncate it to a smaller
8014     // lshr iff we know that the bits we would otherwise be shifting in are
8015     // already zeros.
8016     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8017       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8018       uint32_t BitWidth = Ty->getScalarSizeInBits();
8019       if (BitWidth < OrigBitWidth &&
8020           MaskedValueIsZero(I->getOperand(0),
8021             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8022           CI->getLimitedValue(BitWidth) < BitWidth) {
8023         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8024                                           NumCastsRemoved);
8025       }
8026     }
8027     break;
8028   case Instruction::ZExt:
8029   case Instruction::SExt:
8030   case Instruction::Trunc:
8031     // If this is the same kind of case as our original (e.g. zext+zext), we
8032     // can safely replace it.  Note that replacing it does not reduce the number
8033     // of casts in the input.
8034     if (Opc == CastOpc)
8035       return true;
8036
8037     // sext (zext ty1), ty2 -> zext ty2
8038     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8039       return true;
8040     break;
8041   case Instruction::Select: {
8042     SelectInst *SI = cast<SelectInst>(I);
8043     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8044                                       NumCastsRemoved) &&
8045            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8046                                       NumCastsRemoved);
8047   }
8048   case Instruction::PHI: {
8049     // We can change a phi if we can change all operands.
8050     PHINode *PN = cast<PHINode>(I);
8051     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8052       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8053                                       NumCastsRemoved))
8054         return false;
8055     return true;
8056   }
8057   default:
8058     // TODO: Can handle more cases here.
8059     break;
8060   }
8061   
8062   return false;
8063 }
8064
8065 /// EvaluateInDifferentType - Given an expression that 
8066 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8067 /// evaluate the expression.
8068 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8069                                              bool isSigned) {
8070   if (Constant *C = dyn_cast<Constant>(V))
8071     return Context->getConstantExprIntegerCast(C, Ty,
8072                                                isSigned /*Sext or ZExt*/);
8073
8074   // Otherwise, it must be an instruction.
8075   Instruction *I = cast<Instruction>(V);
8076   Instruction *Res = 0;
8077   unsigned Opc = I->getOpcode();
8078   switch (Opc) {
8079   case Instruction::Add:
8080   case Instruction::Sub:
8081   case Instruction::Mul:
8082   case Instruction::And:
8083   case Instruction::Or:
8084   case Instruction::Xor:
8085   case Instruction::AShr:
8086   case Instruction::LShr:
8087   case Instruction::Shl:
8088   case Instruction::UDiv:
8089   case Instruction::URem: {
8090     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8091     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8092     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8093     break;
8094   }    
8095   case Instruction::Trunc:
8096   case Instruction::ZExt:
8097   case Instruction::SExt:
8098     // If the source type of the cast is the type we're trying for then we can
8099     // just return the source.  There's no need to insert it because it is not
8100     // new.
8101     if (I->getOperand(0)->getType() == Ty)
8102       return I->getOperand(0);
8103     
8104     // Otherwise, must be the same type of cast, so just reinsert a new one.
8105     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8106                            Ty);
8107     break;
8108   case Instruction::Select: {
8109     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8110     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8111     Res = SelectInst::Create(I->getOperand(0), True, False);
8112     break;
8113   }
8114   case Instruction::PHI: {
8115     PHINode *OPN = cast<PHINode>(I);
8116     PHINode *NPN = PHINode::Create(Ty);
8117     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8118       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8119       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8120     }
8121     Res = NPN;
8122     break;
8123   }
8124   default: 
8125     // TODO: Can handle more cases here.
8126     llvm_unreachable("Unreachable!");
8127     break;
8128   }
8129   
8130   Res->takeName(I);
8131   return InsertNewInstBefore(Res, *I);
8132 }
8133
8134 /// @brief Implement the transforms common to all CastInst visitors.
8135 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8136   Value *Src = CI.getOperand(0);
8137
8138   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8139   // eliminate it now.
8140   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8141     if (Instruction::CastOps opc = 
8142         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8143       // The first cast (CSrc) is eliminable so we need to fix up or replace
8144       // the second cast (CI). CSrc will then have a good chance of being dead.
8145       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8146     }
8147   }
8148
8149   // If we are casting a select then fold the cast into the select
8150   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8151     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8152       return NV;
8153
8154   // If we are casting a PHI then fold the cast into the PHI
8155   if (isa<PHINode>(Src))
8156     if (Instruction *NV = FoldOpIntoPhi(CI))
8157       return NV;
8158   
8159   return 0;
8160 }
8161
8162 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8163 /// or not there is a sequence of GEP indices into the type that will land us at
8164 /// the specified offset.  If so, fill them into NewIndices and return the
8165 /// resultant element type, otherwise return null.
8166 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8167                                        SmallVectorImpl<Value*> &NewIndices,
8168                                        const TargetData *TD,
8169                                        LLVMContext *Context) {
8170   if (!TD) return 0;
8171   if (!Ty->isSized()) return 0;
8172   
8173   // Start with the index over the outer type.  Note that the type size
8174   // might be zero (even if the offset isn't zero) if the indexed type
8175   // is something like [0 x {int, int}]
8176   const Type *IntPtrTy = TD->getIntPtrType();
8177   int64_t FirstIdx = 0;
8178   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8179     FirstIdx = Offset/TySize;
8180     Offset -= FirstIdx*TySize;
8181     
8182     // Handle hosts where % returns negative instead of values [0..TySize).
8183     if (Offset < 0) {
8184       --FirstIdx;
8185       Offset += TySize;
8186       assert(Offset >= 0);
8187     }
8188     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8189   }
8190   
8191   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8192     
8193   // Index into the types.  If we fail, set OrigBase to null.
8194   while (Offset) {
8195     // Indexing into tail padding between struct/array elements.
8196     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8197       return 0;
8198     
8199     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8200       const StructLayout *SL = TD->getStructLayout(STy);
8201       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8202              "Offset must stay within the indexed type");
8203       
8204       unsigned Elt = SL->getElementContainingOffset(Offset);
8205       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8206       
8207       Offset -= SL->getElementOffset(Elt);
8208       Ty = STy->getElementType(Elt);
8209     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8210       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8211       assert(EltSize && "Cannot index into a zero-sized array");
8212       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8213       Offset %= EltSize;
8214       Ty = AT->getElementType();
8215     } else {
8216       // Otherwise, we can't index into the middle of this atomic type, bail.
8217       return 0;
8218     }
8219   }
8220   
8221   return Ty;
8222 }
8223
8224 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8225 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8226   Value *Src = CI.getOperand(0);
8227   
8228   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8229     // If casting the result of a getelementptr instruction with no offset, turn
8230     // this into a cast of the original pointer!
8231     if (GEP->hasAllZeroIndices()) {
8232       // Changing the cast operand is usually not a good idea but it is safe
8233       // here because the pointer operand is being replaced with another 
8234       // pointer operand so the opcode doesn't need to change.
8235       AddToWorkList(GEP);
8236       CI.setOperand(0, GEP->getOperand(0));
8237       return &CI;
8238     }
8239     
8240     // If the GEP has a single use, and the base pointer is a bitcast, and the
8241     // GEP computes a constant offset, see if we can convert these three
8242     // instructions into fewer.  This typically happens with unions and other
8243     // non-type-safe code.
8244     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8245       if (GEP->hasAllConstantIndices()) {
8246         // We are guaranteed to get a constant from EmitGEPOffset.
8247         ConstantInt *OffsetV =
8248                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8249         int64_t Offset = OffsetV->getSExtValue();
8250         
8251         // Get the base pointer input of the bitcast, and the type it points to.
8252         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8253         const Type *GEPIdxTy =
8254           cast<PointerType>(OrigBase->getType())->getElementType();
8255         SmallVector<Value*, 8> NewIndices;
8256         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8257           // If we were able to index down into an element, create the GEP
8258           // and bitcast the result.  This eliminates one bitcast, potentially
8259           // two.
8260           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8261                                                         NewIndices.begin(),
8262                                                         NewIndices.end(), "");
8263           InsertNewInstBefore(NGEP, CI);
8264           NGEP->takeName(GEP);
8265           
8266           if (isa<BitCastInst>(CI))
8267             return new BitCastInst(NGEP, CI.getType());
8268           assert(isa<PtrToIntInst>(CI));
8269           return new PtrToIntInst(NGEP, CI.getType());
8270         }
8271       }      
8272     }
8273   }
8274     
8275   return commonCastTransforms(CI);
8276 }
8277
8278 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8279 /// type like i42.  We don't want to introduce operations on random non-legal
8280 /// integer types where they don't already exist in the code.  In the future,
8281 /// we should consider making this based off target-data, so that 32-bit targets
8282 /// won't get i64 operations etc.
8283 static bool isSafeIntegerType(const Type *Ty) {
8284   switch (Ty->getPrimitiveSizeInBits()) {
8285   case 8:
8286   case 16:
8287   case 32:
8288   case 64:
8289     return true;
8290   default: 
8291     return false;
8292   }
8293 }
8294
8295 /// commonIntCastTransforms - This function implements the common transforms
8296 /// for trunc, zext, and sext.
8297 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8298   if (Instruction *Result = commonCastTransforms(CI))
8299     return Result;
8300
8301   Value *Src = CI.getOperand(0);
8302   const Type *SrcTy = Src->getType();
8303   const Type *DestTy = CI.getType();
8304   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8305   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8306
8307   // See if we can simplify any instructions used by the LHS whose sole 
8308   // purpose is to compute bits we don't care about.
8309   if (SimplifyDemandedInstructionBits(CI))
8310     return &CI;
8311
8312   // If the source isn't an instruction or has more than one use then we
8313   // can't do anything more. 
8314   Instruction *SrcI = dyn_cast<Instruction>(Src);
8315   if (!SrcI || !Src->hasOneUse())
8316     return 0;
8317
8318   // Attempt to propagate the cast into the instruction for int->int casts.
8319   int NumCastsRemoved = 0;
8320   // Only do this if the dest type is a simple type, don't convert the
8321   // expression tree to something weird like i93 unless the source is also
8322   // strange.
8323   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8324        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8325       CanEvaluateInDifferentType(SrcI, DestTy,
8326                                  CI.getOpcode(), NumCastsRemoved)) {
8327     // If this cast is a truncate, evaluting in a different type always
8328     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8329     // we need to do an AND to maintain the clear top-part of the computation,
8330     // so we require that the input have eliminated at least one cast.  If this
8331     // is a sign extension, we insert two new casts (to do the extension) so we
8332     // require that two casts have been eliminated.
8333     bool DoXForm = false;
8334     bool JustReplace = false;
8335     switch (CI.getOpcode()) {
8336     default:
8337       // All the others use floating point so we shouldn't actually 
8338       // get here because of the check above.
8339       llvm_unreachable("Unknown cast type");
8340     case Instruction::Trunc:
8341       DoXForm = true;
8342       break;
8343     case Instruction::ZExt: {
8344       DoXForm = NumCastsRemoved >= 1;
8345       if (!DoXForm && 0) {
8346         // If it's unnecessary to issue an AND to clear the high bits, it's
8347         // always profitable to do this xform.
8348         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8349         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8350         if (MaskedValueIsZero(TryRes, Mask))
8351           return ReplaceInstUsesWith(CI, TryRes);
8352         
8353         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8354           if (TryI->use_empty())
8355             EraseInstFromFunction(*TryI);
8356       }
8357       break;
8358     }
8359     case Instruction::SExt: {
8360       DoXForm = NumCastsRemoved >= 2;
8361       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8362         // If we do not have to emit the truncate + sext pair, then it's always
8363         // profitable to do this xform.
8364         //
8365         // It's not safe to eliminate the trunc + sext pair if one of the
8366         // eliminated cast is a truncate. e.g.
8367         // t2 = trunc i32 t1 to i16
8368         // t3 = sext i16 t2 to i32
8369         // !=
8370         // i32 t1
8371         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8372         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8373         if (NumSignBits > (DestBitSize - SrcBitSize))
8374           return ReplaceInstUsesWith(CI, TryRes);
8375         
8376         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8377           if (TryI->use_empty())
8378             EraseInstFromFunction(*TryI);
8379       }
8380       break;
8381     }
8382     }
8383     
8384     if (DoXForm) {
8385       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8386            << " cast: " << CI;
8387       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8388                                            CI.getOpcode() == Instruction::SExt);
8389       if (JustReplace)
8390         // Just replace this cast with the result.
8391         return ReplaceInstUsesWith(CI, Res);
8392
8393       assert(Res->getType() == DestTy);
8394       switch (CI.getOpcode()) {
8395       default: llvm_unreachable("Unknown cast type!");
8396       case Instruction::Trunc:
8397         // Just replace this cast with the result.
8398         return ReplaceInstUsesWith(CI, Res);
8399       case Instruction::ZExt: {
8400         assert(SrcBitSize < DestBitSize && "Not a zext?");
8401
8402         // If the high bits are already zero, just replace this cast with the
8403         // result.
8404         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8405         if (MaskedValueIsZero(Res, Mask))
8406           return ReplaceInstUsesWith(CI, Res);
8407
8408         // We need to emit an AND to clear the high bits.
8409         Constant *C = ConstantInt::get(*Context, 
8410                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8411         return BinaryOperator::CreateAnd(Res, C);
8412       }
8413       case Instruction::SExt: {
8414         // If the high bits are already filled with sign bit, just replace this
8415         // cast with the result.
8416         unsigned NumSignBits = ComputeNumSignBits(Res);
8417         if (NumSignBits > (DestBitSize - SrcBitSize))
8418           return ReplaceInstUsesWith(CI, Res);
8419
8420         // We need to emit a cast to truncate, then a cast to sext.
8421         return CastInst::Create(Instruction::SExt,
8422             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8423                              CI), DestTy);
8424       }
8425       }
8426     }
8427   }
8428   
8429   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8430   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8431
8432   switch (SrcI->getOpcode()) {
8433   case Instruction::Add:
8434   case Instruction::Mul:
8435   case Instruction::And:
8436   case Instruction::Or:
8437   case Instruction::Xor:
8438     // If we are discarding information, rewrite.
8439     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8440       // Don't insert two casts unless at least one can be eliminated.
8441       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8442           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8443         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8444         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8445         return BinaryOperator::Create(
8446             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8447       }
8448     }
8449
8450     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8451     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8452         SrcI->getOpcode() == Instruction::Xor &&
8453         Op1 == Context->getTrue() &&
8454         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8455       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8456       return BinaryOperator::CreateXor(New,
8457                                       ConstantInt::get(CI.getType(), 1));
8458     }
8459     break;
8460
8461   case Instruction::Shl: {
8462     // Canonicalize trunc inside shl, if we can.
8463     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8464     if (CI && DestBitSize < SrcBitSize &&
8465         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8466       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8467       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8468       return BinaryOperator::CreateShl(Op0c, Op1c);
8469     }
8470     break;
8471   }
8472   }
8473   return 0;
8474 }
8475
8476 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8477   if (Instruction *Result = commonIntCastTransforms(CI))
8478     return Result;
8479   
8480   Value *Src = CI.getOperand(0);
8481   const Type *Ty = CI.getType();
8482   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8483   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8484
8485   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8486   if (DestBitWidth == 1) {
8487     Constant *One = ConstantInt::get(Src->getType(), 1);
8488     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8489     Value *Zero = Context->getNullValue(Src->getType());
8490     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8491   }
8492
8493   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8494   ConstantInt *ShAmtV = 0;
8495   Value *ShiftOp = 0;
8496   if (Src->hasOneUse() &&
8497       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8498     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8499     
8500     // Get a mask for the bits shifting in.
8501     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8502     if (MaskedValueIsZero(ShiftOp, Mask)) {
8503       if (ShAmt >= DestBitWidth)        // All zeros.
8504         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8505       
8506       // Okay, we can shrink this.  Truncate the input, then return a new
8507       // shift.
8508       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8509       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8510       return BinaryOperator::CreateLShr(V1, V2);
8511     }
8512   }
8513   
8514   return 0;
8515 }
8516
8517 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8518 /// in order to eliminate the icmp.
8519 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8520                                              bool DoXform) {
8521   // If we are just checking for a icmp eq of a single bit and zext'ing it
8522   // to an integer, then shift the bit to the appropriate place and then
8523   // cast to integer to avoid the comparison.
8524   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8525     const APInt &Op1CV = Op1C->getValue();
8526       
8527     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8528     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8529     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8530         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8531       if (!DoXform) return ICI;
8532
8533       Value *In = ICI->getOperand(0);
8534       Value *Sh = ConstantInt::get(In->getType(),
8535                                    In->getType()->getScalarSizeInBits()-1);
8536       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8537                                                         In->getName()+".lobit"),
8538                                CI);
8539       if (In->getType() != CI.getType())
8540         In = CastInst::CreateIntegerCast(In, CI.getType(),
8541                                          false/*ZExt*/, "tmp", &CI);
8542
8543       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8544         Constant *One = ConstantInt::get(In->getType(), 1);
8545         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8546                                                          In->getName()+".not"),
8547                                  CI);
8548       }
8549
8550       return ReplaceInstUsesWith(CI, In);
8551     }
8552       
8553       
8554       
8555     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8556     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8557     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8558     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8559     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8560     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8561     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8562     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8563     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8564         // This only works for EQ and NE
8565         ICI->isEquality()) {
8566       // If Op1C some other power of two, convert:
8567       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8568       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8569       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8570       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8571         
8572       APInt KnownZeroMask(~KnownZero);
8573       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8574         if (!DoXform) return ICI;
8575
8576         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8577         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8578           // (X&4) == 2 --> false
8579           // (X&4) != 2 --> true
8580           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8581           Res = Context->getConstantExprZExt(Res, CI.getType());
8582           return ReplaceInstUsesWith(CI, Res);
8583         }
8584           
8585         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8586         Value *In = ICI->getOperand(0);
8587         if (ShiftAmt) {
8588           // Perform a logical shr by shiftamt.
8589           // Insert the shift to put the result in the low bit.
8590           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8591                               ConstantInt::get(In->getType(), ShiftAmt),
8592                                                    In->getName()+".lobit"), CI);
8593         }
8594           
8595         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8596           Constant *One = ConstantInt::get(In->getType(), 1);
8597           In = BinaryOperator::CreateXor(In, One, "tmp");
8598           InsertNewInstBefore(cast<Instruction>(In), CI);
8599         }
8600           
8601         if (CI.getType() == In->getType())
8602           return ReplaceInstUsesWith(CI, In);
8603         else
8604           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8605       }
8606     }
8607   }
8608
8609   return 0;
8610 }
8611
8612 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8613   // If one of the common conversion will work ..
8614   if (Instruction *Result = commonIntCastTransforms(CI))
8615     return Result;
8616
8617   Value *Src = CI.getOperand(0);
8618
8619   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8620   // types and if the sizes are just right we can convert this into a logical
8621   // 'and' which will be much cheaper than the pair of casts.
8622   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8623     // Get the sizes of the types involved.  We know that the intermediate type
8624     // will be smaller than A or C, but don't know the relation between A and C.
8625     Value *A = CSrc->getOperand(0);
8626     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8627     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8628     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8629     // If we're actually extending zero bits, then if
8630     // SrcSize <  DstSize: zext(a & mask)
8631     // SrcSize == DstSize: a & mask
8632     // SrcSize  > DstSize: trunc(a) & mask
8633     if (SrcSize < DstSize) {
8634       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8635       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8636       Instruction *And =
8637         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8638       InsertNewInstBefore(And, CI);
8639       return new ZExtInst(And, CI.getType());
8640     } else if (SrcSize == DstSize) {
8641       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8642       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8643                                                            AndValue));
8644     } else if (SrcSize > DstSize) {
8645       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8646       InsertNewInstBefore(Trunc, CI);
8647       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8648       return BinaryOperator::CreateAnd(Trunc, 
8649                                        ConstantInt::get(Trunc->getType(),
8650                                                                AndValue));
8651     }
8652   }
8653
8654   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8655     return transformZExtICmp(ICI, CI);
8656
8657   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8658   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8659     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8660     // of the (zext icmp) will be transformed.
8661     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8662     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8663     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8664         (transformZExtICmp(LHS, CI, false) ||
8665          transformZExtICmp(RHS, CI, false))) {
8666       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8667       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8668       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8669     }
8670   }
8671
8672   // zext(trunc(t) & C) -> (t & zext(C)).
8673   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8674     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8675       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8676         Value *TI0 = TI->getOperand(0);
8677         if (TI0->getType() == CI.getType())
8678           return
8679             BinaryOperator::CreateAnd(TI0,
8680                                 Context->getConstantExprZExt(C, CI.getType()));
8681       }
8682
8683   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8684   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8685     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8686       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8687         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8688             And->getOperand(1) == C)
8689           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8690             Value *TI0 = TI->getOperand(0);
8691             if (TI0->getType() == CI.getType()) {
8692               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8693               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8694               InsertNewInstBefore(NewAnd, *And);
8695               return BinaryOperator::CreateXor(NewAnd, ZC);
8696             }
8697           }
8698
8699   return 0;
8700 }
8701
8702 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8703   if (Instruction *I = commonIntCastTransforms(CI))
8704     return I;
8705   
8706   Value *Src = CI.getOperand(0);
8707   
8708   // Canonicalize sign-extend from i1 to a select.
8709   if (Src->getType() == Type::Int1Ty)
8710     return SelectInst::Create(Src,
8711                               Context->getAllOnesValue(CI.getType()),
8712                               Context->getNullValue(CI.getType()));
8713
8714   // See if the value being truncated is already sign extended.  If so, just
8715   // eliminate the trunc/sext pair.
8716   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8717     Value *Op = cast<User>(Src)->getOperand(0);
8718     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8719     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8720     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8721     unsigned NumSignBits = ComputeNumSignBits(Op);
8722
8723     if (OpBits == DestBits) {
8724       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8725       // bits, it is already ready.
8726       if (NumSignBits > DestBits-MidBits)
8727         return ReplaceInstUsesWith(CI, Op);
8728     } else if (OpBits < DestBits) {
8729       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8730       // bits, just sext from i32.
8731       if (NumSignBits > OpBits-MidBits)
8732         return new SExtInst(Op, CI.getType(), "tmp");
8733     } else {
8734       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8735       // bits, just truncate to i32.
8736       if (NumSignBits > OpBits-MidBits)
8737         return new TruncInst(Op, CI.getType(), "tmp");
8738     }
8739   }
8740
8741   // If the input is a shl/ashr pair of a same constant, then this is a sign
8742   // extension from a smaller value.  If we could trust arbitrary bitwidth
8743   // integers, we could turn this into a truncate to the smaller bit and then
8744   // use a sext for the whole extension.  Since we don't, look deeper and check
8745   // for a truncate.  If the source and dest are the same type, eliminate the
8746   // trunc and extend and just do shifts.  For example, turn:
8747   //   %a = trunc i32 %i to i8
8748   //   %b = shl i8 %a, 6
8749   //   %c = ashr i8 %b, 6
8750   //   %d = sext i8 %c to i32
8751   // into:
8752   //   %a = shl i32 %i, 30
8753   //   %d = ashr i32 %a, 30
8754   Value *A = 0;
8755   ConstantInt *BA = 0, *CA = 0;
8756   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8757                         m_ConstantInt(CA)), *Context) &&
8758       BA == CA && isa<TruncInst>(A)) {
8759     Value *I = cast<TruncInst>(A)->getOperand(0);
8760     if (I->getType() == CI.getType()) {
8761       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8762       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8763       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8764       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8765       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8766                                                         CI.getName()), CI);
8767       return BinaryOperator::CreateAShr(I, ShAmtV);
8768     }
8769   }
8770   
8771   return 0;
8772 }
8773
8774 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8775 /// in the specified FP type without changing its value.
8776 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8777                               LLVMContext *Context) {
8778   bool losesInfo;
8779   APFloat F = CFP->getValueAPF();
8780   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8781   if (!losesInfo)
8782     return Context->getConstantFP(F);
8783   return 0;
8784 }
8785
8786 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8787 /// through it until we get the source value.
8788 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8789   if (Instruction *I = dyn_cast<Instruction>(V))
8790     if (I->getOpcode() == Instruction::FPExt)
8791       return LookThroughFPExtensions(I->getOperand(0), Context);
8792   
8793   // If this value is a constant, return the constant in the smallest FP type
8794   // that can accurately represent it.  This allows us to turn
8795   // (float)((double)X+2.0) into x+2.0f.
8796   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8797     if (CFP->getType() == Type::PPC_FP128Ty)
8798       return V;  // No constant folding of this.
8799     // See if the value can be truncated to float and then reextended.
8800     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8801       return V;
8802     if (CFP->getType() == Type::DoubleTy)
8803       return V;  // Won't shrink.
8804     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8805       return V;
8806     // Don't try to shrink to various long double types.
8807   }
8808   
8809   return V;
8810 }
8811
8812 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8813   if (Instruction *I = commonCastTransforms(CI))
8814     return I;
8815   
8816   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8817   // smaller than the destination type, we can eliminate the truncate by doing
8818   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8819   // many builtins (sqrt, etc).
8820   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8821   if (OpI && OpI->hasOneUse()) {
8822     switch (OpI->getOpcode()) {
8823     default: break;
8824     case Instruction::FAdd:
8825     case Instruction::FSub:
8826     case Instruction::FMul:
8827     case Instruction::FDiv:
8828     case Instruction::FRem:
8829       const Type *SrcTy = OpI->getType();
8830       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8831       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8832       if (LHSTrunc->getType() != SrcTy && 
8833           RHSTrunc->getType() != SrcTy) {
8834         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8835         // If the source types were both smaller than the destination type of
8836         // the cast, do this xform.
8837         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8838             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8839           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8840                                       CI.getType(), CI);
8841           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8842                                       CI.getType(), CI);
8843           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8844         }
8845       }
8846       break;  
8847     }
8848   }
8849   return 0;
8850 }
8851
8852 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8853   return commonCastTransforms(CI);
8854 }
8855
8856 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8857   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8858   if (OpI == 0)
8859     return commonCastTransforms(FI);
8860
8861   // fptoui(uitofp(X)) --> X
8862   // fptoui(sitofp(X)) --> X
8863   // This is safe if the intermediate type has enough bits in its mantissa to
8864   // accurately represent all values of X.  For example, do not do this with
8865   // i64->float->i64.  This is also safe for sitofp case, because any negative
8866   // 'X' value would cause an undefined result for the fptoui. 
8867   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8868       OpI->getOperand(0)->getType() == FI.getType() &&
8869       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8870                     OpI->getType()->getFPMantissaWidth())
8871     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8872
8873   return commonCastTransforms(FI);
8874 }
8875
8876 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8877   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8878   if (OpI == 0)
8879     return commonCastTransforms(FI);
8880   
8881   // fptosi(sitofp(X)) --> X
8882   // fptosi(uitofp(X)) --> X
8883   // This is safe if the intermediate type has enough bits in its mantissa to
8884   // accurately represent all values of X.  For example, do not do this with
8885   // i64->float->i64.  This is also safe for sitofp case, because any negative
8886   // 'X' value would cause an undefined result for the fptoui. 
8887   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8888       OpI->getOperand(0)->getType() == FI.getType() &&
8889       (int)FI.getType()->getScalarSizeInBits() <=
8890                     OpI->getType()->getFPMantissaWidth())
8891     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8892   
8893   return commonCastTransforms(FI);
8894 }
8895
8896 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8897   return commonCastTransforms(CI);
8898 }
8899
8900 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8901   return commonCastTransforms(CI);
8902 }
8903
8904 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8905   // If the destination integer type is smaller than the intptr_t type for
8906   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8907   // trunc to be exposed to other transforms.  Don't do this for extending
8908   // ptrtoint's, because we don't know if the target sign or zero extends its
8909   // pointers.
8910   if (TD &&
8911       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8912     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8913                                                     TD->getIntPtrType(),
8914                                                     "tmp"), CI);
8915     return new TruncInst(P, CI.getType());
8916   }
8917   
8918   return commonPointerCastTransforms(CI);
8919 }
8920
8921 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8922   // If the source integer type is larger than the intptr_t type for
8923   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8924   // allows the trunc to be exposed to other transforms.  Don't do this for
8925   // extending inttoptr's, because we don't know if the target sign or zero
8926   // extends to pointers.
8927   if (TD &&
8928       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8929       TD->getPointerSizeInBits()) {
8930     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8931                                                  TD->getIntPtrType(),
8932                                                  "tmp"), CI);
8933     return new IntToPtrInst(P, CI.getType());
8934   }
8935   
8936   if (Instruction *I = commonCastTransforms(CI))
8937     return I;
8938
8939   return 0;
8940 }
8941
8942 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8943   // If the operands are integer typed then apply the integer transforms,
8944   // otherwise just apply the common ones.
8945   Value *Src = CI.getOperand(0);
8946   const Type *SrcTy = Src->getType();
8947   const Type *DestTy = CI.getType();
8948
8949   if (isa<PointerType>(SrcTy)) {
8950     if (Instruction *I = commonPointerCastTransforms(CI))
8951       return I;
8952   } else {
8953     if (Instruction *Result = commonCastTransforms(CI))
8954       return Result;
8955   }
8956
8957
8958   // Get rid of casts from one type to the same type. These are useless and can
8959   // be replaced by the operand.
8960   if (DestTy == Src->getType())
8961     return ReplaceInstUsesWith(CI, Src);
8962
8963   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8964     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8965     const Type *DstElTy = DstPTy->getElementType();
8966     const Type *SrcElTy = SrcPTy->getElementType();
8967     
8968     // If the address spaces don't match, don't eliminate the bitcast, which is
8969     // required for changing types.
8970     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8971       return 0;
8972     
8973     // If we are casting a malloc or alloca to a pointer to a type of the same
8974     // size, rewrite the allocation instruction to allocate the "right" type.
8975     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8976       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8977         return V;
8978     
8979     // If the source and destination are pointers, and this cast is equivalent
8980     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8981     // This can enhance SROA and other transforms that want type-safe pointers.
8982     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
8983     unsigned NumZeros = 0;
8984     while (SrcElTy != DstElTy && 
8985            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8986            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8987       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8988       ++NumZeros;
8989     }
8990
8991     // If we found a path from the src to dest, create the getelementptr now.
8992     if (SrcElTy == DstElTy) {
8993       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8994       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8995                                        ((Instruction*) NULL));
8996     }
8997   }
8998
8999   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9000     if (DestVTy->getNumElements() == 1) {
9001       if (!isa<VectorType>(SrcTy)) {
9002         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9003                                        DestVTy->getElementType(), CI);
9004         return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
9005                                          Context->getNullValue(Type::Int32Ty));
9006       }
9007       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9008     }
9009   }
9010
9011   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9012     if (SrcVTy->getNumElements() == 1) {
9013       if (!isa<VectorType>(DestTy)) {
9014         Instruction *Elem =
9015           ExtractElementInst::Create(Src, Context->getNullValue(Type::Int32Ty));
9016         InsertNewInstBefore(Elem, CI);
9017         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9018       }
9019     }
9020   }
9021
9022   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9023     if (SVI->hasOneUse()) {
9024       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9025       // a bitconvert to a vector with the same # elts.
9026       if (isa<VectorType>(DestTy) && 
9027           cast<VectorType>(DestTy)->getNumElements() ==
9028                 SVI->getType()->getNumElements() &&
9029           SVI->getType()->getNumElements() ==
9030             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9031         CastInst *Tmp;
9032         // If either of the operands is a cast from CI.getType(), then
9033         // evaluating the shuffle in the casted destination's type will allow
9034         // us to eliminate at least one cast.
9035         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9036              Tmp->getOperand(0)->getType() == DestTy) ||
9037             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9038              Tmp->getOperand(0)->getType() == DestTy)) {
9039           Value *LHS = InsertCastBefore(Instruction::BitCast,
9040                                         SVI->getOperand(0), DestTy, CI);
9041           Value *RHS = InsertCastBefore(Instruction::BitCast,
9042                                         SVI->getOperand(1), DestTy, CI);
9043           // Return a new shuffle vector.  Use the same element ID's, as we
9044           // know the vector types match #elts.
9045           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9046         }
9047       }
9048     }
9049   }
9050   return 0;
9051 }
9052
9053 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9054 ///   %C = or %A, %B
9055 ///   %D = select %cond, %C, %A
9056 /// into:
9057 ///   %C = select %cond, %B, 0
9058 ///   %D = or %A, %C
9059 ///
9060 /// Assuming that the specified instruction is an operand to the select, return
9061 /// a bitmask indicating which operands of this instruction are foldable if they
9062 /// equal the other incoming value of the select.
9063 ///
9064 static unsigned GetSelectFoldableOperands(Instruction *I) {
9065   switch (I->getOpcode()) {
9066   case Instruction::Add:
9067   case Instruction::Mul:
9068   case Instruction::And:
9069   case Instruction::Or:
9070   case Instruction::Xor:
9071     return 3;              // Can fold through either operand.
9072   case Instruction::Sub:   // Can only fold on the amount subtracted.
9073   case Instruction::Shl:   // Can only fold on the shift amount.
9074   case Instruction::LShr:
9075   case Instruction::AShr:
9076     return 1;
9077   default:
9078     return 0;              // Cannot fold
9079   }
9080 }
9081
9082 /// GetSelectFoldableConstant - For the same transformation as the previous
9083 /// function, return the identity constant that goes into the select.
9084 static Constant *GetSelectFoldableConstant(Instruction *I,
9085                                            LLVMContext *Context) {
9086   switch (I->getOpcode()) {
9087   default: llvm_unreachable("This cannot happen!");
9088   case Instruction::Add:
9089   case Instruction::Sub:
9090   case Instruction::Or:
9091   case Instruction::Xor:
9092   case Instruction::Shl:
9093   case Instruction::LShr:
9094   case Instruction::AShr:
9095     return Context->getNullValue(I->getType());
9096   case Instruction::And:
9097     return Context->getAllOnesValue(I->getType());
9098   case Instruction::Mul:
9099     return ConstantInt::get(I->getType(), 1);
9100   }
9101 }
9102
9103 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9104 /// have the same opcode and only one use each.  Try to simplify this.
9105 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9106                                           Instruction *FI) {
9107   if (TI->getNumOperands() == 1) {
9108     // If this is a non-volatile load or a cast from the same type,
9109     // merge.
9110     if (TI->isCast()) {
9111       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9112         return 0;
9113     } else {
9114       return 0;  // unknown unary op.
9115     }
9116
9117     // Fold this by inserting a select from the input values.
9118     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9119                                           FI->getOperand(0), SI.getName()+".v");
9120     InsertNewInstBefore(NewSI, SI);
9121     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9122                             TI->getType());
9123   }
9124
9125   // Only handle binary operators here.
9126   if (!isa<BinaryOperator>(TI))
9127     return 0;
9128
9129   // Figure out if the operations have any operands in common.
9130   Value *MatchOp, *OtherOpT, *OtherOpF;
9131   bool MatchIsOpZero;
9132   if (TI->getOperand(0) == FI->getOperand(0)) {
9133     MatchOp  = TI->getOperand(0);
9134     OtherOpT = TI->getOperand(1);
9135     OtherOpF = FI->getOperand(1);
9136     MatchIsOpZero = true;
9137   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9138     MatchOp  = TI->getOperand(1);
9139     OtherOpT = TI->getOperand(0);
9140     OtherOpF = FI->getOperand(0);
9141     MatchIsOpZero = false;
9142   } else if (!TI->isCommutative()) {
9143     return 0;
9144   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9145     MatchOp  = TI->getOperand(0);
9146     OtherOpT = TI->getOperand(1);
9147     OtherOpF = FI->getOperand(0);
9148     MatchIsOpZero = true;
9149   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9150     MatchOp  = TI->getOperand(1);
9151     OtherOpT = TI->getOperand(0);
9152     OtherOpF = FI->getOperand(1);
9153     MatchIsOpZero = true;
9154   } else {
9155     return 0;
9156   }
9157
9158   // If we reach here, they do have operations in common.
9159   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9160                                          OtherOpF, SI.getName()+".v");
9161   InsertNewInstBefore(NewSI, SI);
9162
9163   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9164     if (MatchIsOpZero)
9165       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9166     else
9167       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9168   }
9169   llvm_unreachable("Shouldn't get here");
9170   return 0;
9171 }
9172
9173 static bool isSelect01(Constant *C1, Constant *C2) {
9174   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9175   if (!C1I)
9176     return false;
9177   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9178   if (!C2I)
9179     return false;
9180   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9181 }
9182
9183 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9184 /// facilitate further optimization.
9185 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9186                                             Value *FalseVal) {
9187   // See the comment above GetSelectFoldableOperands for a description of the
9188   // transformation we are doing here.
9189   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9190     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9191         !isa<Constant>(FalseVal)) {
9192       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9193         unsigned OpToFold = 0;
9194         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9195           OpToFold = 1;
9196         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9197           OpToFold = 2;
9198         }
9199
9200         if (OpToFold) {
9201           Constant *C = GetSelectFoldableConstant(TVI, Context);
9202           Value *OOp = TVI->getOperand(2-OpToFold);
9203           // Avoid creating select between 2 constants unless it's selecting
9204           // between 0 and 1.
9205           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9206             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9207             InsertNewInstBefore(NewSel, SI);
9208             NewSel->takeName(TVI);
9209             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9210               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9211             llvm_unreachable("Unknown instruction!!");
9212           }
9213         }
9214       }
9215     }
9216   }
9217
9218   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9219     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9220         !isa<Constant>(TrueVal)) {
9221       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9222         unsigned OpToFold = 0;
9223         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9224           OpToFold = 1;
9225         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9226           OpToFold = 2;
9227         }
9228
9229         if (OpToFold) {
9230           Constant *C = GetSelectFoldableConstant(FVI, Context);
9231           Value *OOp = FVI->getOperand(2-OpToFold);
9232           // Avoid creating select between 2 constants unless it's selecting
9233           // between 0 and 1.
9234           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9235             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9236             InsertNewInstBefore(NewSel, SI);
9237             NewSel->takeName(FVI);
9238             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9239               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9240             llvm_unreachable("Unknown instruction!!");
9241           }
9242         }
9243       }
9244     }
9245   }
9246
9247   return 0;
9248 }
9249
9250 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9251 /// ICmpInst as its first operand.
9252 ///
9253 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9254                                                    ICmpInst *ICI) {
9255   bool Changed = false;
9256   ICmpInst::Predicate Pred = ICI->getPredicate();
9257   Value *CmpLHS = ICI->getOperand(0);
9258   Value *CmpRHS = ICI->getOperand(1);
9259   Value *TrueVal = SI.getTrueValue();
9260   Value *FalseVal = SI.getFalseValue();
9261
9262   // Check cases where the comparison is with a constant that
9263   // can be adjusted to fit the min/max idiom. We may edit ICI in
9264   // place here, so make sure the select is the only user.
9265   if (ICI->hasOneUse())
9266     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9267       switch (Pred) {
9268       default: break;
9269       case ICmpInst::ICMP_ULT:
9270       case ICmpInst::ICMP_SLT: {
9271         // X < MIN ? T : F  -->  F
9272         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9273           return ReplaceInstUsesWith(SI, FalseVal);
9274         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9275         Constant *AdjustedRHS = SubOne(CI, Context);
9276         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9277             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9278           Pred = ICmpInst::getSwappedPredicate(Pred);
9279           CmpRHS = AdjustedRHS;
9280           std::swap(FalseVal, TrueVal);
9281           ICI->setPredicate(Pred);
9282           ICI->setOperand(1, CmpRHS);
9283           SI.setOperand(1, TrueVal);
9284           SI.setOperand(2, FalseVal);
9285           Changed = true;
9286         }
9287         break;
9288       }
9289       case ICmpInst::ICMP_UGT:
9290       case ICmpInst::ICMP_SGT: {
9291         // X > MAX ? T : F  -->  F
9292         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9293           return ReplaceInstUsesWith(SI, FalseVal);
9294         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9295         Constant *AdjustedRHS = AddOne(CI, Context);
9296         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9297             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9298           Pred = ICmpInst::getSwappedPredicate(Pred);
9299           CmpRHS = AdjustedRHS;
9300           std::swap(FalseVal, TrueVal);
9301           ICI->setPredicate(Pred);
9302           ICI->setOperand(1, CmpRHS);
9303           SI.setOperand(1, TrueVal);
9304           SI.setOperand(2, FalseVal);
9305           Changed = true;
9306         }
9307         break;
9308       }
9309       }
9310
9311       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9312       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9313       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9314       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9315           match(FalseVal, m_ConstantInt<0>(), *Context))
9316         Pred = ICI->getPredicate();
9317       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9318                match(FalseVal, m_ConstantInt<-1>(), *Context))
9319         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9320       
9321       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9322         // If we are just checking for a icmp eq of a single bit and zext'ing it
9323         // to an integer, then shift the bit to the appropriate place and then
9324         // cast to integer to avoid the comparison.
9325         const APInt &Op1CV = CI->getValue();
9326     
9327         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9328         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9329         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9330             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9331           Value *In = ICI->getOperand(0);
9332           Value *Sh = ConstantInt::get(In->getType(),
9333                                        In->getType()->getScalarSizeInBits()-1);
9334           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9335                                                         In->getName()+".lobit"),
9336                                    *ICI);
9337           if (In->getType() != SI.getType())
9338             In = CastInst::CreateIntegerCast(In, SI.getType(),
9339                                              true/*SExt*/, "tmp", ICI);
9340     
9341           if (Pred == ICmpInst::ICMP_SGT)
9342             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9343                                        In->getName()+".not"), *ICI);
9344     
9345           return ReplaceInstUsesWith(SI, In);
9346         }
9347       }
9348     }
9349
9350   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9351     // Transform (X == Y) ? X : Y  -> Y
9352     if (Pred == ICmpInst::ICMP_EQ)
9353       return ReplaceInstUsesWith(SI, FalseVal);
9354     // Transform (X != Y) ? X : Y  -> X
9355     if (Pred == ICmpInst::ICMP_NE)
9356       return ReplaceInstUsesWith(SI, TrueVal);
9357     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9358
9359   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9360     // Transform (X == Y) ? Y : X  -> X
9361     if (Pred == ICmpInst::ICMP_EQ)
9362       return ReplaceInstUsesWith(SI, FalseVal);
9363     // Transform (X != Y) ? Y : X  -> Y
9364     if (Pred == ICmpInst::ICMP_NE)
9365       return ReplaceInstUsesWith(SI, TrueVal);
9366     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9367   }
9368
9369   /// NOTE: if we wanted to, this is where to detect integer ABS
9370
9371   return Changed ? &SI : 0;
9372 }
9373
9374 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9375   Value *CondVal = SI.getCondition();
9376   Value *TrueVal = SI.getTrueValue();
9377   Value *FalseVal = SI.getFalseValue();
9378
9379   // select true, X, Y  -> X
9380   // select false, X, Y -> Y
9381   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9382     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9383
9384   // select C, X, X -> X
9385   if (TrueVal == FalseVal)
9386     return ReplaceInstUsesWith(SI, TrueVal);
9387
9388   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9389     return ReplaceInstUsesWith(SI, FalseVal);
9390   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9391     return ReplaceInstUsesWith(SI, TrueVal);
9392   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9393     if (isa<Constant>(TrueVal))
9394       return ReplaceInstUsesWith(SI, TrueVal);
9395     else
9396       return ReplaceInstUsesWith(SI, FalseVal);
9397   }
9398
9399   if (SI.getType() == Type::Int1Ty) {
9400     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9401       if (C->getZExtValue()) {
9402         // Change: A = select B, true, C --> A = or B, C
9403         return BinaryOperator::CreateOr(CondVal, FalseVal);
9404       } else {
9405         // Change: A = select B, false, C --> A = and !B, C
9406         Value *NotCond =
9407           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9408                                              "not."+CondVal->getName()), SI);
9409         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9410       }
9411     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9412       if (C->getZExtValue() == false) {
9413         // Change: A = select B, C, false --> A = and B, C
9414         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9415       } else {
9416         // Change: A = select B, C, true --> A = or !B, C
9417         Value *NotCond =
9418           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9419                                              "not."+CondVal->getName()), SI);
9420         return BinaryOperator::CreateOr(NotCond, TrueVal);
9421       }
9422     }
9423     
9424     // select a, b, a  -> a&b
9425     // select a, a, b  -> a|b
9426     if (CondVal == TrueVal)
9427       return BinaryOperator::CreateOr(CondVal, FalseVal);
9428     else if (CondVal == FalseVal)
9429       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9430   }
9431
9432   // Selecting between two integer constants?
9433   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9434     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9435       // select C, 1, 0 -> zext C to int
9436       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9437         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9438       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9439         // select C, 0, 1 -> zext !C to int
9440         Value *NotCond =
9441           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9442                                                "not."+CondVal->getName()), SI);
9443         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9444       }
9445
9446       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9447         // If one of the constants is zero (we know they can't both be) and we
9448         // have an icmp instruction with zero, and we have an 'and' with the
9449         // non-constant value, eliminate this whole mess.  This corresponds to
9450         // cases like this: ((X & 27) ? 27 : 0)
9451         if (TrueValC->isZero() || FalseValC->isZero())
9452           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9453               cast<Constant>(IC->getOperand(1))->isNullValue())
9454             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9455               if (ICA->getOpcode() == Instruction::And &&
9456                   isa<ConstantInt>(ICA->getOperand(1)) &&
9457                   (ICA->getOperand(1) == TrueValC ||
9458                    ICA->getOperand(1) == FalseValC) &&
9459                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9460                 // Okay, now we know that everything is set up, we just don't
9461                 // know whether we have a icmp_ne or icmp_eq and whether the 
9462                 // true or false val is the zero.
9463                 bool ShouldNotVal = !TrueValC->isZero();
9464                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9465                 Value *V = ICA;
9466                 if (ShouldNotVal)
9467                   V = InsertNewInstBefore(BinaryOperator::Create(
9468                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9469                 return ReplaceInstUsesWith(SI, V);
9470               }
9471       }
9472     }
9473
9474   // See if we are selecting two values based on a comparison of the two values.
9475   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9476     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9477       // Transform (X == Y) ? X : Y  -> Y
9478       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9479         // This is not safe in general for floating point:  
9480         // consider X== -0, Y== +0.
9481         // It becomes safe if either operand is a nonzero constant.
9482         ConstantFP *CFPt, *CFPf;
9483         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9484               !CFPt->getValueAPF().isZero()) ||
9485             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9486              !CFPf->getValueAPF().isZero()))
9487         return ReplaceInstUsesWith(SI, FalseVal);
9488       }
9489       // Transform (X != Y) ? X : Y  -> X
9490       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9491         return ReplaceInstUsesWith(SI, TrueVal);
9492       // NOTE: if we wanted to, this is where to detect MIN/MAX
9493
9494     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9495       // Transform (X == Y) ? Y : X  -> X
9496       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9497         // This is not safe in general for floating point:  
9498         // consider X== -0, Y== +0.
9499         // It becomes safe if either operand is a nonzero constant.
9500         ConstantFP *CFPt, *CFPf;
9501         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9502               !CFPt->getValueAPF().isZero()) ||
9503             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9504              !CFPf->getValueAPF().isZero()))
9505           return ReplaceInstUsesWith(SI, FalseVal);
9506       }
9507       // Transform (X != Y) ? Y : X  -> Y
9508       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9509         return ReplaceInstUsesWith(SI, TrueVal);
9510       // NOTE: if we wanted to, this is where to detect MIN/MAX
9511     }
9512     // NOTE: if we wanted to, this is where to detect ABS
9513   }
9514
9515   // See if we are selecting two values based on a comparison of the two values.
9516   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9517     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9518       return Result;
9519
9520   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9521     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9522       if (TI->hasOneUse() && FI->hasOneUse()) {
9523         Instruction *AddOp = 0, *SubOp = 0;
9524
9525         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9526         if (TI->getOpcode() == FI->getOpcode())
9527           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9528             return IV;
9529
9530         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9531         // even legal for FP.
9532         if ((TI->getOpcode() == Instruction::Sub &&
9533              FI->getOpcode() == Instruction::Add) ||
9534             (TI->getOpcode() == Instruction::FSub &&
9535              FI->getOpcode() == Instruction::FAdd)) {
9536           AddOp = FI; SubOp = TI;
9537         } else if ((FI->getOpcode() == Instruction::Sub &&
9538                     TI->getOpcode() == Instruction::Add) ||
9539                    (FI->getOpcode() == Instruction::FSub &&
9540                     TI->getOpcode() == Instruction::FAdd)) {
9541           AddOp = TI; SubOp = FI;
9542         }
9543
9544         if (AddOp) {
9545           Value *OtherAddOp = 0;
9546           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9547             OtherAddOp = AddOp->getOperand(1);
9548           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9549             OtherAddOp = AddOp->getOperand(0);
9550           }
9551
9552           if (OtherAddOp) {
9553             // So at this point we know we have (Y -> OtherAddOp):
9554             //        select C, (add X, Y), (sub X, Z)
9555             Value *NegVal;  // Compute -Z
9556             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9557               NegVal = Context->getConstantExprNeg(C);
9558             } else {
9559               NegVal = InsertNewInstBefore(
9560                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9561                                               "tmp"), SI);
9562             }
9563
9564             Value *NewTrueOp = OtherAddOp;
9565             Value *NewFalseOp = NegVal;
9566             if (AddOp != TI)
9567               std::swap(NewTrueOp, NewFalseOp);
9568             Instruction *NewSel =
9569               SelectInst::Create(CondVal, NewTrueOp,
9570                                  NewFalseOp, SI.getName() + ".p");
9571
9572             NewSel = InsertNewInstBefore(NewSel, SI);
9573             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9574           }
9575         }
9576       }
9577
9578   // See if we can fold the select into one of our operands.
9579   if (SI.getType()->isInteger()) {
9580     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9581     if (FoldI)
9582       return FoldI;
9583   }
9584
9585   if (BinaryOperator::isNot(CondVal)) {
9586     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9587     SI.setOperand(1, FalseVal);
9588     SI.setOperand(2, TrueVal);
9589     return &SI;
9590   }
9591
9592   return 0;
9593 }
9594
9595 /// EnforceKnownAlignment - If the specified pointer points to an object that
9596 /// we control, modify the object's alignment to PrefAlign. This isn't
9597 /// often possible though. If alignment is important, a more reliable approach
9598 /// is to simply align all global variables and allocation instructions to
9599 /// their preferred alignment from the beginning.
9600 ///
9601 static unsigned EnforceKnownAlignment(Value *V,
9602                                       unsigned Align, unsigned PrefAlign) {
9603
9604   User *U = dyn_cast<User>(V);
9605   if (!U) return Align;
9606
9607   switch (Operator::getOpcode(U)) {
9608   default: break;
9609   case Instruction::BitCast:
9610     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9611   case Instruction::GetElementPtr: {
9612     // If all indexes are zero, it is just the alignment of the base pointer.
9613     bool AllZeroOperands = true;
9614     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9615       if (!isa<Constant>(*i) ||
9616           !cast<Constant>(*i)->isNullValue()) {
9617         AllZeroOperands = false;
9618         break;
9619       }
9620
9621     if (AllZeroOperands) {
9622       // Treat this like a bitcast.
9623       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9624     }
9625     break;
9626   }
9627   }
9628
9629   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9630     // If there is a large requested alignment and we can, bump up the alignment
9631     // of the global.
9632     if (!GV->isDeclaration()) {
9633       if (GV->getAlignment() >= PrefAlign)
9634         Align = GV->getAlignment();
9635       else {
9636         GV->setAlignment(PrefAlign);
9637         Align = PrefAlign;
9638       }
9639     }
9640   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9641     // If there is a requested alignment and if this is an alloca, round up.  We
9642     // don't do this for malloc, because some systems can't respect the request.
9643     if (isa<AllocaInst>(AI)) {
9644       if (AI->getAlignment() >= PrefAlign)
9645         Align = AI->getAlignment();
9646       else {
9647         AI->setAlignment(PrefAlign);
9648         Align = PrefAlign;
9649       }
9650     }
9651   }
9652
9653   return Align;
9654 }
9655
9656 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9657 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9658 /// and it is more than the alignment of the ultimate object, see if we can
9659 /// increase the alignment of the ultimate object, making this check succeed.
9660 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9661                                                   unsigned PrefAlign) {
9662   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9663                       sizeof(PrefAlign) * CHAR_BIT;
9664   APInt Mask = APInt::getAllOnesValue(BitWidth);
9665   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9666   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9667   unsigned TrailZ = KnownZero.countTrailingOnes();
9668   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9669
9670   if (PrefAlign > Align)
9671     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9672   
9673     // We don't need to make any adjustment.
9674   return Align;
9675 }
9676
9677 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9678   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9679   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9680   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9681   unsigned CopyAlign = MI->getAlignment();
9682
9683   if (CopyAlign < MinAlign) {
9684     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9685                                              MinAlign, false));
9686     return MI;
9687   }
9688   
9689   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9690   // load/store.
9691   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9692   if (MemOpLength == 0) return 0;
9693   
9694   // Source and destination pointer types are always "i8*" for intrinsic.  See
9695   // if the size is something we can handle with a single primitive load/store.
9696   // A single load+store correctly handles overlapping memory in the memmove
9697   // case.
9698   unsigned Size = MemOpLength->getZExtValue();
9699   if (Size == 0) return MI;  // Delete this mem transfer.
9700   
9701   if (Size > 8 || (Size&(Size-1)))
9702     return 0;  // If not 1/2/4/8 bytes, exit.
9703   
9704   // Use an integer load+store unless we can find something better.
9705   Type *NewPtrTy =
9706                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9707   
9708   // Memcpy forces the use of i8* for the source and destination.  That means
9709   // that if you're using memcpy to move one double around, you'll get a cast
9710   // from double* to i8*.  We'd much rather use a double load+store rather than
9711   // an i64 load+store, here because this improves the odds that the source or
9712   // dest address will be promotable.  See if we can find a better type than the
9713   // integer datatype.
9714   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9715     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9716     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9717       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9718       // down through these levels if so.
9719       while (!SrcETy->isSingleValueType()) {
9720         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9721           if (STy->getNumElements() == 1)
9722             SrcETy = STy->getElementType(0);
9723           else
9724             break;
9725         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9726           if (ATy->getNumElements() == 1)
9727             SrcETy = ATy->getElementType();
9728           else
9729             break;
9730         } else
9731           break;
9732       }
9733       
9734       if (SrcETy->isSingleValueType())
9735         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9736     }
9737   }
9738   
9739   
9740   // If the memcpy/memmove provides better alignment info than we can
9741   // infer, use it.
9742   SrcAlign = std::max(SrcAlign, CopyAlign);
9743   DstAlign = std::max(DstAlign, CopyAlign);
9744   
9745   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9746   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9747   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9748   InsertNewInstBefore(L, *MI);
9749   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9750
9751   // Set the size of the copy to 0, it will be deleted on the next iteration.
9752   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9753   return MI;
9754 }
9755
9756 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9757   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9758   if (MI->getAlignment() < Alignment) {
9759     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9760                                              Alignment, false));
9761     return MI;
9762   }
9763   
9764   // Extract the length and alignment and fill if they are constant.
9765   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9766   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9767   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9768     return 0;
9769   uint64_t Len = LenC->getZExtValue();
9770   Alignment = MI->getAlignment();
9771   
9772   // If the length is zero, this is a no-op
9773   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9774   
9775   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9776   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9777     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9778     
9779     Value *Dest = MI->getDest();
9780     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9781
9782     // Alignment 0 is identity for alignment 1 for memset, but not store.
9783     if (Alignment == 0) Alignment = 1;
9784     
9785     // Extract the fill value and store.
9786     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9787     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9788                                       Dest, false, Alignment), *MI);
9789     
9790     // Set the size of the copy to 0, it will be deleted on the next iteration.
9791     MI->setLength(Context->getNullValue(LenC->getType()));
9792     return MI;
9793   }
9794
9795   return 0;
9796 }
9797
9798
9799 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9800 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9801 /// the heavy lifting.
9802 ///
9803 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9804   // If the caller function is nounwind, mark the call as nounwind, even if the
9805   // callee isn't.
9806   if (CI.getParent()->getParent()->doesNotThrow() &&
9807       !CI.doesNotThrow()) {
9808     CI.setDoesNotThrow();
9809     return &CI;
9810   }
9811   
9812   
9813   
9814   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9815   if (!II) return visitCallSite(&CI);
9816   
9817   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9818   // visitCallSite.
9819   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9820     bool Changed = false;
9821
9822     // memmove/cpy/set of zero bytes is a noop.
9823     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9824       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9825
9826       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9827         if (CI->getZExtValue() == 1) {
9828           // Replace the instruction with just byte operations.  We would
9829           // transform other cases to loads/stores, but we don't know if
9830           // alignment is sufficient.
9831         }
9832     }
9833
9834     // If we have a memmove and the source operation is a constant global,
9835     // then the source and dest pointers can't alias, so we can change this
9836     // into a call to memcpy.
9837     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9838       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9839         if (GVSrc->isConstant()) {
9840           Module *M = CI.getParent()->getParent()->getParent();
9841           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9842           const Type *Tys[1];
9843           Tys[0] = CI.getOperand(3)->getType();
9844           CI.setOperand(0, 
9845                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9846           Changed = true;
9847         }
9848
9849       // memmove(x,x,size) -> noop.
9850       if (MMI->getSource() == MMI->getDest())
9851         return EraseInstFromFunction(CI);
9852     }
9853
9854     // If we can determine a pointer alignment that is bigger than currently
9855     // set, update the alignment.
9856     if (isa<MemTransferInst>(MI)) {
9857       if (Instruction *I = SimplifyMemTransfer(MI))
9858         return I;
9859     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9860       if (Instruction *I = SimplifyMemSet(MSI))
9861         return I;
9862     }
9863           
9864     if (Changed) return II;
9865   }
9866   
9867   switch (II->getIntrinsicID()) {
9868   default: break;
9869   case Intrinsic::bswap:
9870     // bswap(bswap(x)) -> x
9871     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9872       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9873         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9874     break;
9875   case Intrinsic::ppc_altivec_lvx:
9876   case Intrinsic::ppc_altivec_lvxl:
9877   case Intrinsic::x86_sse_loadu_ps:
9878   case Intrinsic::x86_sse2_loadu_pd:
9879   case Intrinsic::x86_sse2_loadu_dq:
9880     // Turn PPC lvx     -> load if the pointer is known aligned.
9881     // Turn X86 loadups -> load if the pointer is known aligned.
9882     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9883       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9884                                    Context->getPointerTypeUnqual(II->getType()),
9885                                        CI);
9886       return new LoadInst(Ptr);
9887     }
9888     break;
9889   case Intrinsic::ppc_altivec_stvx:
9890   case Intrinsic::ppc_altivec_stvxl:
9891     // Turn stvx -> store if the pointer is known aligned.
9892     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9893       const Type *OpPtrTy = 
9894         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9895       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9896       return new StoreInst(II->getOperand(1), Ptr);
9897     }
9898     break;
9899   case Intrinsic::x86_sse_storeu_ps:
9900   case Intrinsic::x86_sse2_storeu_pd:
9901   case Intrinsic::x86_sse2_storeu_dq:
9902     // Turn X86 storeu -> store if the pointer is known aligned.
9903     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9904       const Type *OpPtrTy = 
9905         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9906       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9907       return new StoreInst(II->getOperand(2), Ptr);
9908     }
9909     break;
9910     
9911   case Intrinsic::x86_sse_cvttss2si: {
9912     // These intrinsics only demands the 0th element of its input vector.  If
9913     // we can simplify the input based on that, do so now.
9914     unsigned VWidth =
9915       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9916     APInt DemandedElts(VWidth, 1);
9917     APInt UndefElts(VWidth, 0);
9918     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9919                                               UndefElts)) {
9920       II->setOperand(1, V);
9921       return II;
9922     }
9923     break;
9924   }
9925     
9926   case Intrinsic::ppc_altivec_vperm:
9927     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9928     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9929       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9930       
9931       // Check that all of the elements are integer constants or undefs.
9932       bool AllEltsOk = true;
9933       for (unsigned i = 0; i != 16; ++i) {
9934         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9935             !isa<UndefValue>(Mask->getOperand(i))) {
9936           AllEltsOk = false;
9937           break;
9938         }
9939       }
9940       
9941       if (AllEltsOk) {
9942         // Cast the input vectors to byte vectors.
9943         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9944         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9945         Value *Result = Context->getUndef(Op0->getType());
9946         
9947         // Only extract each element once.
9948         Value *ExtractedElts[32];
9949         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9950         
9951         for (unsigned i = 0; i != 16; ++i) {
9952           if (isa<UndefValue>(Mask->getOperand(i)))
9953             continue;
9954           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9955           Idx &= 31;  // Match the hardware behavior.
9956           
9957           if (ExtractedElts[Idx] == 0) {
9958             Instruction *Elt = 
9959               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9960                   ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
9961             InsertNewInstBefore(Elt, CI);
9962             ExtractedElts[Idx] = Elt;
9963           }
9964         
9965           // Insert this value into the result vector.
9966           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9967                                ConstantInt::get(Type::Int32Ty, i, false), 
9968                                "tmp");
9969           InsertNewInstBefore(cast<Instruction>(Result), CI);
9970         }
9971         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9972       }
9973     }
9974     break;
9975
9976   case Intrinsic::stackrestore: {
9977     // If the save is right next to the restore, remove the restore.  This can
9978     // happen when variable allocas are DCE'd.
9979     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9980       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9981         BasicBlock::iterator BI = SS;
9982         if (&*++BI == II)
9983           return EraseInstFromFunction(CI);
9984       }
9985     }
9986     
9987     // Scan down this block to see if there is another stack restore in the
9988     // same block without an intervening call/alloca.
9989     BasicBlock::iterator BI = II;
9990     TerminatorInst *TI = II->getParent()->getTerminator();
9991     bool CannotRemove = false;
9992     for (++BI; &*BI != TI; ++BI) {
9993       if (isa<AllocaInst>(BI)) {
9994         CannotRemove = true;
9995         break;
9996       }
9997       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9998         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9999           // If there is a stackrestore below this one, remove this one.
10000           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10001             return EraseInstFromFunction(CI);
10002           // Otherwise, ignore the intrinsic.
10003         } else {
10004           // If we found a non-intrinsic call, we can't remove the stack
10005           // restore.
10006           CannotRemove = true;
10007           break;
10008         }
10009       }
10010     }
10011     
10012     // If the stack restore is in a return/unwind block and if there are no
10013     // allocas or calls between the restore and the return, nuke the restore.
10014     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10015       return EraseInstFromFunction(CI);
10016     break;
10017   }
10018   }
10019
10020   return visitCallSite(II);
10021 }
10022
10023 // InvokeInst simplification
10024 //
10025 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10026   return visitCallSite(&II);
10027 }
10028
10029 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10030 /// passed through the varargs area, we can eliminate the use of the cast.
10031 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10032                                          const CastInst * const CI,
10033                                          const TargetData * const TD,
10034                                          const int ix) {
10035   if (!CI->isLosslessCast())
10036     return false;
10037
10038   // The size of ByVal arguments is derived from the type, so we
10039   // can't change to a type with a different size.  If the size were
10040   // passed explicitly we could avoid this check.
10041   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10042     return true;
10043
10044   const Type* SrcTy = 
10045             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10046   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10047   if (!SrcTy->isSized() || !DstTy->isSized())
10048     return false;
10049   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10050     return false;
10051   return true;
10052 }
10053
10054 // visitCallSite - Improvements for call and invoke instructions.
10055 //
10056 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10057   bool Changed = false;
10058
10059   // If the callee is a constexpr cast of a function, attempt to move the cast
10060   // to the arguments of the call/invoke.
10061   if (transformConstExprCastCall(CS)) return 0;
10062
10063   Value *Callee = CS.getCalledValue();
10064
10065   if (Function *CalleeF = dyn_cast<Function>(Callee))
10066     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10067       Instruction *OldCall = CS.getInstruction();
10068       // If the call and callee calling conventions don't match, this call must
10069       // be unreachable, as the call is undefined.
10070       new StoreInst(Context->getTrue(),
10071                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10072                                   OldCall);
10073       if (!OldCall->use_empty())
10074         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10075       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10076         return EraseInstFromFunction(*OldCall);
10077       return 0;
10078     }
10079
10080   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10081     // This instruction is not reachable, just remove it.  We insert a store to
10082     // undef so that we know that this code is not reachable, despite the fact
10083     // that we can't modify the CFG here.
10084     new StoreInst(Context->getTrue(),
10085                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10086                   CS.getInstruction());
10087
10088     if (!CS.getInstruction()->use_empty())
10089       CS.getInstruction()->
10090         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10091
10092     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10093       // Don't break the CFG, insert a dummy cond branch.
10094       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10095                          Context->getTrue(), II);
10096     }
10097     return EraseInstFromFunction(*CS.getInstruction());
10098   }
10099
10100   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10101     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10102       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10103         return transformCallThroughTrampoline(CS);
10104
10105   const PointerType *PTy = cast<PointerType>(Callee->getType());
10106   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10107   if (FTy->isVarArg()) {
10108     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10109     // See if we can optimize any arguments passed through the varargs area of
10110     // the call.
10111     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10112            E = CS.arg_end(); I != E; ++I, ++ix) {
10113       CastInst *CI = dyn_cast<CastInst>(*I);
10114       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10115         *I = CI->getOperand(0);
10116         Changed = true;
10117       }
10118     }
10119   }
10120
10121   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10122     // Inline asm calls cannot throw - mark them 'nounwind'.
10123     CS.setDoesNotThrow();
10124     Changed = true;
10125   }
10126
10127   return Changed ? CS.getInstruction() : 0;
10128 }
10129
10130 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10131 // attempt to move the cast to the arguments of the call/invoke.
10132 //
10133 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10134   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10135   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10136   if (CE->getOpcode() != Instruction::BitCast || 
10137       !isa<Function>(CE->getOperand(0)))
10138     return false;
10139   Function *Callee = cast<Function>(CE->getOperand(0));
10140   Instruction *Caller = CS.getInstruction();
10141   const AttrListPtr &CallerPAL = CS.getAttributes();
10142
10143   // Okay, this is a cast from a function to a different type.  Unless doing so
10144   // would cause a type conversion of one of our arguments, change this call to
10145   // be a direct call with arguments casted to the appropriate types.
10146   //
10147   const FunctionType *FT = Callee->getFunctionType();
10148   const Type *OldRetTy = Caller->getType();
10149   const Type *NewRetTy = FT->getReturnType();
10150
10151   if (isa<StructType>(NewRetTy))
10152     return false; // TODO: Handle multiple return values.
10153
10154   // Check to see if we are changing the return type...
10155   if (OldRetTy != NewRetTy) {
10156     if (Callee->isDeclaration() &&
10157         // Conversion is ok if changing from one pointer type to another or from
10158         // a pointer to an integer of the same size.
10159         !((isa<PointerType>(OldRetTy) || !TD ||
10160            OldRetTy == TD->getIntPtrType()) &&
10161           (isa<PointerType>(NewRetTy) || !TD ||
10162            NewRetTy == TD->getIntPtrType())))
10163       return false;   // Cannot transform this return value.
10164
10165     if (!Caller->use_empty() &&
10166         // void -> non-void is handled specially
10167         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10168       return false;   // Cannot transform this return value.
10169
10170     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10171       Attributes RAttrs = CallerPAL.getRetAttributes();
10172       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10173         return false;   // Attribute not compatible with transformed value.
10174     }
10175
10176     // If the callsite is an invoke instruction, and the return value is used by
10177     // a PHI node in a successor, we cannot change the return type of the call
10178     // because there is no place to put the cast instruction (without breaking
10179     // the critical edge).  Bail out in this case.
10180     if (!Caller->use_empty())
10181       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10182         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10183              UI != E; ++UI)
10184           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10185             if (PN->getParent() == II->getNormalDest() ||
10186                 PN->getParent() == II->getUnwindDest())
10187               return false;
10188   }
10189
10190   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10191   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10192
10193   CallSite::arg_iterator AI = CS.arg_begin();
10194   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10195     const Type *ParamTy = FT->getParamType(i);
10196     const Type *ActTy = (*AI)->getType();
10197
10198     if (!CastInst::isCastable(ActTy, ParamTy))
10199       return false;   // Cannot transform this parameter value.
10200
10201     if (CallerPAL.getParamAttributes(i + 1) 
10202         & Attribute::typeIncompatible(ParamTy))
10203       return false;   // Attribute not compatible with transformed value.
10204
10205     // Converting from one pointer type to another or between a pointer and an
10206     // integer of the same size is safe even if we do not have a body.
10207     bool isConvertible = ActTy == ParamTy ||
10208       (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10209               (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10210     if (Callee->isDeclaration() && !isConvertible) return false;
10211   }
10212
10213   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10214       Callee->isDeclaration())
10215     return false;   // Do not delete arguments unless we have a function body.
10216
10217   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10218       !CallerPAL.isEmpty())
10219     // In this case we have more arguments than the new function type, but we
10220     // won't be dropping them.  Check that these extra arguments have attributes
10221     // that are compatible with being a vararg call argument.
10222     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10223       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10224         break;
10225       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10226       if (PAttrs & Attribute::VarArgsIncompatible)
10227         return false;
10228     }
10229
10230   // Okay, we decided that this is a safe thing to do: go ahead and start
10231   // inserting cast instructions as necessary...
10232   std::vector<Value*> Args;
10233   Args.reserve(NumActualArgs);
10234   SmallVector<AttributeWithIndex, 8> attrVec;
10235   attrVec.reserve(NumCommonArgs);
10236
10237   // Get any return attributes.
10238   Attributes RAttrs = CallerPAL.getRetAttributes();
10239
10240   // If the return value is not being used, the type may not be compatible
10241   // with the existing attributes.  Wipe out any problematic attributes.
10242   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10243
10244   // Add the new return attributes.
10245   if (RAttrs)
10246     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10247
10248   AI = CS.arg_begin();
10249   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10250     const Type *ParamTy = FT->getParamType(i);
10251     if ((*AI)->getType() == ParamTy) {
10252       Args.push_back(*AI);
10253     } else {
10254       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10255           false, ParamTy, false);
10256       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10257       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10258     }
10259
10260     // Add any parameter attributes.
10261     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10262       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10263   }
10264
10265   // If the function takes more arguments than the call was taking, add them
10266   // now...
10267   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10268     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10269
10270   // If we are removing arguments to the function, emit an obnoxious warning...
10271   if (FT->getNumParams() < NumActualArgs) {
10272     if (!FT->isVarArg()) {
10273       errs() << "WARNING: While resolving call to function '"
10274              << Callee->getName() << "' arguments were dropped!\n";
10275     } else {
10276       // Add all of the arguments in their promoted form to the arg list...
10277       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10278         const Type *PTy = getPromotedType((*AI)->getType());
10279         if (PTy != (*AI)->getType()) {
10280           // Must promote to pass through va_arg area!
10281           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10282                                                                 PTy, false);
10283           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10284           InsertNewInstBefore(Cast, *Caller);
10285           Args.push_back(Cast);
10286         } else {
10287           Args.push_back(*AI);
10288         }
10289
10290         // Add any parameter attributes.
10291         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10292           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10293       }
10294     }
10295   }
10296
10297   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10298     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10299
10300   if (NewRetTy == Type::VoidTy)
10301     Caller->setName("");   // Void type should not have a name.
10302
10303   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10304                                                      attrVec.end());
10305
10306   Instruction *NC;
10307   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10308     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10309                             Args.begin(), Args.end(),
10310                             Caller->getName(), Caller);
10311     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10312     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10313   } else {
10314     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10315                           Caller->getName(), Caller);
10316     CallInst *CI = cast<CallInst>(Caller);
10317     if (CI->isTailCall())
10318       cast<CallInst>(NC)->setTailCall();
10319     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10320     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10321   }
10322
10323   // Insert a cast of the return type as necessary.
10324   Value *NV = NC;
10325   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10326     if (NV->getType() != Type::VoidTy) {
10327       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10328                                                             OldRetTy, false);
10329       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10330
10331       // If this is an invoke instruction, we should insert it after the first
10332       // non-phi, instruction in the normal successor block.
10333       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10334         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10335         InsertNewInstBefore(NC, *I);
10336       } else {
10337         // Otherwise, it's a call, just insert cast right after the call instr
10338         InsertNewInstBefore(NC, *Caller);
10339       }
10340       AddUsersToWorkList(*Caller);
10341     } else {
10342       NV = Context->getUndef(Caller->getType());
10343     }
10344   }
10345
10346   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10347     Caller->replaceAllUsesWith(NV);
10348   Caller->eraseFromParent();
10349   RemoveFromWorkList(Caller);
10350   return true;
10351 }
10352
10353 // transformCallThroughTrampoline - Turn a call to a function created by the
10354 // init_trampoline intrinsic into a direct call to the underlying function.
10355 //
10356 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10357   Value *Callee = CS.getCalledValue();
10358   const PointerType *PTy = cast<PointerType>(Callee->getType());
10359   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10360   const AttrListPtr &Attrs = CS.getAttributes();
10361
10362   // If the call already has the 'nest' attribute somewhere then give up -
10363   // otherwise 'nest' would occur twice after splicing in the chain.
10364   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10365     return 0;
10366
10367   IntrinsicInst *Tramp =
10368     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10369
10370   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10371   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10372   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10373
10374   const AttrListPtr &NestAttrs = NestF->getAttributes();
10375   if (!NestAttrs.isEmpty()) {
10376     unsigned NestIdx = 1;
10377     const Type *NestTy = 0;
10378     Attributes NestAttr = Attribute::None;
10379
10380     // Look for a parameter marked with the 'nest' attribute.
10381     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10382          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10383       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10384         // Record the parameter type and any other attributes.
10385         NestTy = *I;
10386         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10387         break;
10388       }
10389
10390     if (NestTy) {
10391       Instruction *Caller = CS.getInstruction();
10392       std::vector<Value*> NewArgs;
10393       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10394
10395       SmallVector<AttributeWithIndex, 8> NewAttrs;
10396       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10397
10398       // Insert the nest argument into the call argument list, which may
10399       // mean appending it.  Likewise for attributes.
10400
10401       // Add any result attributes.
10402       if (Attributes Attr = Attrs.getRetAttributes())
10403         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10404
10405       {
10406         unsigned Idx = 1;
10407         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10408         do {
10409           if (Idx == NestIdx) {
10410             // Add the chain argument and attributes.
10411             Value *NestVal = Tramp->getOperand(3);
10412             if (NestVal->getType() != NestTy)
10413               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10414             NewArgs.push_back(NestVal);
10415             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10416           }
10417
10418           if (I == E)
10419             break;
10420
10421           // Add the original argument and attributes.
10422           NewArgs.push_back(*I);
10423           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10424             NewAttrs.push_back
10425               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10426
10427           ++Idx, ++I;
10428         } while (1);
10429       }
10430
10431       // Add any function attributes.
10432       if (Attributes Attr = Attrs.getFnAttributes())
10433         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10434
10435       // The trampoline may have been bitcast to a bogus type (FTy).
10436       // Handle this by synthesizing a new function type, equal to FTy
10437       // with the chain parameter inserted.
10438
10439       std::vector<const Type*> NewTypes;
10440       NewTypes.reserve(FTy->getNumParams()+1);
10441
10442       // Insert the chain's type into the list of parameter types, which may
10443       // mean appending it.
10444       {
10445         unsigned Idx = 1;
10446         FunctionType::param_iterator I = FTy->param_begin(),
10447           E = FTy->param_end();
10448
10449         do {
10450           if (Idx == NestIdx)
10451             // Add the chain's type.
10452             NewTypes.push_back(NestTy);
10453
10454           if (I == E)
10455             break;
10456
10457           // Add the original type.
10458           NewTypes.push_back(*I);
10459
10460           ++Idx, ++I;
10461         } while (1);
10462       }
10463
10464       // Replace the trampoline call with a direct call.  Let the generic
10465       // code sort out any function type mismatches.
10466       FunctionType *NewFTy =
10467                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10468                                                 FTy->isVarArg());
10469       Constant *NewCallee =
10470         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10471         NestF : Context->getConstantExprBitCast(NestF, 
10472                                          Context->getPointerTypeUnqual(NewFTy));
10473       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10474                                                    NewAttrs.end());
10475
10476       Instruction *NewCaller;
10477       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10478         NewCaller = InvokeInst::Create(NewCallee,
10479                                        II->getNormalDest(), II->getUnwindDest(),
10480                                        NewArgs.begin(), NewArgs.end(),
10481                                        Caller->getName(), Caller);
10482         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10483         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10484       } else {
10485         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10486                                      Caller->getName(), Caller);
10487         if (cast<CallInst>(Caller)->isTailCall())
10488           cast<CallInst>(NewCaller)->setTailCall();
10489         cast<CallInst>(NewCaller)->
10490           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10491         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10492       }
10493       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10494         Caller->replaceAllUsesWith(NewCaller);
10495       Caller->eraseFromParent();
10496       RemoveFromWorkList(Caller);
10497       return 0;
10498     }
10499   }
10500
10501   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10502   // parameter, there is no need to adjust the argument list.  Let the generic
10503   // code sort out any function type mismatches.
10504   Constant *NewCallee =
10505     NestF->getType() == PTy ? NestF : 
10506                               Context->getConstantExprBitCast(NestF, PTy);
10507   CS.setCalledFunction(NewCallee);
10508   return CS.getInstruction();
10509 }
10510
10511 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10512 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10513 /// and a single binop.
10514 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10515   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10516   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10517   unsigned Opc = FirstInst->getOpcode();
10518   Value *LHSVal = FirstInst->getOperand(0);
10519   Value *RHSVal = FirstInst->getOperand(1);
10520     
10521   const Type *LHSType = LHSVal->getType();
10522   const Type *RHSType = RHSVal->getType();
10523   
10524   // Scan to see if all operands are the same opcode, all have one use, and all
10525   // kill their operands (i.e. the operands have one use).
10526   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10527     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10528     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10529         // Verify type of the LHS matches so we don't fold cmp's of different
10530         // types or GEP's with different index types.
10531         I->getOperand(0)->getType() != LHSType ||
10532         I->getOperand(1)->getType() != RHSType)
10533       return 0;
10534
10535     // If they are CmpInst instructions, check their predicates
10536     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10537       if (cast<CmpInst>(I)->getPredicate() !=
10538           cast<CmpInst>(FirstInst)->getPredicate())
10539         return 0;
10540     
10541     // Keep track of which operand needs a phi node.
10542     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10543     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10544   }
10545   
10546   // Otherwise, this is safe to transform!
10547   
10548   Value *InLHS = FirstInst->getOperand(0);
10549   Value *InRHS = FirstInst->getOperand(1);
10550   PHINode *NewLHS = 0, *NewRHS = 0;
10551   if (LHSVal == 0) {
10552     NewLHS = PHINode::Create(LHSType,
10553                              FirstInst->getOperand(0)->getName() + ".pn");
10554     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10555     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10556     InsertNewInstBefore(NewLHS, PN);
10557     LHSVal = NewLHS;
10558   }
10559   
10560   if (RHSVal == 0) {
10561     NewRHS = PHINode::Create(RHSType,
10562                              FirstInst->getOperand(1)->getName() + ".pn");
10563     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10564     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10565     InsertNewInstBefore(NewRHS, PN);
10566     RHSVal = NewRHS;
10567   }
10568   
10569   // Add all operands to the new PHIs.
10570   if (NewLHS || NewRHS) {
10571     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10572       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10573       if (NewLHS) {
10574         Value *NewInLHS = InInst->getOperand(0);
10575         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10576       }
10577       if (NewRHS) {
10578         Value *NewInRHS = InInst->getOperand(1);
10579         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10580       }
10581     }
10582   }
10583     
10584   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10585     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10586   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10587   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10588                          LHSVal, RHSVal);
10589 }
10590
10591 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10592   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10593   
10594   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10595                                         FirstInst->op_end());
10596   // This is true if all GEP bases are allocas and if all indices into them are
10597   // constants.
10598   bool AllBasePointersAreAllocas = true;
10599   
10600   // Scan to see if all operands are the same opcode, all have one use, and all
10601   // kill their operands (i.e. the operands have one use).
10602   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10603     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10604     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10605       GEP->getNumOperands() != FirstInst->getNumOperands())
10606       return 0;
10607
10608     // Keep track of whether or not all GEPs are of alloca pointers.
10609     if (AllBasePointersAreAllocas &&
10610         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10611          !GEP->hasAllConstantIndices()))
10612       AllBasePointersAreAllocas = false;
10613     
10614     // Compare the operand lists.
10615     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10616       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10617         continue;
10618       
10619       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10620       // if one of the PHIs has a constant for the index.  The index may be
10621       // substantially cheaper to compute for the constants, so making it a
10622       // variable index could pessimize the path.  This also handles the case
10623       // for struct indices, which must always be constant.
10624       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10625           isa<ConstantInt>(GEP->getOperand(op)))
10626         return 0;
10627       
10628       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10629         return 0;
10630       FixedOperands[op] = 0;  // Needs a PHI.
10631     }
10632   }
10633   
10634   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10635   // bother doing this transformation.  At best, this will just save a bit of
10636   // offset calculation, but all the predecessors will have to materialize the
10637   // stack address into a register anyway.  We'd actually rather *clone* the
10638   // load up into the predecessors so that we have a load of a gep of an alloca,
10639   // which can usually all be folded into the load.
10640   if (AllBasePointersAreAllocas)
10641     return 0;
10642   
10643   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10644   // that is variable.
10645   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10646   
10647   bool HasAnyPHIs = false;
10648   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10649     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10650     Value *FirstOp = FirstInst->getOperand(i);
10651     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10652                                      FirstOp->getName()+".pn");
10653     InsertNewInstBefore(NewPN, PN);
10654     
10655     NewPN->reserveOperandSpace(e);
10656     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10657     OperandPhis[i] = NewPN;
10658     FixedOperands[i] = NewPN;
10659     HasAnyPHIs = true;
10660   }
10661
10662   
10663   // Add all operands to the new PHIs.
10664   if (HasAnyPHIs) {
10665     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10666       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10667       BasicBlock *InBB = PN.getIncomingBlock(i);
10668       
10669       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10670         if (PHINode *OpPhi = OperandPhis[op])
10671           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10672     }
10673   }
10674   
10675   Value *Base = FixedOperands[0];
10676   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10677                                    FixedOperands.end());
10678 }
10679
10680
10681 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10682 /// sink the load out of the block that defines it.  This means that it must be
10683 /// obvious the value of the load is not changed from the point of the load to
10684 /// the end of the block it is in.
10685 ///
10686 /// Finally, it is safe, but not profitable, to sink a load targetting a
10687 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10688 /// to a register.
10689 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10690   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10691   
10692   for (++BBI; BBI != E; ++BBI)
10693     if (BBI->mayWriteToMemory())
10694       return false;
10695   
10696   // Check for non-address taken alloca.  If not address-taken already, it isn't
10697   // profitable to do this xform.
10698   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10699     bool isAddressTaken = false;
10700     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10701          UI != E; ++UI) {
10702       if (isa<LoadInst>(UI)) continue;
10703       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10704         // If storing TO the alloca, then the address isn't taken.
10705         if (SI->getOperand(1) == AI) continue;
10706       }
10707       isAddressTaken = true;
10708       break;
10709     }
10710     
10711     if (!isAddressTaken && AI->isStaticAlloca())
10712       return false;
10713   }
10714   
10715   // If this load is a load from a GEP with a constant offset from an alloca,
10716   // then we don't want to sink it.  In its present form, it will be
10717   // load [constant stack offset].  Sinking it will cause us to have to
10718   // materialize the stack addresses in each predecessor in a register only to
10719   // do a shared load from register in the successor.
10720   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10721     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10722       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10723         return false;
10724   
10725   return true;
10726 }
10727
10728
10729 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10730 // operator and they all are only used by the PHI, PHI together their
10731 // inputs, and do the operation once, to the result of the PHI.
10732 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10733   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10734
10735   // Scan the instruction, looking for input operations that can be folded away.
10736   // If all input operands to the phi are the same instruction (e.g. a cast from
10737   // the same type or "+42") we can pull the operation through the PHI, reducing
10738   // code size and simplifying code.
10739   Constant *ConstantOp = 0;
10740   const Type *CastSrcTy = 0;
10741   bool isVolatile = false;
10742   if (isa<CastInst>(FirstInst)) {
10743     CastSrcTy = FirstInst->getOperand(0)->getType();
10744   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10745     // Can fold binop, compare or shift here if the RHS is a constant, 
10746     // otherwise call FoldPHIArgBinOpIntoPHI.
10747     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10748     if (ConstantOp == 0)
10749       return FoldPHIArgBinOpIntoPHI(PN);
10750   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10751     isVolatile = LI->isVolatile();
10752     // We can't sink the load if the loaded value could be modified between the
10753     // load and the PHI.
10754     if (LI->getParent() != PN.getIncomingBlock(0) ||
10755         !isSafeAndProfitableToSinkLoad(LI))
10756       return 0;
10757     
10758     // If the PHI is of volatile loads and the load block has multiple
10759     // successors, sinking it would remove a load of the volatile value from
10760     // the path through the other successor.
10761     if (isVolatile &&
10762         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10763       return 0;
10764     
10765   } else if (isa<GetElementPtrInst>(FirstInst)) {
10766     return FoldPHIArgGEPIntoPHI(PN);
10767   } else {
10768     return 0;  // Cannot fold this operation.
10769   }
10770
10771   // Check to see if all arguments are the same operation.
10772   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10773     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10774     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10775     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10776       return 0;
10777     if (CastSrcTy) {
10778       if (I->getOperand(0)->getType() != CastSrcTy)
10779         return 0;  // Cast operation must match.
10780     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10781       // We can't sink the load if the loaded value could be modified between 
10782       // the load and the PHI.
10783       if (LI->isVolatile() != isVolatile ||
10784           LI->getParent() != PN.getIncomingBlock(i) ||
10785           !isSafeAndProfitableToSinkLoad(LI))
10786         return 0;
10787       
10788       // If the PHI is of volatile loads and the load block has multiple
10789       // successors, sinking it would remove a load of the volatile value from
10790       // the path through the other successor.
10791       if (isVolatile &&
10792           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10793         return 0;
10794       
10795     } else if (I->getOperand(1) != ConstantOp) {
10796       return 0;
10797     }
10798   }
10799
10800   // Okay, they are all the same operation.  Create a new PHI node of the
10801   // correct type, and PHI together all of the LHS's of the instructions.
10802   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10803                                    PN.getName()+".in");
10804   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10805
10806   Value *InVal = FirstInst->getOperand(0);
10807   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10808
10809   // Add all operands to the new PHI.
10810   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10811     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10812     if (NewInVal != InVal)
10813       InVal = 0;
10814     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10815   }
10816
10817   Value *PhiVal;
10818   if (InVal) {
10819     // The new PHI unions all of the same values together.  This is really
10820     // common, so we handle it intelligently here for compile-time speed.
10821     PhiVal = InVal;
10822     delete NewPN;
10823   } else {
10824     InsertNewInstBefore(NewPN, PN);
10825     PhiVal = NewPN;
10826   }
10827
10828   // Insert and return the new operation.
10829   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10830     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10831   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10832     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10833   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10834     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10835                            PhiVal, ConstantOp);
10836   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10837   
10838   // If this was a volatile load that we are merging, make sure to loop through
10839   // and mark all the input loads as non-volatile.  If we don't do this, we will
10840   // insert a new volatile load and the old ones will not be deletable.
10841   if (isVolatile)
10842     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10843       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10844   
10845   return new LoadInst(PhiVal, "", isVolatile);
10846 }
10847
10848 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10849 /// that is dead.
10850 static bool DeadPHICycle(PHINode *PN,
10851                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10852   if (PN->use_empty()) return true;
10853   if (!PN->hasOneUse()) return false;
10854
10855   // Remember this node, and if we find the cycle, return.
10856   if (!PotentiallyDeadPHIs.insert(PN))
10857     return true;
10858   
10859   // Don't scan crazily complex things.
10860   if (PotentiallyDeadPHIs.size() == 16)
10861     return false;
10862
10863   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10864     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10865
10866   return false;
10867 }
10868
10869 /// PHIsEqualValue - Return true if this phi node is always equal to
10870 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10871 ///   z = some value; x = phi (y, z); y = phi (x, z)
10872 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10873                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10874   // See if we already saw this PHI node.
10875   if (!ValueEqualPHIs.insert(PN))
10876     return true;
10877   
10878   // Don't scan crazily complex things.
10879   if (ValueEqualPHIs.size() == 16)
10880     return false;
10881  
10882   // Scan the operands to see if they are either phi nodes or are equal to
10883   // the value.
10884   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10885     Value *Op = PN->getIncomingValue(i);
10886     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10887       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10888         return false;
10889     } else if (Op != NonPhiInVal)
10890       return false;
10891   }
10892   
10893   return true;
10894 }
10895
10896
10897 // PHINode simplification
10898 //
10899 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10900   // If LCSSA is around, don't mess with Phi nodes
10901   if (MustPreserveLCSSA) return 0;
10902   
10903   if (Value *V = PN.hasConstantValue())
10904     return ReplaceInstUsesWith(PN, V);
10905
10906   // If all PHI operands are the same operation, pull them through the PHI,
10907   // reducing code size.
10908   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10909       isa<Instruction>(PN.getIncomingValue(1)) &&
10910       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10911       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10912       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10913       // than themselves more than once.
10914       PN.getIncomingValue(0)->hasOneUse())
10915     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10916       return Result;
10917
10918   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10919   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10920   // PHI)... break the cycle.
10921   if (PN.hasOneUse()) {
10922     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10923     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10924       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10925       PotentiallyDeadPHIs.insert(&PN);
10926       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10927         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10928     }
10929    
10930     // If this phi has a single use, and if that use just computes a value for
10931     // the next iteration of a loop, delete the phi.  This occurs with unused
10932     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10933     // common case here is good because the only other things that catch this
10934     // are induction variable analysis (sometimes) and ADCE, which is only run
10935     // late.
10936     if (PHIUser->hasOneUse() &&
10937         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10938         PHIUser->use_back() == &PN) {
10939       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10940     }
10941   }
10942
10943   // We sometimes end up with phi cycles that non-obviously end up being the
10944   // same value, for example:
10945   //   z = some value; x = phi (y, z); y = phi (x, z)
10946   // where the phi nodes don't necessarily need to be in the same block.  Do a
10947   // quick check to see if the PHI node only contains a single non-phi value, if
10948   // so, scan to see if the phi cycle is actually equal to that value.
10949   {
10950     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10951     // Scan for the first non-phi operand.
10952     while (InValNo != NumOperandVals && 
10953            isa<PHINode>(PN.getIncomingValue(InValNo)))
10954       ++InValNo;
10955
10956     if (InValNo != NumOperandVals) {
10957       Value *NonPhiInVal = PN.getOperand(InValNo);
10958       
10959       // Scan the rest of the operands to see if there are any conflicts, if so
10960       // there is no need to recursively scan other phis.
10961       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10962         Value *OpVal = PN.getIncomingValue(InValNo);
10963         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10964           break;
10965       }
10966       
10967       // If we scanned over all operands, then we have one unique value plus
10968       // phi values.  Scan PHI nodes to see if they all merge in each other or
10969       // the value.
10970       if (InValNo == NumOperandVals) {
10971         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10972         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10973           return ReplaceInstUsesWith(PN, NonPhiInVal);
10974       }
10975     }
10976   }
10977   return 0;
10978 }
10979
10980 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10981                                    Instruction *InsertPoint,
10982                                    InstCombiner *IC) {
10983   unsigned PtrSize = DTy->getScalarSizeInBits();
10984   unsigned VTySize = V->getType()->getScalarSizeInBits();
10985   // We must cast correctly to the pointer type. Ensure that we
10986   // sign extend the integer value if it is smaller as this is
10987   // used for address computation.
10988   Instruction::CastOps opcode = 
10989      (VTySize < PtrSize ? Instruction::SExt :
10990       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10991   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10992 }
10993
10994
10995 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10996   Value *PtrOp = GEP.getOperand(0);
10997   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10998   // If so, eliminate the noop.
10999   if (GEP.getNumOperands() == 1)
11000     return ReplaceInstUsesWith(GEP, PtrOp);
11001
11002   if (isa<UndefValue>(GEP.getOperand(0)))
11003     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11004
11005   bool HasZeroPointerIndex = false;
11006   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11007     HasZeroPointerIndex = C->isNullValue();
11008
11009   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11010     return ReplaceInstUsesWith(GEP, PtrOp);
11011
11012   // Eliminate unneeded casts for indices.
11013   bool MadeChange = false;
11014   
11015   gep_type_iterator GTI = gep_type_begin(GEP);
11016   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11017        i != e; ++i, ++GTI) {
11018     if (TD && isa<SequentialType>(*GTI)) {
11019       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11020         if (CI->getOpcode() == Instruction::ZExt ||
11021             CI->getOpcode() == Instruction::SExt) {
11022           const Type *SrcTy = CI->getOperand(0)->getType();
11023           // We can eliminate a cast from i32 to i64 iff the target 
11024           // is a 32-bit pointer target.
11025           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11026             MadeChange = true;
11027             *i = CI->getOperand(0);
11028           }
11029         }
11030       }
11031       // If we are using a wider index than needed for this platform, shrink it
11032       // to what we need.  If narrower, sign-extend it to what we need.
11033       // If the incoming value needs a cast instruction,
11034       // insert it.  This explicit cast can make subsequent optimizations more
11035       // obvious.
11036       Value *Op = *i;
11037       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11038         if (Constant *C = dyn_cast<Constant>(Op)) {
11039           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11040           MadeChange = true;
11041         } else {
11042           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11043                                 GEP);
11044           *i = Op;
11045           MadeChange = true;
11046         }
11047       } else if (TD->getTypeSizeInBits(Op->getType()) 
11048                   < TD->getPointerSizeInBits()) {
11049         if (Constant *C = dyn_cast<Constant>(Op)) {
11050           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11051           MadeChange = true;
11052         } else {
11053           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11054                                 GEP);
11055           *i = Op;
11056           MadeChange = true;
11057         }
11058       }
11059     }
11060   }
11061   if (MadeChange) return &GEP;
11062
11063   // Combine Indices - If the source pointer to this getelementptr instruction
11064   // is a getelementptr instruction, combine the indices of the two
11065   // getelementptr instructions into a single instruction.
11066   //
11067   SmallVector<Value*, 8> SrcGEPOperands;
11068   if (User *Src = dyn_castGetElementPtr(PtrOp))
11069     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11070
11071   if (!SrcGEPOperands.empty()) {
11072     // Note that if our source is a gep chain itself that we wait for that
11073     // chain to be resolved before we perform this transformation.  This
11074     // avoids us creating a TON of code in some cases.
11075     //
11076     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11077         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11078       return 0;   // Wait until our source is folded to completion.
11079
11080     SmallVector<Value*, 8> Indices;
11081
11082     // Find out whether the last index in the source GEP is a sequential idx.
11083     bool EndsWithSequential = false;
11084     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11085            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11086       EndsWithSequential = !isa<StructType>(*I);
11087
11088     // Can we combine the two pointer arithmetics offsets?
11089     if (EndsWithSequential) {
11090       // Replace: gep (gep %P, long B), long A, ...
11091       // With:    T = long A+B; gep %P, T, ...
11092       //
11093       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11094       if (SO1 == Context->getNullValue(SO1->getType())) {
11095         Sum = GO1;
11096       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11097         Sum = SO1;
11098       } else {
11099         // If they aren't the same type, convert both to an integer of the
11100         // target's pointer size.
11101         if (SO1->getType() != GO1->getType()) {
11102           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11103             SO1 =
11104                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11105           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11106             GO1 =
11107                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11108           } else if (TD) {
11109             unsigned PS = TD->getPointerSizeInBits();
11110             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11111               // Convert GO1 to SO1's type.
11112               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11113
11114             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11115               // Convert SO1 to GO1's type.
11116               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11117             } else {
11118               const Type *PT = TD->getIntPtrType();
11119               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11120               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11121             }
11122           }
11123         }
11124         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11125           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11126                                             cast<Constant>(GO1));
11127         else {
11128           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11129           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11130         }
11131       }
11132
11133       // Recycle the GEP we already have if possible.
11134       if (SrcGEPOperands.size() == 2) {
11135         GEP.setOperand(0, SrcGEPOperands[0]);
11136         GEP.setOperand(1, Sum);
11137         return &GEP;
11138       } else {
11139         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11140                        SrcGEPOperands.end()-1);
11141         Indices.push_back(Sum);
11142         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11143       }
11144     } else if (isa<Constant>(*GEP.idx_begin()) &&
11145                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11146                SrcGEPOperands.size() != 1) {
11147       // Otherwise we can do the fold if the first index of the GEP is a zero
11148       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11149                      SrcGEPOperands.end());
11150       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11151     }
11152
11153     if (!Indices.empty())
11154       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11155                                        Indices.end(), GEP.getName());
11156
11157   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11158     // GEP of global variable.  If all of the indices for this GEP are
11159     // constants, we can promote this to a constexpr instead of an instruction.
11160
11161     // Scan for nonconstants...
11162     SmallVector<Constant*, 8> Indices;
11163     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11164     for (; I != E && isa<Constant>(*I); ++I)
11165       Indices.push_back(cast<Constant>(*I));
11166
11167     if (I == E) {  // If they are all constants...
11168       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11169                                                     &Indices[0],Indices.size());
11170
11171       // Replace all uses of the GEP with the new constexpr...
11172       return ReplaceInstUsesWith(GEP, CE);
11173     }
11174   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11175     if (!isa<PointerType>(X->getType())) {
11176       // Not interesting.  Source pointer must be a cast from pointer.
11177     } else if (HasZeroPointerIndex) {
11178       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11179       // into     : GEP [10 x i8]* X, i32 0, ...
11180       //
11181       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11182       //           into     : GEP i8* X, ...
11183       // 
11184       // This occurs when the program declares an array extern like "int X[];"
11185       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11186       const PointerType *XTy = cast<PointerType>(X->getType());
11187       if (const ArrayType *CATy =
11188           dyn_cast<ArrayType>(CPTy->getElementType())) {
11189         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11190         if (CATy->getElementType() == XTy->getElementType()) {
11191           // -> GEP i8* X, ...
11192           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11193           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11194                                            GEP.getName());
11195         } else if (const ArrayType *XATy =
11196                  dyn_cast<ArrayType>(XTy->getElementType())) {
11197           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11198           if (CATy->getElementType() == XATy->getElementType()) {
11199             // -> GEP [10 x i8]* X, i32 0, ...
11200             // At this point, we know that the cast source type is a pointer
11201             // to an array of the same type as the destination pointer
11202             // array.  Because the array type is never stepped over (there
11203             // is a leading zero) we can fold the cast into this GEP.
11204             GEP.setOperand(0, X);
11205             return &GEP;
11206           }
11207         }
11208       }
11209     } else if (GEP.getNumOperands() == 2) {
11210       // Transform things like:
11211       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11212       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11213       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11214       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11215       if (TD && isa<ArrayType>(SrcElTy) &&
11216           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11217           TD->getTypeAllocSize(ResElTy)) {
11218         Value *Idx[2];
11219         Idx[0] = Context->getNullValue(Type::Int32Ty);
11220         Idx[1] = GEP.getOperand(1);
11221         Value *V = InsertNewInstBefore(
11222                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11223         // V and GEP are both pointer types --> BitCast
11224         return new BitCastInst(V, GEP.getType());
11225       }
11226       
11227       // Transform things like:
11228       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11229       //   (where tmp = 8*tmp2) into:
11230       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11231       
11232       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11233         uint64_t ArrayEltSize =
11234             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11235         
11236         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11237         // allow either a mul, shift, or constant here.
11238         Value *NewIdx = 0;
11239         ConstantInt *Scale = 0;
11240         if (ArrayEltSize == 1) {
11241           NewIdx = GEP.getOperand(1);
11242           Scale = 
11243                ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11244         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11245           NewIdx = ConstantInt::get(CI->getType(), 1);
11246           Scale = CI;
11247         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11248           if (Inst->getOpcode() == Instruction::Shl &&
11249               isa<ConstantInt>(Inst->getOperand(1))) {
11250             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11251             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11252             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11253                                      1ULL << ShAmtVal);
11254             NewIdx = Inst->getOperand(0);
11255           } else if (Inst->getOpcode() == Instruction::Mul &&
11256                      isa<ConstantInt>(Inst->getOperand(1))) {
11257             Scale = cast<ConstantInt>(Inst->getOperand(1));
11258             NewIdx = Inst->getOperand(0);
11259           }
11260         }
11261         
11262         // If the index will be to exactly the right offset with the scale taken
11263         // out, perform the transformation. Note, we don't know whether Scale is
11264         // signed or not. We'll use unsigned version of division/modulo
11265         // operation after making sure Scale doesn't have the sign bit set.
11266         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11267             Scale->getZExtValue() % ArrayEltSize == 0) {
11268           Scale = ConstantInt::get(Scale->getType(),
11269                                    Scale->getZExtValue() / ArrayEltSize);
11270           if (Scale->getZExtValue() != 1) {
11271             Constant *C =
11272                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11273                                                        false /*ZExt*/);
11274             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11275             NewIdx = InsertNewInstBefore(Sc, GEP);
11276           }
11277
11278           // Insert the new GEP instruction.
11279           Value *Idx[2];
11280           Idx[0] = Context->getNullValue(Type::Int32Ty);
11281           Idx[1] = NewIdx;
11282           Instruction *NewGEP =
11283             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11284           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11285           // The NewGEP must be pointer typed, so must the old one -> BitCast
11286           return new BitCastInst(NewGEP, GEP.getType());
11287         }
11288       }
11289     }
11290   }
11291   
11292   /// See if we can simplify:
11293   ///   X = bitcast A to B*
11294   ///   Y = gep X, <...constant indices...>
11295   /// into a gep of the original struct.  This is important for SROA and alias
11296   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11297   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11298     if (TD &&
11299         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11300       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11301       // a constant back from EmitGEPOffset.
11302       ConstantInt *OffsetV =
11303                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11304       int64_t Offset = OffsetV->getSExtValue();
11305       
11306       // If this GEP instruction doesn't move the pointer, just replace the GEP
11307       // with a bitcast of the real input to the dest type.
11308       if (Offset == 0) {
11309         // If the bitcast is of an allocation, and the allocation will be
11310         // converted to match the type of the cast, don't touch this.
11311         if (isa<AllocationInst>(BCI->getOperand(0))) {
11312           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11313           if (Instruction *I = visitBitCast(*BCI)) {
11314             if (I != BCI) {
11315               I->takeName(BCI);
11316               BCI->getParent()->getInstList().insert(BCI, I);
11317               ReplaceInstUsesWith(*BCI, I);
11318             }
11319             return &GEP;
11320           }
11321         }
11322         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11323       }
11324       
11325       // Otherwise, if the offset is non-zero, we need to find out if there is a
11326       // field at Offset in 'A's type.  If so, we can pull the cast through the
11327       // GEP.
11328       SmallVector<Value*, 8> NewIndices;
11329       const Type *InTy =
11330         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11331       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11332         Instruction *NGEP =
11333            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11334                                      NewIndices.end());
11335         if (NGEP->getType() == GEP.getType()) return NGEP;
11336         InsertNewInstBefore(NGEP, GEP);
11337         NGEP->takeName(&GEP);
11338         return new BitCastInst(NGEP, GEP.getType());
11339       }
11340     }
11341   }    
11342     
11343   return 0;
11344 }
11345
11346 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11347   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11348   if (AI.isArrayAllocation()) {  // Check C != 1
11349     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11350       const Type *NewTy = 
11351         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11352       AllocationInst *New = 0;
11353
11354       // Create and insert the replacement instruction...
11355       if (isa<MallocInst>(AI))
11356         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11357       else {
11358         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11359         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11360       }
11361
11362       InsertNewInstBefore(New, AI);
11363
11364       // Scan to the end of the allocation instructions, to skip over a block of
11365       // allocas if possible...also skip interleaved debug info
11366       //
11367       BasicBlock::iterator It = New;
11368       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11369
11370       // Now that I is pointing to the first non-allocation-inst in the block,
11371       // insert our getelementptr instruction...
11372       //
11373       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11374       Value *Idx[2];
11375       Idx[0] = NullIdx;
11376       Idx[1] = NullIdx;
11377       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11378                                            New->getName()+".sub", It);
11379
11380       // Now make everything use the getelementptr instead of the original
11381       // allocation.
11382       return ReplaceInstUsesWith(AI, V);
11383     } else if (isa<UndefValue>(AI.getArraySize())) {
11384       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11385     }
11386   }
11387
11388   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11389     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11390     // Note that we only do this for alloca's, because malloc should allocate
11391     // and return a unique pointer, even for a zero byte allocation.
11392     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11393       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11394
11395     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11396     if (AI.getAlignment() == 0)
11397       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11398   }
11399
11400   return 0;
11401 }
11402
11403 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11404   Value *Op = FI.getOperand(0);
11405
11406   // free undef -> unreachable.
11407   if (isa<UndefValue>(Op)) {
11408     // Insert a new store to null because we cannot modify the CFG here.
11409     new StoreInst(Context->getTrue(),
11410            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11411     return EraseInstFromFunction(FI);
11412   }
11413   
11414   // If we have 'free null' delete the instruction.  This can happen in stl code
11415   // when lots of inlining happens.
11416   if (isa<ConstantPointerNull>(Op))
11417     return EraseInstFromFunction(FI);
11418   
11419   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11420   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11421     FI.setOperand(0, CI->getOperand(0));
11422     return &FI;
11423   }
11424   
11425   // Change free (gep X, 0,0,0,0) into free(X)
11426   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11427     if (GEPI->hasAllZeroIndices()) {
11428       AddToWorkList(GEPI);
11429       FI.setOperand(0, GEPI->getOperand(0));
11430       return &FI;
11431     }
11432   }
11433   
11434   // Change free(malloc) into nothing, if the malloc has a single use.
11435   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11436     if (MI->hasOneUse()) {
11437       EraseInstFromFunction(FI);
11438       return EraseInstFromFunction(*MI);
11439     }
11440
11441   return 0;
11442 }
11443
11444
11445 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11446 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11447                                         const TargetData *TD) {
11448   User *CI = cast<User>(LI.getOperand(0));
11449   Value *CastOp = CI->getOperand(0);
11450   LLVMContext *Context = IC.getContext();
11451
11452   if (TD) {
11453     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11454       // Instead of loading constant c string, use corresponding integer value
11455       // directly if string length is small enough.
11456       std::string Str;
11457       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11458         unsigned len = Str.length();
11459         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11460         unsigned numBits = Ty->getPrimitiveSizeInBits();
11461         // Replace LI with immediate integer store.
11462         if ((numBits >> 3) == len + 1) {
11463           APInt StrVal(numBits, 0);
11464           APInt SingleChar(numBits, 0);
11465           if (TD->isLittleEndian()) {
11466             for (signed i = len-1; i >= 0; i--) {
11467               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11468               StrVal = (StrVal << 8) | SingleChar;
11469             }
11470           } else {
11471             for (unsigned i = 0; i < len; i++) {
11472               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11473               StrVal = (StrVal << 8) | SingleChar;
11474             }
11475             // Append NULL at the end.
11476             SingleChar = 0;
11477             StrVal = (StrVal << 8) | SingleChar;
11478           }
11479           Value *NL = ConstantInt::get(*Context, StrVal);
11480           return IC.ReplaceInstUsesWith(LI, NL);
11481         }
11482       }
11483     }
11484   }
11485
11486   const PointerType *DestTy = cast<PointerType>(CI->getType());
11487   const Type *DestPTy = DestTy->getElementType();
11488   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11489
11490     // If the address spaces don't match, don't eliminate the cast.
11491     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11492       return 0;
11493
11494     const Type *SrcPTy = SrcTy->getElementType();
11495
11496     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11497          isa<VectorType>(DestPTy)) {
11498       // If the source is an array, the code below will not succeed.  Check to
11499       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11500       // constants.
11501       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11502         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11503           if (ASrcTy->getNumElements() != 0) {
11504             Value *Idxs[2];
11505             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11506             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11507             SrcTy = cast<PointerType>(CastOp->getType());
11508             SrcPTy = SrcTy->getElementType();
11509           }
11510
11511       if (IC.getTargetData() &&
11512           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11513             isa<VectorType>(SrcPTy)) &&
11514           // Do not allow turning this into a load of an integer, which is then
11515           // casted to a pointer, this pessimizes pointer analysis a lot.
11516           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11517           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11518                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11519
11520         // Okay, we are casting from one integer or pointer type to another of
11521         // the same size.  Instead of casting the pointer before the load, cast
11522         // the result of the loaded value.
11523         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11524                                                              CI->getName(),
11525                                                          LI.isVolatile()),LI);
11526         // Now cast the result of the load.
11527         return new BitCastInst(NewLoad, LI.getType());
11528       }
11529     }
11530   }
11531   return 0;
11532 }
11533
11534 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11535   Value *Op = LI.getOperand(0);
11536
11537   // Attempt to improve the alignment.
11538   if (TD) {
11539     unsigned KnownAlign =
11540       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11541     if (KnownAlign >
11542         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11543                                   LI.getAlignment()))
11544       LI.setAlignment(KnownAlign);
11545   }
11546
11547   // load (cast X) --> cast (load X) iff safe
11548   if (isa<CastInst>(Op))
11549     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11550       return Res;
11551
11552   // None of the following transforms are legal for volatile loads.
11553   if (LI.isVolatile()) return 0;
11554   
11555   // Do really simple store-to-load forwarding and load CSE, to catch cases
11556   // where there are several consequtive memory accesses to the same location,
11557   // separated by a few arithmetic operations.
11558   BasicBlock::iterator BBI = &LI;
11559   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11560     return ReplaceInstUsesWith(LI, AvailableVal);
11561
11562   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11563     const Value *GEPI0 = GEPI->getOperand(0);
11564     // TODO: Consider a target hook for valid address spaces for this xform.
11565     if (isa<ConstantPointerNull>(GEPI0) &&
11566         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11567       // Insert a new store to null instruction before the load to indicate
11568       // that this code is not reachable.  We do this instead of inserting
11569       // an unreachable instruction directly because we cannot modify the
11570       // CFG.
11571       new StoreInst(Context->getUndef(LI.getType()),
11572                     Context->getNullValue(Op->getType()), &LI);
11573       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11574     }
11575   } 
11576
11577   if (Constant *C = dyn_cast<Constant>(Op)) {
11578     // load null/undef -> undef
11579     // TODO: Consider a target hook for valid address spaces for this xform.
11580     if (isa<UndefValue>(C) || (C->isNullValue() && 
11581         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11582       // Insert a new store to null instruction before the load to indicate that
11583       // this code is not reachable.  We do this instead of inserting an
11584       // unreachable instruction directly because we cannot modify the CFG.
11585       new StoreInst(Context->getUndef(LI.getType()),
11586                     Context->getNullValue(Op->getType()), &LI);
11587       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11588     }
11589
11590     // Instcombine load (constant global) into the value loaded.
11591     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11592       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11593         return ReplaceInstUsesWith(LI, GV->getInitializer());
11594
11595     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11596     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11597       if (CE->getOpcode() == Instruction::GetElementPtr) {
11598         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11599           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11600             if (Constant *V = 
11601                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11602                                                       *Context))
11603               return ReplaceInstUsesWith(LI, V);
11604         if (CE->getOperand(0)->isNullValue()) {
11605           // Insert a new store to null instruction before the load to indicate
11606           // that this code is not reachable.  We do this instead of inserting
11607           // an unreachable instruction directly because we cannot modify the
11608           // CFG.
11609           new StoreInst(Context->getUndef(LI.getType()),
11610                         Context->getNullValue(Op->getType()), &LI);
11611           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11612         }
11613
11614       } else if (CE->isCast()) {
11615         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11616           return Res;
11617       }
11618     }
11619   }
11620     
11621   // If this load comes from anywhere in a constant global, and if the global
11622   // is all undef or zero, we know what it loads.
11623   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11624     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11625       if (GV->getInitializer()->isNullValue())
11626         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11627       else if (isa<UndefValue>(GV->getInitializer()))
11628         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11629     }
11630   }
11631
11632   if (Op->hasOneUse()) {
11633     // Change select and PHI nodes to select values instead of addresses: this
11634     // helps alias analysis out a lot, allows many others simplifications, and
11635     // exposes redundancy in the code.
11636     //
11637     // Note that we cannot do the transformation unless we know that the
11638     // introduced loads cannot trap!  Something like this is valid as long as
11639     // the condition is always false: load (select bool %C, int* null, int* %G),
11640     // but it would not be valid if we transformed it to load from null
11641     // unconditionally.
11642     //
11643     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11644       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11645       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11646           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11647         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11648                                      SI->getOperand(1)->getName()+".val"), LI);
11649         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11650                                      SI->getOperand(2)->getName()+".val"), LI);
11651         return SelectInst::Create(SI->getCondition(), V1, V2);
11652       }
11653
11654       // load (select (cond, null, P)) -> load P
11655       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11656         if (C->isNullValue()) {
11657           LI.setOperand(0, SI->getOperand(2));
11658           return &LI;
11659         }
11660
11661       // load (select (cond, P, null)) -> load P
11662       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11663         if (C->isNullValue()) {
11664           LI.setOperand(0, SI->getOperand(1));
11665           return &LI;
11666         }
11667     }
11668   }
11669   return 0;
11670 }
11671
11672 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11673 /// when possible.  This makes it generally easy to do alias analysis and/or
11674 /// SROA/mem2reg of the memory object.
11675 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11676   User *CI = cast<User>(SI.getOperand(1));
11677   Value *CastOp = CI->getOperand(0);
11678   LLVMContext *Context = IC.getContext();
11679
11680   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11681   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11682   if (SrcTy == 0) return 0;
11683   
11684   const Type *SrcPTy = SrcTy->getElementType();
11685
11686   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11687     return 0;
11688   
11689   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11690   /// to its first element.  This allows us to handle things like:
11691   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11692   /// on 32-bit hosts.
11693   SmallVector<Value*, 4> NewGEPIndices;
11694   
11695   // If the source is an array, the code below will not succeed.  Check to
11696   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11697   // constants.
11698   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11699     // Index through pointer.
11700     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11701     NewGEPIndices.push_back(Zero);
11702     
11703     while (1) {
11704       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11705         if (!STy->getNumElements()) /* Struct can be empty {} */
11706           break;
11707         NewGEPIndices.push_back(Zero);
11708         SrcPTy = STy->getElementType(0);
11709       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11710         NewGEPIndices.push_back(Zero);
11711         SrcPTy = ATy->getElementType();
11712       } else {
11713         break;
11714       }
11715     }
11716     
11717     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11718   }
11719
11720   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11721     return 0;
11722   
11723   // If the pointers point into different address spaces or if they point to
11724   // values with different sizes, we can't do the transformation.
11725   if (!IC.getTargetData() ||
11726       SrcTy->getAddressSpace() != 
11727         cast<PointerType>(CI->getType())->getAddressSpace() ||
11728       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11729       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11730     return 0;
11731
11732   // Okay, we are casting from one integer or pointer type to another of
11733   // the same size.  Instead of casting the pointer before 
11734   // the store, cast the value to be stored.
11735   Value *NewCast;
11736   Value *SIOp0 = SI.getOperand(0);
11737   Instruction::CastOps opcode = Instruction::BitCast;
11738   const Type* CastSrcTy = SIOp0->getType();
11739   const Type* CastDstTy = SrcPTy;
11740   if (isa<PointerType>(CastDstTy)) {
11741     if (CastSrcTy->isInteger())
11742       opcode = Instruction::IntToPtr;
11743   } else if (isa<IntegerType>(CastDstTy)) {
11744     if (isa<PointerType>(SIOp0->getType()))
11745       opcode = Instruction::PtrToInt;
11746   }
11747   
11748   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11749   // emit a GEP to index into its first field.
11750   if (!NewGEPIndices.empty()) {
11751     if (Constant *C = dyn_cast<Constant>(CastOp))
11752       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11753                                               NewGEPIndices.size());
11754     else
11755       CastOp = IC.InsertNewInstBefore(
11756               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11757                                         NewGEPIndices.end()), SI);
11758   }
11759   
11760   if (Constant *C = dyn_cast<Constant>(SIOp0))
11761     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11762   else
11763     NewCast = IC.InsertNewInstBefore(
11764       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11765       SI);
11766   return new StoreInst(NewCast, CastOp);
11767 }
11768
11769 /// equivalentAddressValues - Test if A and B will obviously have the same
11770 /// value. This includes recognizing that %t0 and %t1 will have the same
11771 /// value in code like this:
11772 ///   %t0 = getelementptr \@a, 0, 3
11773 ///   store i32 0, i32* %t0
11774 ///   %t1 = getelementptr \@a, 0, 3
11775 ///   %t2 = load i32* %t1
11776 ///
11777 static bool equivalentAddressValues(Value *A, Value *B) {
11778   // Test if the values are trivially equivalent.
11779   if (A == B) return true;
11780   
11781   // Test if the values come form identical arithmetic instructions.
11782   if (isa<BinaryOperator>(A) ||
11783       isa<CastInst>(A) ||
11784       isa<PHINode>(A) ||
11785       isa<GetElementPtrInst>(A))
11786     if (Instruction *BI = dyn_cast<Instruction>(B))
11787       if (cast<Instruction>(A)->isIdenticalTo(BI))
11788         return true;
11789   
11790   // Otherwise they may not be equivalent.
11791   return false;
11792 }
11793
11794 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11795 // return the llvm.dbg.declare.
11796 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11797   if (!V->hasNUses(2))
11798     return 0;
11799   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11800        UI != E; ++UI) {
11801     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11802       return DI;
11803     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11804       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11805         return DI;
11806       }
11807   }
11808   return 0;
11809 }
11810
11811 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11812   Value *Val = SI.getOperand(0);
11813   Value *Ptr = SI.getOperand(1);
11814
11815   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11816     EraseInstFromFunction(SI);
11817     ++NumCombined;
11818     return 0;
11819   }
11820   
11821   // If the RHS is an alloca with a single use, zapify the store, making the
11822   // alloca dead.
11823   // If the RHS is an alloca with a two uses, the other one being a 
11824   // llvm.dbg.declare, zapify the store and the declare, making the
11825   // alloca dead.  We must do this to prevent declare's from affecting
11826   // codegen.
11827   if (!SI.isVolatile()) {
11828     if (Ptr->hasOneUse()) {
11829       if (isa<AllocaInst>(Ptr)) {
11830         EraseInstFromFunction(SI);
11831         ++NumCombined;
11832         return 0;
11833       }
11834       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11835         if (isa<AllocaInst>(GEP->getOperand(0))) {
11836           if (GEP->getOperand(0)->hasOneUse()) {
11837             EraseInstFromFunction(SI);
11838             ++NumCombined;
11839             return 0;
11840           }
11841           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11842             EraseInstFromFunction(*DI);
11843             EraseInstFromFunction(SI);
11844             ++NumCombined;
11845             return 0;
11846           }
11847         }
11848       }
11849     }
11850     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11851       EraseInstFromFunction(*DI);
11852       EraseInstFromFunction(SI);
11853       ++NumCombined;
11854       return 0;
11855     }
11856   }
11857
11858   // Attempt to improve the alignment.
11859   if (TD) {
11860     unsigned KnownAlign =
11861       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11862     if (KnownAlign >
11863         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11864                                   SI.getAlignment()))
11865       SI.setAlignment(KnownAlign);
11866   }
11867
11868   // Do really simple DSE, to catch cases where there are several consecutive
11869   // stores to the same location, separated by a few arithmetic operations. This
11870   // situation often occurs with bitfield accesses.
11871   BasicBlock::iterator BBI = &SI;
11872   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11873        --ScanInsts) {
11874     --BBI;
11875     // Don't count debug info directives, lest they affect codegen,
11876     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11877     // It is necessary for correctness to skip those that feed into a
11878     // llvm.dbg.declare, as these are not present when debugging is off.
11879     if (isa<DbgInfoIntrinsic>(BBI) ||
11880         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11881       ScanInsts++;
11882       continue;
11883     }    
11884     
11885     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11886       // Prev store isn't volatile, and stores to the same location?
11887       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11888                                                           SI.getOperand(1))) {
11889         ++NumDeadStore;
11890         ++BBI;
11891         EraseInstFromFunction(*PrevSI);
11892         continue;
11893       }
11894       break;
11895     }
11896     
11897     // If this is a load, we have to stop.  However, if the loaded value is from
11898     // the pointer we're loading and is producing the pointer we're storing,
11899     // then *this* store is dead (X = load P; store X -> P).
11900     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11901       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11902           !SI.isVolatile()) {
11903         EraseInstFromFunction(SI);
11904         ++NumCombined;
11905         return 0;
11906       }
11907       // Otherwise, this is a load from some other location.  Stores before it
11908       // may not be dead.
11909       break;
11910     }
11911     
11912     // Don't skip over loads or things that can modify memory.
11913     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11914       break;
11915   }
11916   
11917   
11918   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11919
11920   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11921   if (isa<ConstantPointerNull>(Ptr) &&
11922       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11923     if (!isa<UndefValue>(Val)) {
11924       SI.setOperand(0, Context->getUndef(Val->getType()));
11925       if (Instruction *U = dyn_cast<Instruction>(Val))
11926         AddToWorkList(U);  // Dropped a use.
11927       ++NumCombined;
11928     }
11929     return 0;  // Do not modify these!
11930   }
11931
11932   // store undef, Ptr -> noop
11933   if (isa<UndefValue>(Val)) {
11934     EraseInstFromFunction(SI);
11935     ++NumCombined;
11936     return 0;
11937   }
11938
11939   // If the pointer destination is a cast, see if we can fold the cast into the
11940   // source instead.
11941   if (isa<CastInst>(Ptr))
11942     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11943       return Res;
11944   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11945     if (CE->isCast())
11946       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11947         return Res;
11948
11949   
11950   // If this store is the last instruction in the basic block (possibly
11951   // excepting debug info instructions and the pointer bitcasts that feed
11952   // into them), and if the block ends with an unconditional branch, try
11953   // to move it to the successor block.
11954   BBI = &SI; 
11955   do {
11956     ++BBI;
11957   } while (isa<DbgInfoIntrinsic>(BBI) ||
11958            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11959   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11960     if (BI->isUnconditional())
11961       if (SimplifyStoreAtEndOfBlock(SI))
11962         return 0;  // xform done!
11963   
11964   return 0;
11965 }
11966
11967 /// SimplifyStoreAtEndOfBlock - Turn things like:
11968 ///   if () { *P = v1; } else { *P = v2 }
11969 /// into a phi node with a store in the successor.
11970 ///
11971 /// Simplify things like:
11972 ///   *P = v1; if () { *P = v2; }
11973 /// into a phi node with a store in the successor.
11974 ///
11975 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11976   BasicBlock *StoreBB = SI.getParent();
11977   
11978   // Check to see if the successor block has exactly two incoming edges.  If
11979   // so, see if the other predecessor contains a store to the same location.
11980   // if so, insert a PHI node (if needed) and move the stores down.
11981   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11982   
11983   // Determine whether Dest has exactly two predecessors and, if so, compute
11984   // the other predecessor.
11985   pred_iterator PI = pred_begin(DestBB);
11986   BasicBlock *OtherBB = 0;
11987   if (*PI != StoreBB)
11988     OtherBB = *PI;
11989   ++PI;
11990   if (PI == pred_end(DestBB))
11991     return false;
11992   
11993   if (*PI != StoreBB) {
11994     if (OtherBB)
11995       return false;
11996     OtherBB = *PI;
11997   }
11998   if (++PI != pred_end(DestBB))
11999     return false;
12000
12001   // Bail out if all the relevant blocks aren't distinct (this can happen,
12002   // for example, if SI is in an infinite loop)
12003   if (StoreBB == DestBB || OtherBB == DestBB)
12004     return false;
12005
12006   // Verify that the other block ends in a branch and is not otherwise empty.
12007   BasicBlock::iterator BBI = OtherBB->getTerminator();
12008   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12009   if (!OtherBr || BBI == OtherBB->begin())
12010     return false;
12011   
12012   // If the other block ends in an unconditional branch, check for the 'if then
12013   // else' case.  there is an instruction before the branch.
12014   StoreInst *OtherStore = 0;
12015   if (OtherBr->isUnconditional()) {
12016     --BBI;
12017     // Skip over debugging info.
12018     while (isa<DbgInfoIntrinsic>(BBI) ||
12019            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12020       if (BBI==OtherBB->begin())
12021         return false;
12022       --BBI;
12023     }
12024     // If this isn't a store, or isn't a store to the same location, bail out.
12025     OtherStore = dyn_cast<StoreInst>(BBI);
12026     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12027       return false;
12028   } else {
12029     // Otherwise, the other block ended with a conditional branch. If one of the
12030     // destinations is StoreBB, then we have the if/then case.
12031     if (OtherBr->getSuccessor(0) != StoreBB && 
12032         OtherBr->getSuccessor(1) != StoreBB)
12033       return false;
12034     
12035     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12036     // if/then triangle.  See if there is a store to the same ptr as SI that
12037     // lives in OtherBB.
12038     for (;; --BBI) {
12039       // Check to see if we find the matching store.
12040       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12041         if (OtherStore->getOperand(1) != SI.getOperand(1))
12042           return false;
12043         break;
12044       }
12045       // If we find something that may be using or overwriting the stored
12046       // value, or if we run out of instructions, we can't do the xform.
12047       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12048           BBI == OtherBB->begin())
12049         return false;
12050     }
12051     
12052     // In order to eliminate the store in OtherBr, we have to
12053     // make sure nothing reads or overwrites the stored value in
12054     // StoreBB.
12055     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12056       // FIXME: This should really be AA driven.
12057       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12058         return false;
12059     }
12060   }
12061   
12062   // Insert a PHI node now if we need it.
12063   Value *MergedVal = OtherStore->getOperand(0);
12064   if (MergedVal != SI.getOperand(0)) {
12065     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12066     PN->reserveOperandSpace(2);
12067     PN->addIncoming(SI.getOperand(0), SI.getParent());
12068     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12069     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12070   }
12071   
12072   // Advance to a place where it is safe to insert the new store and
12073   // insert it.
12074   BBI = DestBB->getFirstNonPHI();
12075   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12076                                     OtherStore->isVolatile()), *BBI);
12077   
12078   // Nuke the old stores.
12079   EraseInstFromFunction(SI);
12080   EraseInstFromFunction(*OtherStore);
12081   ++NumCombined;
12082   return true;
12083 }
12084
12085
12086 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12087   // Change br (not X), label True, label False to: br X, label False, True
12088   Value *X = 0;
12089   BasicBlock *TrueDest;
12090   BasicBlock *FalseDest;
12091   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12092       !isa<Constant>(X)) {
12093     // Swap Destinations and condition...
12094     BI.setCondition(X);
12095     BI.setSuccessor(0, FalseDest);
12096     BI.setSuccessor(1, TrueDest);
12097     return &BI;
12098   }
12099
12100   // Cannonicalize fcmp_one -> fcmp_oeq
12101   FCmpInst::Predicate FPred; Value *Y;
12102   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12103                              TrueDest, FalseDest), *Context))
12104     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12105          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12106       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12107       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12108       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12109       NewSCC->takeName(I);
12110       // Swap Destinations and condition...
12111       BI.setCondition(NewSCC);
12112       BI.setSuccessor(0, FalseDest);
12113       BI.setSuccessor(1, TrueDest);
12114       RemoveFromWorkList(I);
12115       I->eraseFromParent();
12116       AddToWorkList(NewSCC);
12117       return &BI;
12118     }
12119
12120   // Cannonicalize icmp_ne -> icmp_eq
12121   ICmpInst::Predicate IPred;
12122   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12123                       TrueDest, FalseDest), *Context))
12124     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12125          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12126          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12127       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12128       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12129       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12130       NewSCC->takeName(I);
12131       // Swap Destinations and condition...
12132       BI.setCondition(NewSCC);
12133       BI.setSuccessor(0, FalseDest);
12134       BI.setSuccessor(1, TrueDest);
12135       RemoveFromWorkList(I);
12136       I->eraseFromParent();;
12137       AddToWorkList(NewSCC);
12138       return &BI;
12139     }
12140
12141   return 0;
12142 }
12143
12144 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12145   Value *Cond = SI.getCondition();
12146   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12147     if (I->getOpcode() == Instruction::Add)
12148       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12149         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12150         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12151           SI.setOperand(i,
12152                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12153                                                 AddRHS));
12154         SI.setOperand(0, I->getOperand(0));
12155         AddToWorkList(I);
12156         return &SI;
12157       }
12158   }
12159   return 0;
12160 }
12161
12162 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12163   Value *Agg = EV.getAggregateOperand();
12164
12165   if (!EV.hasIndices())
12166     return ReplaceInstUsesWith(EV, Agg);
12167
12168   if (Constant *C = dyn_cast<Constant>(Agg)) {
12169     if (isa<UndefValue>(C))
12170       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12171       
12172     if (isa<ConstantAggregateZero>(C))
12173       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12174
12175     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12176       // Extract the element indexed by the first index out of the constant
12177       Value *V = C->getOperand(*EV.idx_begin());
12178       if (EV.getNumIndices() > 1)
12179         // Extract the remaining indices out of the constant indexed by the
12180         // first index
12181         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12182       else
12183         return ReplaceInstUsesWith(EV, V);
12184     }
12185     return 0; // Can't handle other constants
12186   } 
12187   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12188     // We're extracting from an insertvalue instruction, compare the indices
12189     const unsigned *exti, *exte, *insi, *inse;
12190     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12191          exte = EV.idx_end(), inse = IV->idx_end();
12192          exti != exte && insi != inse;
12193          ++exti, ++insi) {
12194       if (*insi != *exti)
12195         // The insert and extract both reference distinctly different elements.
12196         // This means the extract is not influenced by the insert, and we can
12197         // replace the aggregate operand of the extract with the aggregate
12198         // operand of the insert. i.e., replace
12199         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12200         // %E = extractvalue { i32, { i32 } } %I, 0
12201         // with
12202         // %E = extractvalue { i32, { i32 } } %A, 0
12203         return ExtractValueInst::Create(IV->getAggregateOperand(),
12204                                         EV.idx_begin(), EV.idx_end());
12205     }
12206     if (exti == exte && insi == inse)
12207       // Both iterators are at the end: Index lists are identical. Replace
12208       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12209       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12210       // with "i32 42"
12211       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12212     if (exti == exte) {
12213       // The extract list is a prefix of the insert list. i.e. replace
12214       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12215       // %E = extractvalue { i32, { i32 } } %I, 1
12216       // with
12217       // %X = extractvalue { i32, { i32 } } %A, 1
12218       // %E = insertvalue { i32 } %X, i32 42, 0
12219       // by switching the order of the insert and extract (though the
12220       // insertvalue should be left in, since it may have other uses).
12221       Value *NewEV = InsertNewInstBefore(
12222         ExtractValueInst::Create(IV->getAggregateOperand(),
12223                                  EV.idx_begin(), EV.idx_end()),
12224         EV);
12225       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12226                                      insi, inse);
12227     }
12228     if (insi == inse)
12229       // The insert list is a prefix of the extract list
12230       // We can simply remove the common indices from the extract and make it
12231       // operate on the inserted value instead of the insertvalue result.
12232       // i.e., replace
12233       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12234       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12235       // with
12236       // %E extractvalue { i32 } { i32 42 }, 0
12237       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12238                                       exti, exte);
12239   }
12240   // Can't simplify extracts from other values. Note that nested extracts are
12241   // already simplified implicitely by the above (extract ( extract (insert) )
12242   // will be translated into extract ( insert ( extract ) ) first and then just
12243   // the value inserted, if appropriate).
12244   return 0;
12245 }
12246
12247 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12248 /// is to leave as a vector operation.
12249 static bool CheapToScalarize(Value *V, bool isConstant) {
12250   if (isa<ConstantAggregateZero>(V)) 
12251     return true;
12252   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12253     if (isConstant) return true;
12254     // If all elts are the same, we can extract.
12255     Constant *Op0 = C->getOperand(0);
12256     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12257       if (C->getOperand(i) != Op0)
12258         return false;
12259     return true;
12260   }
12261   Instruction *I = dyn_cast<Instruction>(V);
12262   if (!I) return false;
12263   
12264   // Insert element gets simplified to the inserted element or is deleted if
12265   // this is constant idx extract element and its a constant idx insertelt.
12266   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12267       isa<ConstantInt>(I->getOperand(2)))
12268     return true;
12269   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12270     return true;
12271   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12272     if (BO->hasOneUse() &&
12273         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12274          CheapToScalarize(BO->getOperand(1), isConstant)))
12275       return true;
12276   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12277     if (CI->hasOneUse() &&
12278         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12279          CheapToScalarize(CI->getOperand(1), isConstant)))
12280       return true;
12281   
12282   return false;
12283 }
12284
12285 /// Read and decode a shufflevector mask.
12286 ///
12287 /// It turns undef elements into values that are larger than the number of
12288 /// elements in the input.
12289 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12290   unsigned NElts = SVI->getType()->getNumElements();
12291   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12292     return std::vector<unsigned>(NElts, 0);
12293   if (isa<UndefValue>(SVI->getOperand(2)))
12294     return std::vector<unsigned>(NElts, 2*NElts);
12295
12296   std::vector<unsigned> Result;
12297   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12298   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12299     if (isa<UndefValue>(*i))
12300       Result.push_back(NElts*2);  // undef -> 8
12301     else
12302       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12303   return Result;
12304 }
12305
12306 /// FindScalarElement - Given a vector and an element number, see if the scalar
12307 /// value is already around as a register, for example if it were inserted then
12308 /// extracted from the vector.
12309 static Value *FindScalarElement(Value *V, unsigned EltNo,
12310                                 LLVMContext *Context) {
12311   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12312   const VectorType *PTy = cast<VectorType>(V->getType());
12313   unsigned Width = PTy->getNumElements();
12314   if (EltNo >= Width)  // Out of range access.
12315     return Context->getUndef(PTy->getElementType());
12316   
12317   if (isa<UndefValue>(V))
12318     return Context->getUndef(PTy->getElementType());
12319   else if (isa<ConstantAggregateZero>(V))
12320     return Context->getNullValue(PTy->getElementType());
12321   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12322     return CP->getOperand(EltNo);
12323   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12324     // If this is an insert to a variable element, we don't know what it is.
12325     if (!isa<ConstantInt>(III->getOperand(2))) 
12326       return 0;
12327     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12328     
12329     // If this is an insert to the element we are looking for, return the
12330     // inserted value.
12331     if (EltNo == IIElt) 
12332       return III->getOperand(1);
12333     
12334     // Otherwise, the insertelement doesn't modify the value, recurse on its
12335     // vector input.
12336     return FindScalarElement(III->getOperand(0), EltNo, Context);
12337   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12338     unsigned LHSWidth =
12339       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12340     unsigned InEl = getShuffleMask(SVI)[EltNo];
12341     if (InEl < LHSWidth)
12342       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12343     else if (InEl < LHSWidth*2)
12344       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12345     else
12346       return Context->getUndef(PTy->getElementType());
12347   }
12348   
12349   // Otherwise, we don't know.
12350   return 0;
12351 }
12352
12353 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12354   // If vector val is undef, replace extract with scalar undef.
12355   if (isa<UndefValue>(EI.getOperand(0)))
12356     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12357
12358   // If vector val is constant 0, replace extract with scalar 0.
12359   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12360     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12361   
12362   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12363     // If vector val is constant with all elements the same, replace EI with
12364     // that element. When the elements are not identical, we cannot replace yet
12365     // (we do that below, but only when the index is constant).
12366     Constant *op0 = C->getOperand(0);
12367     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12368       if (C->getOperand(i) != op0) {
12369         op0 = 0; 
12370         break;
12371       }
12372     if (op0)
12373       return ReplaceInstUsesWith(EI, op0);
12374   }
12375   
12376   // If extracting a specified index from the vector, see if we can recursively
12377   // find a previously computed scalar that was inserted into the vector.
12378   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12379     unsigned IndexVal = IdxC->getZExtValue();
12380     unsigned VectorWidth = 
12381       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12382       
12383     // If this is extracting an invalid index, turn this into undef, to avoid
12384     // crashing the code below.
12385     if (IndexVal >= VectorWidth)
12386       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12387     
12388     // This instruction only demands the single element from the input vector.
12389     // If the input vector has a single use, simplify it based on this use
12390     // property.
12391     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12392       APInt UndefElts(VectorWidth, 0);
12393       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12394       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12395                                                 DemandedMask, UndefElts)) {
12396         EI.setOperand(0, V);
12397         return &EI;
12398       }
12399     }
12400     
12401     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12402       return ReplaceInstUsesWith(EI, Elt);
12403     
12404     // If the this extractelement is directly using a bitcast from a vector of
12405     // the same number of elements, see if we can find the source element from
12406     // it.  In this case, we will end up needing to bitcast the scalars.
12407     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12408       if (const VectorType *VT = 
12409               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12410         if (VT->getNumElements() == VectorWidth)
12411           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12412                                              IndexVal, Context))
12413             return new BitCastInst(Elt, EI.getType());
12414     }
12415   }
12416   
12417   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12418     if (I->hasOneUse()) {
12419       // Push extractelement into predecessor operation if legal and
12420       // profitable to do so
12421       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12422         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12423         if (CheapToScalarize(BO, isConstantElt)) {
12424           ExtractElementInst *newEI0 = 
12425             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12426                                    EI.getName()+".lhs");
12427           ExtractElementInst *newEI1 =
12428             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12429                                    EI.getName()+".rhs");
12430           InsertNewInstBefore(newEI0, EI);
12431           InsertNewInstBefore(newEI1, EI);
12432           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12433         }
12434       } else if (isa<LoadInst>(I)) {
12435         unsigned AS = 
12436           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12437         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12438                                   Context->getPointerType(EI.getType(), AS),EI);
12439         GetElementPtrInst *GEP =
12440           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12441         InsertNewInstBefore(GEP, EI);
12442         return new LoadInst(GEP);
12443       }
12444     }
12445     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12446       // Extracting the inserted element?
12447       if (IE->getOperand(2) == EI.getOperand(1))
12448         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12449       // If the inserted and extracted elements are constants, they must not
12450       // be the same value, extract from the pre-inserted value instead.
12451       if (isa<Constant>(IE->getOperand(2)) &&
12452           isa<Constant>(EI.getOperand(1))) {
12453         AddUsesToWorkList(EI);
12454         EI.setOperand(0, IE->getOperand(0));
12455         return &EI;
12456       }
12457     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12458       // If this is extracting an element from a shufflevector, figure out where
12459       // it came from and extract from the appropriate input element instead.
12460       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12461         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12462         Value *Src;
12463         unsigned LHSWidth =
12464           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12465
12466         if (SrcIdx < LHSWidth)
12467           Src = SVI->getOperand(0);
12468         else if (SrcIdx < LHSWidth*2) {
12469           SrcIdx -= LHSWidth;
12470           Src = SVI->getOperand(1);
12471         } else {
12472           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12473         }
12474         return ExtractElementInst::Create(Src,
12475                          ConstantInt::get(Type::Int32Ty, SrcIdx, false));
12476       }
12477     }
12478     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12479   }
12480   return 0;
12481 }
12482
12483 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12484 /// elements from either LHS or RHS, return the shuffle mask and true. 
12485 /// Otherwise, return false.
12486 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12487                                          std::vector<Constant*> &Mask,
12488                                          LLVMContext *Context) {
12489   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12490          "Invalid CollectSingleShuffleElements");
12491   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12492
12493   if (isa<UndefValue>(V)) {
12494     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12495     return true;
12496   } else if (V == LHS) {
12497     for (unsigned i = 0; i != NumElts; ++i)
12498       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12499     return true;
12500   } else if (V == RHS) {
12501     for (unsigned i = 0; i != NumElts; ++i)
12502       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12503     return true;
12504   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12505     // If this is an insert of an extract from some other vector, include it.
12506     Value *VecOp    = IEI->getOperand(0);
12507     Value *ScalarOp = IEI->getOperand(1);
12508     Value *IdxOp    = IEI->getOperand(2);
12509     
12510     if (!isa<ConstantInt>(IdxOp))
12511       return false;
12512     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12513     
12514     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12515       // Okay, we can handle this if the vector we are insertinting into is
12516       // transitively ok.
12517       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12518         // If so, update the mask to reflect the inserted undef.
12519         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12520         return true;
12521       }      
12522     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12523       if (isa<ConstantInt>(EI->getOperand(1)) &&
12524           EI->getOperand(0)->getType() == V->getType()) {
12525         unsigned ExtractedIdx =
12526           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12527         
12528         // This must be extracting from either LHS or RHS.
12529         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12530           // Okay, we can handle this if the vector we are insertinting into is
12531           // transitively ok.
12532           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12533             // If so, update the mask to reflect the inserted value.
12534             if (EI->getOperand(0) == LHS) {
12535               Mask[InsertedIdx % NumElts] = 
12536                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12537             } else {
12538               assert(EI->getOperand(0) == RHS);
12539               Mask[InsertedIdx % NumElts] = 
12540                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12541               
12542             }
12543             return true;
12544           }
12545         }
12546       }
12547     }
12548   }
12549   // TODO: Handle shufflevector here!
12550   
12551   return false;
12552 }
12553
12554 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12555 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12556 /// that computes V and the LHS value of the shuffle.
12557 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12558                                      Value *&RHS, LLVMContext *Context) {
12559   assert(isa<VectorType>(V->getType()) && 
12560          (RHS == 0 || V->getType() == RHS->getType()) &&
12561          "Invalid shuffle!");
12562   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12563
12564   if (isa<UndefValue>(V)) {
12565     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12566     return V;
12567   } else if (isa<ConstantAggregateZero>(V)) {
12568     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12569     return V;
12570   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12571     // If this is an insert of an extract from some other vector, include it.
12572     Value *VecOp    = IEI->getOperand(0);
12573     Value *ScalarOp = IEI->getOperand(1);
12574     Value *IdxOp    = IEI->getOperand(2);
12575     
12576     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12577       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12578           EI->getOperand(0)->getType() == V->getType()) {
12579         unsigned ExtractedIdx =
12580           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12581         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12582         
12583         // Either the extracted from or inserted into vector must be RHSVec,
12584         // otherwise we'd end up with a shuffle of three inputs.
12585         if (EI->getOperand(0) == RHS || RHS == 0) {
12586           RHS = EI->getOperand(0);
12587           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12588           Mask[InsertedIdx % NumElts] = 
12589             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12590           return V;
12591         }
12592         
12593         if (VecOp == RHS) {
12594           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12595                                             RHS, Context);
12596           // Everything but the extracted element is replaced with the RHS.
12597           for (unsigned i = 0; i != NumElts; ++i) {
12598             if (i != InsertedIdx)
12599               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12600           }
12601           return V;
12602         }
12603         
12604         // If this insertelement is a chain that comes from exactly these two
12605         // vectors, return the vector and the effective shuffle.
12606         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12607                                          Context))
12608           return EI->getOperand(0);
12609         
12610       }
12611     }
12612   }
12613   // TODO: Handle shufflevector here!
12614   
12615   // Otherwise, can't do anything fancy.  Return an identity vector.
12616   for (unsigned i = 0; i != NumElts; ++i)
12617     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12618   return V;
12619 }
12620
12621 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12622   Value *VecOp    = IE.getOperand(0);
12623   Value *ScalarOp = IE.getOperand(1);
12624   Value *IdxOp    = IE.getOperand(2);
12625   
12626   // Inserting an undef or into an undefined place, remove this.
12627   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12628     ReplaceInstUsesWith(IE, VecOp);
12629   
12630   // If the inserted element was extracted from some other vector, and if the 
12631   // indexes are constant, try to turn this into a shufflevector operation.
12632   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12633     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12634         EI->getOperand(0)->getType() == IE.getType()) {
12635       unsigned NumVectorElts = IE.getType()->getNumElements();
12636       unsigned ExtractedIdx =
12637         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12638       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12639       
12640       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12641         return ReplaceInstUsesWith(IE, VecOp);
12642       
12643       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12644         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12645       
12646       // If we are extracting a value from a vector, then inserting it right
12647       // back into the same place, just use the input vector.
12648       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12649         return ReplaceInstUsesWith(IE, VecOp);      
12650       
12651       // We could theoretically do this for ANY input.  However, doing so could
12652       // turn chains of insertelement instructions into a chain of shufflevector
12653       // instructions, and right now we do not merge shufflevectors.  As such,
12654       // only do this in a situation where it is clear that there is benefit.
12655       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12656         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12657         // the values of VecOp, except then one read from EIOp0.
12658         // Build a new shuffle mask.
12659         std::vector<Constant*> Mask;
12660         if (isa<UndefValue>(VecOp))
12661           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12662         else {
12663           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12664           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12665                                                        NumVectorElts));
12666         } 
12667         Mask[InsertedIdx] = 
12668                            ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12669         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12670                                      Context->getConstantVector(Mask));
12671       }
12672       
12673       // If this insertelement isn't used by some other insertelement, turn it
12674       // (and any insertelements it points to), into one big shuffle.
12675       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12676         std::vector<Constant*> Mask;
12677         Value *RHS = 0;
12678         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12679         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12680         // We now have a shuffle of LHS, RHS, Mask.
12681         return new ShuffleVectorInst(LHS, RHS,
12682                                      Context->getConstantVector(Mask));
12683       }
12684     }
12685   }
12686
12687   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12688   APInt UndefElts(VWidth, 0);
12689   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12690   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12691     return &IE;
12692
12693   return 0;
12694 }
12695
12696
12697 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12698   Value *LHS = SVI.getOperand(0);
12699   Value *RHS = SVI.getOperand(1);
12700   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12701
12702   bool MadeChange = false;
12703
12704   // Undefined shuffle mask -> undefined value.
12705   if (isa<UndefValue>(SVI.getOperand(2)))
12706     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12707
12708   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12709
12710   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12711     return 0;
12712
12713   APInt UndefElts(VWidth, 0);
12714   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12715   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12716     LHS = SVI.getOperand(0);
12717     RHS = SVI.getOperand(1);
12718     MadeChange = true;
12719   }
12720   
12721   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12722   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12723   if (LHS == RHS || isa<UndefValue>(LHS)) {
12724     if (isa<UndefValue>(LHS) && LHS == RHS) {
12725       // shuffle(undef,undef,mask) -> undef.
12726       return ReplaceInstUsesWith(SVI, LHS);
12727     }
12728     
12729     // Remap any references to RHS to use LHS.
12730     std::vector<Constant*> Elts;
12731     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12732       if (Mask[i] >= 2*e)
12733         Elts.push_back(Context->getUndef(Type::Int32Ty));
12734       else {
12735         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12736             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12737           Mask[i] = 2*e;     // Turn into undef.
12738           Elts.push_back(Context->getUndef(Type::Int32Ty));
12739         } else {
12740           Mask[i] = Mask[i] % e;  // Force to LHS.
12741           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12742         }
12743       }
12744     }
12745     SVI.setOperand(0, SVI.getOperand(1));
12746     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12747     SVI.setOperand(2, Context->getConstantVector(Elts));
12748     LHS = SVI.getOperand(0);
12749     RHS = SVI.getOperand(1);
12750     MadeChange = true;
12751   }
12752   
12753   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12754   bool isLHSID = true, isRHSID = true;
12755     
12756   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12757     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12758     // Is this an identity shuffle of the LHS value?
12759     isLHSID &= (Mask[i] == i);
12760       
12761     // Is this an identity shuffle of the RHS value?
12762     isRHSID &= (Mask[i]-e == i);
12763   }
12764
12765   // Eliminate identity shuffles.
12766   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12767   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12768   
12769   // If the LHS is a shufflevector itself, see if we can combine it with this
12770   // one without producing an unusual shuffle.  Here we are really conservative:
12771   // we are absolutely afraid of producing a shuffle mask not in the input
12772   // program, because the code gen may not be smart enough to turn a merged
12773   // shuffle into two specific shuffles: it may produce worse code.  As such,
12774   // we only merge two shuffles if the result is one of the two input shuffle
12775   // masks.  In this case, merging the shuffles just removes one instruction,
12776   // which we know is safe.  This is good for things like turning:
12777   // (splat(splat)) -> splat.
12778   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12779     if (isa<UndefValue>(RHS)) {
12780       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12781
12782       std::vector<unsigned> NewMask;
12783       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12784         if (Mask[i] >= 2*e)
12785           NewMask.push_back(2*e);
12786         else
12787           NewMask.push_back(LHSMask[Mask[i]]);
12788       
12789       // If the result mask is equal to the src shuffle or this shuffle mask, do
12790       // the replacement.
12791       if (NewMask == LHSMask || NewMask == Mask) {
12792         unsigned LHSInNElts =
12793           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12794         std::vector<Constant*> Elts;
12795         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12796           if (NewMask[i] >= LHSInNElts*2) {
12797             Elts.push_back(Context->getUndef(Type::Int32Ty));
12798           } else {
12799             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12800           }
12801         }
12802         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12803                                      LHSSVI->getOperand(1),
12804                                      Context->getConstantVector(Elts));
12805       }
12806     }
12807   }
12808
12809   return MadeChange ? &SVI : 0;
12810 }
12811
12812
12813
12814
12815 /// TryToSinkInstruction - Try to move the specified instruction from its
12816 /// current block into the beginning of DestBlock, which can only happen if it's
12817 /// safe to move the instruction past all of the instructions between it and the
12818 /// end of its block.
12819 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12820   assert(I->hasOneUse() && "Invariants didn't hold!");
12821
12822   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12823   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12824     return false;
12825
12826   // Do not sink alloca instructions out of the entry block.
12827   if (isa<AllocaInst>(I) && I->getParent() ==
12828         &DestBlock->getParent()->getEntryBlock())
12829     return false;
12830
12831   // We can only sink load instructions if there is nothing between the load and
12832   // the end of block that could change the value.
12833   if (I->mayReadFromMemory()) {
12834     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12835          Scan != E; ++Scan)
12836       if (Scan->mayWriteToMemory())
12837         return false;
12838   }
12839
12840   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12841
12842   CopyPrecedingStopPoint(I, InsertPos);
12843   I->moveBefore(InsertPos);
12844   ++NumSunkInst;
12845   return true;
12846 }
12847
12848
12849 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12850 /// all reachable code to the worklist.
12851 ///
12852 /// This has a couple of tricks to make the code faster and more powerful.  In
12853 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12854 /// them to the worklist (this significantly speeds up instcombine on code where
12855 /// many instructions are dead or constant).  Additionally, if we find a branch
12856 /// whose condition is a known constant, we only visit the reachable successors.
12857 ///
12858 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12859                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12860                                        InstCombiner &IC,
12861                                        const TargetData *TD) {
12862   SmallVector<BasicBlock*, 256> Worklist;
12863   Worklist.push_back(BB);
12864
12865   while (!Worklist.empty()) {
12866     BB = Worklist.back();
12867     Worklist.pop_back();
12868     
12869     // We have now visited this block!  If we've already been here, ignore it.
12870     if (!Visited.insert(BB)) continue;
12871
12872     DbgInfoIntrinsic *DBI_Prev = NULL;
12873     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12874       Instruction *Inst = BBI++;
12875       
12876       // DCE instruction if trivially dead.
12877       if (isInstructionTriviallyDead(Inst)) {
12878         ++NumDeadInst;
12879         DOUT << "IC: DCE: " << *Inst;
12880         Inst->eraseFromParent();
12881         continue;
12882       }
12883       
12884       // ConstantProp instruction if trivially constant.
12885       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12886         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12887         Inst->replaceAllUsesWith(C);
12888         ++NumConstProp;
12889         Inst->eraseFromParent();
12890         continue;
12891       }
12892      
12893       // If there are two consecutive llvm.dbg.stoppoint calls then
12894       // it is likely that the optimizer deleted code in between these
12895       // two intrinsics. 
12896       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12897       if (DBI_Next) {
12898         if (DBI_Prev
12899             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12900             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12901           IC.RemoveFromWorkList(DBI_Prev);
12902           DBI_Prev->eraseFromParent();
12903         }
12904         DBI_Prev = DBI_Next;
12905       } else {
12906         DBI_Prev = 0;
12907       }
12908
12909       IC.AddToWorkList(Inst);
12910     }
12911
12912     // Recursively visit successors.  If this is a branch or switch on a
12913     // constant, only visit the reachable successor.
12914     TerminatorInst *TI = BB->getTerminator();
12915     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12916       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12917         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12918         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12919         Worklist.push_back(ReachableBB);
12920         continue;
12921       }
12922     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12923       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12924         // See if this is an explicit destination.
12925         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12926           if (SI->getCaseValue(i) == Cond) {
12927             BasicBlock *ReachableBB = SI->getSuccessor(i);
12928             Worklist.push_back(ReachableBB);
12929             continue;
12930           }
12931         
12932         // Otherwise it is the default destination.
12933         Worklist.push_back(SI->getSuccessor(0));
12934         continue;
12935       }
12936     }
12937     
12938     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12939       Worklist.push_back(TI->getSuccessor(i));
12940   }
12941 }
12942
12943 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12944   bool Changed = false;
12945   TD = getAnalysisIfAvailable<TargetData>();
12946   
12947   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12948         << F.getNameStr() << "\n");
12949
12950   {
12951     // Do a depth-first traversal of the function, populate the worklist with
12952     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12953     // track of which blocks we visit.
12954     SmallPtrSet<BasicBlock*, 64> Visited;
12955     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12956
12957     // Do a quick scan over the function.  If we find any blocks that are
12958     // unreachable, remove any instructions inside of them.  This prevents
12959     // the instcombine code from having to deal with some bad special cases.
12960     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12961       if (!Visited.count(BB)) {
12962         Instruction *Term = BB->getTerminator();
12963         while (Term != BB->begin()) {   // Remove instrs bottom-up
12964           BasicBlock::iterator I = Term; --I;
12965
12966           DOUT << "IC: DCE: " << *I;
12967           // A debug intrinsic shouldn't force another iteration if we weren't
12968           // going to do one without it.
12969           if (!isa<DbgInfoIntrinsic>(I)) {
12970             ++NumDeadInst;
12971             Changed = true;
12972           }
12973           if (!I->use_empty())
12974             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12975           I->eraseFromParent();
12976         }
12977       }
12978   }
12979
12980   while (!Worklist.empty()) {
12981     Instruction *I = RemoveOneFromWorkList();
12982     if (I == 0) continue;  // skip null values.
12983
12984     // Check to see if we can DCE the instruction.
12985     if (isInstructionTriviallyDead(I)) {
12986       // Add operands to the worklist.
12987       if (I->getNumOperands() < 4)
12988         AddUsesToWorkList(*I);
12989       ++NumDeadInst;
12990
12991       DOUT << "IC: DCE: " << *I;
12992
12993       I->eraseFromParent();
12994       RemoveFromWorkList(I);
12995       Changed = true;
12996       continue;
12997     }
12998
12999     // Instruction isn't dead, see if we can constant propagate it.
13000     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13001       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13002
13003       // Add operands to the worklist.
13004       AddUsesToWorkList(*I);
13005       ReplaceInstUsesWith(*I, C);
13006
13007       ++NumConstProp;
13008       I->eraseFromParent();
13009       RemoveFromWorkList(I);
13010       Changed = true;
13011       continue;
13012     }
13013
13014     if (TD) {
13015       // See if we can constant fold its operands.
13016       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13017         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13018           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13019                                   F.getContext(), TD))
13020             if (NewC != CE) {
13021               i->set(NewC);
13022               Changed = true;
13023             }
13024     }
13025
13026     // See if we can trivially sink this instruction to a successor basic block.
13027     if (I->hasOneUse()) {
13028       BasicBlock *BB = I->getParent();
13029       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13030       if (UserParent != BB) {
13031         bool UserIsSuccessor = false;
13032         // See if the user is one of our successors.
13033         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13034           if (*SI == UserParent) {
13035             UserIsSuccessor = true;
13036             break;
13037           }
13038
13039         // If the user is one of our immediate successors, and if that successor
13040         // only has us as a predecessors (we'd have to split the critical edge
13041         // otherwise), we can keep going.
13042         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13043             next(pred_begin(UserParent)) == pred_end(UserParent))
13044           // Okay, the CFG is simple enough, try to sink this instruction.
13045           Changed |= TryToSinkInstruction(I, UserParent);
13046       }
13047     }
13048
13049     // Now that we have an instruction, try combining it to simplify it...
13050 #ifndef NDEBUG
13051     std::string OrigI;
13052 #endif
13053     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13054     if (Instruction *Result = visit(*I)) {
13055       ++NumCombined;
13056       // Should we replace the old instruction with a new one?
13057       if (Result != I) {
13058         DOUT << "IC: Old = " << *I
13059              << "    New = " << *Result;
13060
13061         // Everything uses the new instruction now.
13062         I->replaceAllUsesWith(Result);
13063
13064         // Push the new instruction and any users onto the worklist.
13065         AddToWorkList(Result);
13066         AddUsersToWorkList(*Result);
13067
13068         // Move the name to the new instruction first.
13069         Result->takeName(I);
13070
13071         // Insert the new instruction into the basic block...
13072         BasicBlock *InstParent = I->getParent();
13073         BasicBlock::iterator InsertPos = I;
13074
13075         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13076           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13077             ++InsertPos;
13078
13079         InstParent->getInstList().insert(InsertPos, Result);
13080
13081         // Make sure that we reprocess all operands now that we reduced their
13082         // use counts.
13083         AddUsesToWorkList(*I);
13084
13085         // Instructions can end up on the worklist more than once.  Make sure
13086         // we do not process an instruction that has been deleted.
13087         RemoveFromWorkList(I);
13088
13089         // Erase the old instruction.
13090         InstParent->getInstList().erase(I);
13091       } else {
13092 #ifndef NDEBUG
13093         DOUT << "IC: Mod = " << OrigI
13094              << "    New = " << *I;
13095 #endif
13096
13097         // If the instruction was modified, it's possible that it is now dead.
13098         // if so, remove it.
13099         if (isInstructionTriviallyDead(I)) {
13100           // Make sure we process all operands now that we are reducing their
13101           // use counts.
13102           AddUsesToWorkList(*I);
13103
13104           // Instructions may end up in the worklist more than once.  Erase all
13105           // occurrences of this instruction.
13106           RemoveFromWorkList(I);
13107           I->eraseFromParent();
13108         } else {
13109           AddToWorkList(I);
13110           AddUsersToWorkList(*I);
13111         }
13112       }
13113       Changed = true;
13114     }
13115   }
13116
13117   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13118     
13119   // Do an explicit clear, this shrinks the map if needed.
13120   WorklistMap.clear();
13121   return Changed;
13122 }
13123
13124
13125 bool InstCombiner::runOnFunction(Function &F) {
13126   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13127   Context = &F.getContext();
13128   
13129   bool EverMadeChange = false;
13130
13131   // Iterate while there is work to do.
13132   unsigned Iteration = 0;
13133   while (DoOneIteration(F, Iteration++))
13134     EverMadeChange = true;
13135   return EverMadeChange;
13136 }
13137
13138 FunctionPass *llvm::createInstructionCombiningPass() {
13139   return new InstCombiner();
13140 }