Fix some typos in a comment.
[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/ADT/DenseMap.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/SmallPtrSet.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include <algorithm>
64 #include <climits>
65 #include <sstream>
66 using namespace llvm;
67 using namespace llvm::PatternMatch;
68
69 STATISTIC(NumCombined , "Number of insts combined");
70 STATISTIC(NumConstProp, "Number of constant folds");
71 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73 STATISTIC(NumSunkInst , "Number of instructions sunk");
74
75 namespace {
76   class VISIBILITY_HIDDEN InstCombiner
77     : public FunctionPass,
78       public InstVisitor<InstCombiner, Instruction*> {
79     // Worklist of all of the instructions that need to be simplified.
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     TargetData *TD;
83     bool MustPreserveLCSSA;
84   public:
85     static char ID; // Pass identification, replacement for typeid
86     InstCombiner() : FunctionPass(&ID) {}
87
88     LLVMContext *getContext() { return Context; }
89
90     /// AddToWorkList - Add the specified instruction to the worklist if it
91     /// isn't already in it.
92     void AddToWorkList(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     // RemoveFromWorkList - remove I from the worklist if it exists.
98     void RemoveFromWorkList(Instruction *I) {
99       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100       if (It == WorklistMap.end()) return; // Not in worklist.
101       
102       // Don't bother moving everything down, just null out the slot.
103       Worklist[It->second] = 0;
104       
105       WorklistMap.erase(It);
106     }
107     
108     Instruction *RemoveOneFromWorkList() {
109       Instruction *I = Worklist.back();
110       Worklist.pop_back();
111       WorklistMap.erase(I);
112       return I;
113     }
114
115     
116     /// AddUsersToWorkList - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorkList(Value &I) {
121       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
122            UI != UE; ++UI)
123         AddToWorkList(cast<Instruction>(*UI));
124     }
125
126     /// AddUsesToWorkList - When an instruction is simplified, add operands to
127     /// the work lists because they might get more simplified now.
128     ///
129     void AddUsesToWorkList(Instruction &I) {
130       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
131         if (Instruction *Op = dyn_cast<Instruction>(*i))
132           AddToWorkList(Op);
133     }
134     
135     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
136     /// dead.  Add all of its operands to the worklist, turning them into
137     /// undef's to reduce the number of uses of those instructions.
138     ///
139     /// Return the specified operand before it is turned into an undef.
140     ///
141     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
142       Value *R = I.getOperand(op);
143       
144       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
145         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
146           AddToWorkList(Op);
147           // Set the operand to undef to drop the use.
148           *i = Context->getUndef(Op->getType());
149         }
150       
151       return R;
152     }
153
154   public:
155     virtual bool runOnFunction(Function &F);
156     
157     bool DoOneIteration(Function &F, unsigned ItNum);
158
159     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
160       AU.addRequired<TargetData>();
161       AU.addPreservedID(LCSSAID);
162       AU.setPreservesCFG();
163     }
164
165     TargetData &getTargetData() const { return *TD; }
166
167     // Visitation implementation - Implement instruction combining for different
168     // instruction types.  The semantics are as follows:
169     // Return Value:
170     //    null        - No change was made
171     //     I          - Change was made, I is still valid, I may be dead though
172     //   otherwise    - Change was made, replace I with returned instruction
173     //
174     Instruction *visitAdd(BinaryOperator &I);
175     Instruction *visitFAdd(BinaryOperator &I);
176     Instruction *visitSub(BinaryOperator &I);
177     Instruction *visitFSub(BinaryOperator &I);
178     Instruction *visitMul(BinaryOperator &I);
179     Instruction *visitFMul(BinaryOperator &I);
180     Instruction *visitURem(BinaryOperator &I);
181     Instruction *visitSRem(BinaryOperator &I);
182     Instruction *visitFRem(BinaryOperator &I);
183     bool SimplifyDivRemOfSelect(BinaryOperator &I);
184     Instruction *commonRemTransforms(BinaryOperator &I);
185     Instruction *commonIRemTransforms(BinaryOperator &I);
186     Instruction *commonDivTransforms(BinaryOperator &I);
187     Instruction *commonIDivTransforms(BinaryOperator &I);
188     Instruction *visitUDiv(BinaryOperator &I);
189     Instruction *visitSDiv(BinaryOperator &I);
190     Instruction *visitFDiv(BinaryOperator &I);
191     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
192     Instruction *visitAnd(BinaryOperator &I);
193     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
194     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
195                                      Value *A, Value *B, Value *C);
196     Instruction *visitOr (BinaryOperator &I);
197     Instruction *visitXor(BinaryOperator &I);
198     Instruction *visitShl(BinaryOperator &I);
199     Instruction *visitAShr(BinaryOperator &I);
200     Instruction *visitLShr(BinaryOperator &I);
201     Instruction *commonShiftTransforms(BinaryOperator &I);
202     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203                                       Constant *RHSC);
204     Instruction *visitFCmpInst(FCmpInst &I);
205     Instruction *visitICmpInst(ICmpInst &I);
206     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
207     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208                                                 Instruction *LHS,
209                                                 ConstantInt *RHS);
210     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211                                 ConstantInt *DivRHS);
212
213     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214                              ICmpInst::Predicate Cond, Instruction &I);
215     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
216                                      BinaryOperator &I);
217     Instruction *commonCastTransforms(CastInst &CI);
218     Instruction *commonIntCastTransforms(CastInst &CI);
219     Instruction *commonPointerCastTransforms(CastInst &CI);
220     Instruction *visitTrunc(TruncInst &CI);
221     Instruction *visitZExt(ZExtInst &CI);
222     Instruction *visitSExt(SExtInst &CI);
223     Instruction *visitFPTrunc(FPTruncInst &CI);
224     Instruction *visitFPExt(CastInst &CI);
225     Instruction *visitFPToUI(FPToUIInst &FI);
226     Instruction *visitFPToSI(FPToSIInst &FI);
227     Instruction *visitUIToFP(CastInst &CI);
228     Instruction *visitSIToFP(CastInst &CI);
229     Instruction *visitPtrToInt(PtrToIntInst &CI);
230     Instruction *visitIntToPtr(IntToPtrInst &CI);
231     Instruction *visitBitCast(BitCastInst &CI);
232     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233                                 Instruction *FI);
234     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
235     Instruction *visitSelectInst(SelectInst &SI);
236     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
237     Instruction *visitCallInst(CallInst &CI);
238     Instruction *visitInvokeInst(InvokeInst &II);
239     Instruction *visitPHINode(PHINode &PN);
240     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
241     Instruction *visitAllocationInst(AllocationInst &AI);
242     Instruction *visitFreeInst(FreeInst &FI);
243     Instruction *visitLoadInst(LoadInst &LI);
244     Instruction *visitStoreInst(StoreInst &SI);
245     Instruction *visitBranchInst(BranchInst &BI);
246     Instruction *visitSwitchInst(SwitchInst &SI);
247     Instruction *visitInsertElementInst(InsertElementInst &IE);
248     Instruction *visitExtractElementInst(ExtractElementInst &EI);
249     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
250     Instruction *visitExtractValueInst(ExtractValueInst &EV);
251
252     // visitInstruction - Specify what to return for unhandled instructions...
253     Instruction *visitInstruction(Instruction &I) { return 0; }
254
255   private:
256     Instruction *visitCallSite(CallSite CS);
257     bool transformConstExprCastCall(CallSite CS);
258     Instruction *transformCallThroughTrampoline(CallSite CS);
259     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260                                    bool DoXform = true);
261     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
262     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
264
265   public:
266     // InsertNewInstBefore - insert an instruction New before instruction Old
267     // in the program.  Add the new instruction to the worklist.
268     //
269     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
270       assert(New && New->getParent() == 0 &&
271              "New instruction already inserted into a basic block!");
272       BasicBlock *BB = Old.getParent();
273       BB->getInstList().insert(&Old, New);  // Insert inst
274       AddToWorkList(New);
275       return New;
276     }
277
278     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279     /// This also adds the cast to the worklist.  Finally, this returns the
280     /// cast.
281     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282                             Instruction &Pos) {
283       if (V->getType() == Ty) return V;
284
285       if (Constant *CV = dyn_cast<Constant>(V))
286         return Context->getConstantExprCast(opc, CV, Ty);
287       
288       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
289       AddToWorkList(C);
290       return C;
291     }
292         
293     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295     }
296
297
298     // ReplaceInstUsesWith - This method is to be used when an instruction is
299     // found to be dead, replacable with another preexisting expression.  Here
300     // we add all uses of I to the worklist, replace all uses of I with the new
301     // value, then return I, so that the inst combiner will know that I was
302     // modified.
303     //
304     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
305       AddUsersToWorkList(I);         // Add all modified instrs to worklist
306       if (&I != V) {
307         I.replaceAllUsesWith(V);
308         return &I;
309       } else {
310         // If we are replacing the instruction with itself, this must be in a
311         // segment of unreachable code, so just clobber the instruction.
312         I.replaceAllUsesWith(Context->getUndef(I.getType()));
313         return &I;
314       }
315     }
316
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343
344     /// SimplifyCommutative - This performs a few simplifications for 
345     /// commutative operators.
346     bool SimplifyCommutative(BinaryOperator &I);
347
348     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349     /// most-complex to least-complex order.
350     bool SimplifyCompare(CmpInst &I);
351
352     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353     /// based on the demanded bits.
354     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
355                                    APInt& KnownZero, APInt& KnownOne,
356                                    unsigned Depth);
357     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
358                               APInt& KnownZero, APInt& KnownOne,
359                               unsigned Depth=0);
360         
361     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362     /// SimplifyDemandedBits knows about.  See if the instruction has any
363     /// properties that allow us to simplify its operands.
364     bool SimplifyDemandedInstructionBits(Instruction &Inst);
365         
366     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367                                       APInt& UndefElts, unsigned Depth = 0);
368       
369     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370     // PHI node as operand #0, see if we can fold the instruction into the PHI
371     // (which is only possible if all operands to the PHI are constants).
372     Instruction *FoldOpIntoPhi(Instruction &I);
373
374     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375     // operator and they all are only used by the PHI, PHI together their
376     // inputs, and do the operation once, to the result of the PHI.
377     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
381     
382     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
384     
385     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
386                               bool isSub, Instruction &I);
387     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
388                                  bool isSigned, bool Inside, Instruction &IB);
389     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
390     Instruction *MatchBSwap(BinaryOperator &I);
391     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
392     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
393     Instruction *SimplifyMemSet(MemSetInst *MI);
394
395
396     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397
398     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
399                                     unsigned CastOpc, int &NumCastsRemoved);
400     unsigned GetOrEnforceKnownAlignment(Value *V,
401                                         unsigned PrefAlign = 0);
402
403   };
404 }
405
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
409
410 // getComplexity:  Assign a complexity or rank value to LLVM Values...
411 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(LLVMContext *Context, Value *V) {
413   if (isa<Instruction>(V)) {
414     if (BinaryOperator::isNeg(V) ||
415         BinaryOperator::isFNeg(V) ||
416         BinaryOperator::isNot(V))
417       return 3;
418     return 4;
419   }
420   if (isa<Argument>(V)) return 3;
421   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
422 }
423
424 // isOnlyUse - Return true if this instruction will be deleted if we stop using
425 // it.
426 static bool isOnlyUse(Value *V) {
427   return V->hasOneUse() || isa<Constant>(V);
428 }
429
430 // getPromotedType - Return the specified type promoted as it would be to pass
431 // though a va_arg area...
432 static const Type *getPromotedType(const Type *Ty) {
433   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434     if (ITy->getBitWidth() < 32)
435       return Type::Int32Ty;
436   }
437   return Ty;
438 }
439
440 /// getBitCastOperand - If the specified operand is a CastInst, a constant
441 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442 /// operand value, otherwise return null.
443 static Value *getBitCastOperand(Value *V) {
444   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
445     // BitCastInst?
446     return I->getOperand(0);
447   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
448     // GetElementPtrInst?
449     if (GEP->hasAllZeroIndices())
450       return GEP->getOperand(0);
451   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
452     if (CE->getOpcode() == Instruction::BitCast)
453       // BitCast ConstantExp?
454       return CE->getOperand(0);
455     else if (CE->getOpcode() == Instruction::GetElementPtr) {
456       // GetElementPtr ConstantExp?
457       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
458            I != E; ++I) {
459         ConstantInt *CI = dyn_cast<ConstantInt>(I);
460         if (!CI || !CI->isZero())
461           // Any non-zero indices? Not cast-like.
462           return 0;
463       }
464       // All-zero indices? This is just like casting.
465       return CE->getOperand(0);
466     }
467   }
468   return 0;
469 }
470
471 /// This function is a wrapper around CastInst::isEliminableCastPair. It
472 /// simply extracts arguments and returns what that function returns.
473 static Instruction::CastOps 
474 isEliminableCastPair(
475   const CastInst *CI, ///< The first cast instruction
476   unsigned opcode,       ///< The opcode of the second cast instruction
477   const Type *DstTy,     ///< The target type for the second cast instruction
478   TargetData *TD         ///< The target data for pointer size
479 ) {
480   
481   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
482   const Type *MidTy = CI->getType();                  // B from above
483
484   // Get the opcodes of the two Cast instructions
485   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
486   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
487
488   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
489                                                 DstTy, TD->getIntPtrType());
490   
491   // We don't want to form an inttoptr or ptrtoint that converts to an integer
492   // type that differs from the pointer size.
493   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
494       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
495     Res = 0;
496   
497   return Instruction::CastOps(Res);
498 }
499
500 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501 /// in any code being generated.  It does not require codegen if V is simple
502 /// enough or if the cast can be folded into other casts.
503 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
504                               const Type *Ty, TargetData *TD) {
505   if (V->getType() == Ty || isa<Constant>(V)) return false;
506   
507   // If this is another cast that can be eliminated, it isn't codegen either.
508   if (const CastInst *CI = dyn_cast<CastInst>(V))
509     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
510       return false;
511   return true;
512 }
513
514 // SimplifyCommutative - This performs a few simplifications for commutative
515 // operators:
516 //
517 //  1. Order operands such that they are listed from right (least complex) to
518 //     left (most complex).  This puts constants before unary operators before
519 //     binary operators.
520 //
521 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
523 //
524 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
525   bool Changed = false;
526   if (getComplexity(Context, I.getOperand(0)) < 
527       getComplexity(Context, I.getOperand(1)))
528     Changed = !I.swapOperands();
529
530   if (!I.isAssociative()) return Changed;
531   Instruction::BinaryOps Opcode = I.getOpcode();
532   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
533     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
534       if (isa<Constant>(I.getOperand(1))) {
535         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
536                                              cast<Constant>(I.getOperand(1)),
537                                              cast<Constant>(Op->getOperand(1)));
538         I.setOperand(0, Op->getOperand(0));
539         I.setOperand(1, Folded);
540         return true;
541       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
542         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
543             isOnlyUse(Op) && isOnlyUse(Op1)) {
544           Constant *C1 = cast<Constant>(Op->getOperand(1));
545           Constant *C2 = cast<Constant>(Op1->getOperand(1));
546
547           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
548           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
549           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
550                                                     Op1->getOperand(0),
551                                                     Op1->getName(), &I);
552           AddToWorkList(New);
553           I.setOperand(0, New);
554           I.setOperand(1, Folded);
555           return true;
556         }
557     }
558   return Changed;
559 }
560
561 /// SimplifyCompare - For a CmpInst this function just orders the operands
562 /// so that theyare listed from right (least complex) to left (most complex).
563 /// This puts constants before unary operators before binary operators.
564 bool InstCombiner::SimplifyCompare(CmpInst &I) {
565   if (getComplexity(Context, I.getOperand(0)) >=
566       getComplexity(Context, I.getOperand(1)))
567     return false;
568   I.swapOperands();
569   // Compare instructions are not associative so there's nothing else we can do.
570   return true;
571 }
572
573 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
574 // if the LHS is a constant zero (which is the 'negate' form).
575 //
576 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
577   if (BinaryOperator::isNeg(V))
578     return BinaryOperator::getNegArgument(V);
579
580   // Constants can be considered to be negated values if they can be folded.
581   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
582     return Context->getConstantExprNeg(C);
583
584   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
585     if (C->getType()->getElementType()->isInteger())
586       return Context->getConstantExprNeg(C);
587
588   return 0;
589 }
590
591 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
592 // instruction if the LHS is a constant negative zero (which is the 'negate'
593 // form).
594 //
595 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
596   if (BinaryOperator::isFNeg(V))
597     return BinaryOperator::getFNegArgument(V);
598
599   // Constants can be considered to be negated values if they can be folded.
600   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
601     return Context->getConstantExprFNeg(C);
602
603   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
604     if (C->getType()->getElementType()->isFloatingPoint())
605       return Context->getConstantExprFNeg(C);
606
607   return 0;
608 }
609
610 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
611   if (BinaryOperator::isNot(V))
612     return BinaryOperator::getNotArgument(V);
613
614   // Constants can be considered to be not'ed values...
615   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
616     return Context->getConstantInt(~C->getValue());
617   return 0;
618 }
619
620 // dyn_castFoldableMul - If this value is a multiply that can be folded into
621 // other computations (because it has a constant operand), return the
622 // non-constant operand of the multiply, and set CST to point to the multiplier.
623 // Otherwise, return null.
624 //
625 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
626                                          LLVMContext *Context) {
627   if (V->hasOneUse() && V->getType()->isInteger())
628     if (Instruction *I = dyn_cast<Instruction>(V)) {
629       if (I->getOpcode() == Instruction::Mul)
630         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
631           return I->getOperand(0);
632       if (I->getOpcode() == Instruction::Shl)
633         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
634           // The multiplier is really 1 << CST.
635           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
636           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
637           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
638           return I->getOperand(0);
639         }
640     }
641   return 0;
642 }
643
644 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
645 /// expression, return it.
646 static User *dyn_castGetElementPtr(Value *V) {
647   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
648   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
649     if (CE->getOpcode() == Instruction::GetElementPtr)
650       return cast<User>(V);
651   return false;
652 }
653
654 /// AddOne - Add one to a ConstantInt
655 static Constant *AddOne(Constant *C, LLVMContext *Context) {
656   return Context->getConstantExprAdd(C, 
657     Context->getConstantInt(C->getType(), 1));
658 }
659 /// SubOne - Subtract one from a ConstantInt
660 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
661   return Context->getConstantExprSub(C, 
662     Context->getConstantInt(C->getType(), 1));
663 }
664 /// MultiplyOverflows - True if the multiply can not be expressed in an int
665 /// this size.
666 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
667                               LLVMContext *Context) {
668   uint32_t W = C1->getBitWidth();
669   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
670   if (sign) {
671     LHSExt.sext(W * 2);
672     RHSExt.sext(W * 2);
673   } else {
674     LHSExt.zext(W * 2);
675     RHSExt.zext(W * 2);
676   }
677
678   APInt MulExt = LHSExt * RHSExt;
679
680   if (sign) {
681     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
682     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
683     return MulExt.slt(Min) || MulExt.sgt(Max);
684   } else 
685     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
686 }
687
688
689 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
690 /// specified instruction is a constant integer.  If so, check to see if there
691 /// are any bits set in the constant that are not demanded.  If so, shrink the
692 /// constant and return true.
693 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
694                                    APInt Demanded, LLVMContext *Context) {
695   assert(I && "No instruction?");
696   assert(OpNo < I->getNumOperands() && "Operand index too large");
697
698   // If the operand is not a constant integer, nothing to do.
699   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
700   if (!OpC) return false;
701
702   // If there are no bits set that aren't demanded, nothing to do.
703   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
704   if ((~Demanded & OpC->getValue()) == 0)
705     return false;
706
707   // This instruction is producing bits that are not demanded. Shrink the RHS.
708   Demanded &= OpC->getValue();
709   I->setOperand(OpNo, Context->getConstantInt(Demanded));
710   return true;
711 }
712
713 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
714 // set of known zero and one bits, compute the maximum and minimum values that
715 // could have the specified known zero and known one bits, returning them in
716 // min/max.
717 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
718                                                    const APInt& KnownOne,
719                                                    APInt& Min, APInt& Max) {
720   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721          KnownZero.getBitWidth() == Min.getBitWidth() &&
722          KnownZero.getBitWidth() == Max.getBitWidth() &&
723          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
724   APInt UnknownBits = ~(KnownZero|KnownOne);
725
726   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
727   // bit if it is unknown.
728   Min = KnownOne;
729   Max = KnownOne|UnknownBits;
730   
731   if (UnknownBits.isNegative()) { // Sign bit is unknown
732     Min.set(Min.getBitWidth()-1);
733     Max.clear(Max.getBitWidth()-1);
734   }
735 }
736
737 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
738 // a set of known zero and one bits, compute the maximum and minimum values that
739 // could have the specified known zero and known one bits, returning them in
740 // min/max.
741 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
742                                                      const APInt &KnownOne,
743                                                      APInt &Min, APInt &Max) {
744   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
745          KnownZero.getBitWidth() == Min.getBitWidth() &&
746          KnownZero.getBitWidth() == Max.getBitWidth() &&
747          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
748   APInt UnknownBits = ~(KnownZero|KnownOne);
749   
750   // The minimum value is when the unknown bits are all zeros.
751   Min = KnownOne;
752   // The maximum value is when the unknown bits are all ones.
753   Max = KnownOne|UnknownBits;
754 }
755
756 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
757 /// SimplifyDemandedBits knows about.  See if the instruction has any
758 /// properties that allow us to simplify its operands.
759 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
760   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
761   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
762   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
763   
764   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
765                                      KnownZero, KnownOne, 0);
766   if (V == 0) return false;
767   if (V == &Inst) return true;
768   ReplaceInstUsesWith(Inst, V);
769   return true;
770 }
771
772 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
773 /// specified instruction operand if possible, updating it in place.  It returns
774 /// true if it made any change and false otherwise.
775 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
776                                         APInt &KnownZero, APInt &KnownOne,
777                                         unsigned Depth) {
778   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
779                                           KnownZero, KnownOne, Depth);
780   if (NewVal == 0) return false;
781   U.set(NewVal);
782   return true;
783 }
784
785
786 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
787 /// value based on the demanded bits.  When this function is called, it is known
788 /// that only the bits set in DemandedMask of the result of V are ever used
789 /// downstream. Consequently, depending on the mask and V, it may be possible
790 /// to replace V with a constant or one of its operands. In such cases, this
791 /// function does the replacement and returns true. In all other cases, it
792 /// returns false after analyzing the expression and setting KnownOne and known
793 /// to be one in the expression.  KnownZero contains all the bits that are known
794 /// to be zero in the expression. These are provided to potentially allow the
795 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
796 /// the expression. KnownOne and KnownZero always follow the invariant that 
797 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
798 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
799 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
800 /// and KnownOne must all be the same.
801 ///
802 /// This returns null if it did not change anything and it permits no
803 /// simplification.  This returns V itself if it did some simplification of V's
804 /// operands based on the information about what bits are demanded. This returns
805 /// some other non-null value if it found out that V is equal to another value
806 /// in the context where the specified bits are demanded, but not for all users.
807 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
808                                              APInt &KnownZero, APInt &KnownOne,
809                                              unsigned Depth) {
810   assert(V != 0 && "Null pointer of Value???");
811   assert(Depth <= 6 && "Limit Search Depth");
812   uint32_t BitWidth = DemandedMask.getBitWidth();
813   const Type *VTy = V->getType();
814   assert((TD || !isa<PointerType>(VTy)) &&
815          "SimplifyDemandedBits needs to know bit widths!");
816   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
817          (!VTy->isIntOrIntVector() ||
818           VTy->getScalarSizeInBits() == BitWidth) &&
819          KnownZero.getBitWidth() == BitWidth &&
820          KnownOne.getBitWidth() == BitWidth &&
821          "Value *V, DemandedMask, KnownZero and KnownOne "
822          "must have same BitWidth");
823   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
824     // We know all of the bits for a constant!
825     KnownOne = CI->getValue() & DemandedMask;
826     KnownZero = ~KnownOne & DemandedMask;
827     return 0;
828   }
829   if (isa<ConstantPointerNull>(V)) {
830     // We know all of the bits for a constant!
831     KnownOne.clear();
832     KnownZero = DemandedMask;
833     return 0;
834   }
835
836   KnownZero.clear();
837   KnownOne.clear();
838   if (DemandedMask == 0) {   // Not demanding any bits from V.
839     if (isa<UndefValue>(V))
840       return 0;
841     return Context->getUndef(VTy);
842   }
843   
844   if (Depth == 6)        // Limit search depth.
845     return 0;
846   
847   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
848   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
849
850   Instruction *I = dyn_cast<Instruction>(V);
851   if (!I) {
852     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
853     return 0;        // Only analyze instructions.
854   }
855
856   // If there are multiple uses of this value and we aren't at the root, then
857   // we can't do any simplifications of the operands, because DemandedMask
858   // only reflects the bits demanded by *one* of the users.
859   if (Depth != 0 && !I->hasOneUse()) {
860     // Despite the fact that we can't simplify this instruction in all User's
861     // context, we can at least compute the knownzero/knownone bits, and we can
862     // do simplifications that apply to *just* the one user if we know that
863     // this instruction has a simpler value in that context.
864     if (I->getOpcode() == Instruction::And) {
865       // If either the LHS or the RHS are Zero, the result is zero.
866       ComputeMaskedBits(I->getOperand(1), DemandedMask,
867                         RHSKnownZero, RHSKnownOne, Depth+1);
868       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
869                         LHSKnownZero, LHSKnownOne, Depth+1);
870       
871       // If all of the demanded bits are known 1 on one side, return the other.
872       // These bits cannot contribute to the result of the 'and' in this
873       // context.
874       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
875           (DemandedMask & ~LHSKnownZero))
876         return I->getOperand(0);
877       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
878           (DemandedMask & ~RHSKnownZero))
879         return I->getOperand(1);
880       
881       // If all of the demanded bits in the inputs are known zeros, return zero.
882       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
883         return Context->getNullValue(VTy);
884       
885     } else if (I->getOpcode() == Instruction::Or) {
886       // We can simplify (X|Y) -> X or Y in the user's context if we know that
887       // only bits from X or Y are demanded.
888       
889       // If either the LHS or the RHS are One, the result is One.
890       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
891                         RHSKnownZero, RHSKnownOne, Depth+1);
892       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
893                         LHSKnownZero, LHSKnownOne, Depth+1);
894       
895       // If all of the demanded bits are known zero on one side, return the
896       // other.  These bits cannot contribute to the result of the 'or' in this
897       // context.
898       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
899           (DemandedMask & ~LHSKnownOne))
900         return I->getOperand(0);
901       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
902           (DemandedMask & ~RHSKnownOne))
903         return I->getOperand(1);
904       
905       // If all of the potentially set bits on one side are known to be set on
906       // the other side, just use the 'other' side.
907       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
908           (DemandedMask & (~RHSKnownZero)))
909         return I->getOperand(0);
910       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
911           (DemandedMask & (~LHSKnownZero)))
912         return I->getOperand(1);
913     }
914     
915     // Compute the KnownZero/KnownOne bits to simplify things downstream.
916     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
917     return 0;
918   }
919   
920   // If this is the root being simplified, allow it to have multiple uses,
921   // just set the DemandedMask to all bits so that we can try to simplify the
922   // operands.  This allows visitTruncInst (for example) to simplify the
923   // operand of a trunc without duplicating all the logic below.
924   if (Depth == 0 && !V->hasOneUse())
925     DemandedMask = APInt::getAllOnesValue(BitWidth);
926   
927   switch (I->getOpcode()) {
928   default:
929     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
930     break;
931   case Instruction::And:
932     // If either the LHS or the RHS are Zero, the result is zero.
933     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
934                              RHSKnownZero, RHSKnownOne, Depth+1) ||
935         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
936                              LHSKnownZero, LHSKnownOne, Depth+1))
937       return I;
938     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
939     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
940
941     // If all of the demanded bits are known 1 on one side, return the other.
942     // These bits cannot contribute to the result of the 'and'.
943     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
944         (DemandedMask & ~LHSKnownZero))
945       return I->getOperand(0);
946     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
947         (DemandedMask & ~RHSKnownZero))
948       return I->getOperand(1);
949     
950     // If all of the demanded bits in the inputs are known zeros, return zero.
951     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
952       return Context->getNullValue(VTy);
953       
954     // If the RHS is a constant, see if we can simplify it.
955     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
956       return I;
957       
958     // Output known-1 bits are only known if set in both the LHS & RHS.
959     RHSKnownOne &= LHSKnownOne;
960     // Output known-0 are known to be clear if zero in either the LHS | RHS.
961     RHSKnownZero |= LHSKnownZero;
962     break;
963   case Instruction::Or:
964     // If either the LHS or the RHS are One, the result is One.
965     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
966                              RHSKnownZero, RHSKnownOne, Depth+1) ||
967         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
968                              LHSKnownZero, LHSKnownOne, Depth+1))
969       return I;
970     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
971     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
972     
973     // If all of the demanded bits are known zero on one side, return the other.
974     // These bits cannot contribute to the result of the 'or'.
975     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
976         (DemandedMask & ~LHSKnownOne))
977       return I->getOperand(0);
978     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
979         (DemandedMask & ~RHSKnownOne))
980       return I->getOperand(1);
981
982     // If all of the potentially set bits on one side are known to be set on
983     // the other side, just use the 'other' side.
984     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
985         (DemandedMask & (~RHSKnownZero)))
986       return I->getOperand(0);
987     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
988         (DemandedMask & (~LHSKnownZero)))
989       return I->getOperand(1);
990         
991     // If the RHS is a constant, see if we can simplify it.
992     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
993       return I;
994           
995     // Output known-0 bits are only known if clear in both the LHS & RHS.
996     RHSKnownZero &= LHSKnownZero;
997     // Output known-1 are known to be set if set in either the LHS | RHS.
998     RHSKnownOne |= LHSKnownOne;
999     break;
1000   case Instruction::Xor: {
1001     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1002                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1003         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1004                              LHSKnownZero, LHSKnownOne, Depth+1))
1005       return I;
1006     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1007     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1008     
1009     // If all of the demanded bits are known zero on one side, return the other.
1010     // These bits cannot contribute to the result of the 'xor'.
1011     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1012       return I->getOperand(0);
1013     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1014       return I->getOperand(1);
1015     
1016     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1017     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1018                          (RHSKnownOne & LHSKnownOne);
1019     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1020     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1021                         (RHSKnownOne & LHSKnownZero);
1022     
1023     // If all of the demanded bits are known to be zero on one side or the
1024     // other, turn this into an *inclusive* or.
1025     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1026     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1027       Instruction *Or =
1028         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1029                                  I->getName());
1030       return InsertNewInstBefore(Or, *I);
1031     }
1032     
1033     // If all of the demanded bits on one side are known, and all of the set
1034     // bits on that side are also known to be set on the other side, turn this
1035     // into an AND, as we know the bits will be cleared.
1036     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1037     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1038       // all known
1039       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1040         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1041         Instruction *And = 
1042           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1043         return InsertNewInstBefore(And, *I);
1044       }
1045     }
1046     
1047     // If the RHS is a constant, see if we can simplify it.
1048     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1049     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1050       return I;
1051     
1052     RHSKnownZero = KnownZeroOut;
1053     RHSKnownOne  = KnownOneOut;
1054     break;
1055   }
1056   case Instruction::Select:
1057     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1058                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1059         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1060                              LHSKnownZero, LHSKnownOne, Depth+1))
1061       return I;
1062     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1063     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1064     
1065     // If the operands are constants, see if we can simplify them.
1066     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1067         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1068       return I;
1069     
1070     // Only known if known in both the LHS and RHS.
1071     RHSKnownOne &= LHSKnownOne;
1072     RHSKnownZero &= LHSKnownZero;
1073     break;
1074   case Instruction::Trunc: {
1075     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1076     DemandedMask.zext(truncBf);
1077     RHSKnownZero.zext(truncBf);
1078     RHSKnownOne.zext(truncBf);
1079     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1080                              RHSKnownZero, RHSKnownOne, Depth+1))
1081       return I;
1082     DemandedMask.trunc(BitWidth);
1083     RHSKnownZero.trunc(BitWidth);
1084     RHSKnownOne.trunc(BitWidth);
1085     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1086     break;
1087   }
1088   case Instruction::BitCast:
1089     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1090       return false;  // vector->int or fp->int?
1091
1092     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1093       if (const VectorType *SrcVTy =
1094             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1095         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1096           // Don't touch a bitcast between vectors of different element counts.
1097           return false;
1098       } else
1099         // Don't touch a scalar-to-vector bitcast.
1100         return false;
1101     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1102       // Don't touch a vector-to-scalar bitcast.
1103       return false;
1104
1105     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1109     break;
1110   case Instruction::ZExt: {
1111     // Compute the bits in the result that are not present in the input.
1112     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1113     
1114     DemandedMask.trunc(SrcBitWidth);
1115     RHSKnownZero.trunc(SrcBitWidth);
1116     RHSKnownOne.trunc(SrcBitWidth);
1117     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1118                              RHSKnownZero, RHSKnownOne, Depth+1))
1119       return I;
1120     DemandedMask.zext(BitWidth);
1121     RHSKnownZero.zext(BitWidth);
1122     RHSKnownOne.zext(BitWidth);
1123     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1124     // The top bits are known to be zero.
1125     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1126     break;
1127   }
1128   case Instruction::SExt: {
1129     // Compute the bits in the result that are not present in the input.
1130     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1131     
1132     APInt InputDemandedBits = DemandedMask & 
1133                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1134
1135     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1136     // If any of the sign extended bits are demanded, we know that the sign
1137     // bit is demanded.
1138     if ((NewBits & DemandedMask) != 0)
1139       InputDemandedBits.set(SrcBitWidth-1);
1140       
1141     InputDemandedBits.trunc(SrcBitWidth);
1142     RHSKnownZero.trunc(SrcBitWidth);
1143     RHSKnownOne.trunc(SrcBitWidth);
1144     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1145                              RHSKnownZero, RHSKnownOne, Depth+1))
1146       return I;
1147     InputDemandedBits.zext(BitWidth);
1148     RHSKnownZero.zext(BitWidth);
1149     RHSKnownOne.zext(BitWidth);
1150     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1151       
1152     // If the sign bit of the input is known set or clear, then we know the
1153     // top bits of the result.
1154
1155     // If the input sign bit is known zero, or if the NewBits are not demanded
1156     // convert this into a zero extension.
1157     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1158       // Convert to ZExt cast
1159       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1160       return InsertNewInstBefore(NewCast, *I);
1161     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1162       RHSKnownOne |= NewBits;
1163     }
1164     break;
1165   }
1166   case Instruction::Add: {
1167     // Figure out what the input bits are.  If the top bits of the and result
1168     // are not demanded, then the add doesn't demand them from its input
1169     // either.
1170     unsigned NLZ = DemandedMask.countLeadingZeros();
1171       
1172     // If there is a constant on the RHS, there are a variety of xformations
1173     // we can do.
1174     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1175       // If null, this should be simplified elsewhere.  Some of the xforms here
1176       // won't work if the RHS is zero.
1177       if (RHS->isZero())
1178         break;
1179       
1180       // If the top bit of the output is demanded, demand everything from the
1181       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1182       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1183
1184       // Find information about known zero/one bits in the input.
1185       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1186                                LHSKnownZero, LHSKnownOne, Depth+1))
1187         return I;
1188
1189       // If the RHS of the add has bits set that can't affect the input, reduce
1190       // the constant.
1191       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1192         return I;
1193       
1194       // Avoid excess work.
1195       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1196         break;
1197       
1198       // Turn it into OR if input bits are zero.
1199       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1200         Instruction *Or =
1201           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1202                                    I->getName());
1203         return InsertNewInstBefore(Or, *I);
1204       }
1205       
1206       // We can say something about the output known-zero and known-one bits,
1207       // depending on potential carries from the input constant and the
1208       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1209       // bits set and the RHS constant is 0x01001, then we know we have a known
1210       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1211       
1212       // To compute this, we first compute the potential carry bits.  These are
1213       // the bits which may be modified.  I'm not aware of a better way to do
1214       // this scan.
1215       const APInt &RHSVal = RHS->getValue();
1216       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1217       
1218       // Now that we know which bits have carries, compute the known-1/0 sets.
1219       
1220       // Bits are known one if they are known zero in one operand and one in the
1221       // other, and there is no input carry.
1222       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1223                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1224       
1225       // Bits are known zero if they are known zero in both operands and there
1226       // is no input carry.
1227       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1228     } else {
1229       // If the high-bits of this ADD are not demanded, then it does not demand
1230       // the high bits of its LHS or RHS.
1231       if (DemandedMask[BitWidth-1] == 0) {
1232         // Right fill the mask of bits for this ADD to demand the most
1233         // significant bit and all those below it.
1234         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1235         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1236                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1237             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1238                                  LHSKnownZero, LHSKnownOne, Depth+1))
1239           return I;
1240       }
1241     }
1242     break;
1243   }
1244   case Instruction::Sub:
1245     // If the high-bits of this SUB are not demanded, then it does not demand
1246     // the high bits of its LHS or RHS.
1247     if (DemandedMask[BitWidth-1] == 0) {
1248       // Right fill the mask of bits for this SUB to demand the most
1249       // significant bit and all those below it.
1250       uint32_t NLZ = DemandedMask.countLeadingZeros();
1251       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1252       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1253                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1254           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1255                                LHSKnownZero, LHSKnownOne, Depth+1))
1256         return I;
1257     }
1258     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1259     // the known zeros and ones.
1260     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1261     break;
1262   case Instruction::Shl:
1263     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1264       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1265       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1266       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1267                                RHSKnownZero, RHSKnownOne, Depth+1))
1268         return I;
1269       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1270       RHSKnownZero <<= ShiftAmt;
1271       RHSKnownOne  <<= ShiftAmt;
1272       // low bits known zero.
1273       if (ShiftAmt)
1274         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1275     }
1276     break;
1277   case Instruction::LShr:
1278     // For a logical shift right
1279     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1280       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1281       
1282       // Unsigned shift right.
1283       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1284       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1285                                RHSKnownZero, RHSKnownOne, Depth+1))
1286         return I;
1287       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1288       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1289       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1290       if (ShiftAmt) {
1291         // Compute the new bits that are at the top now.
1292         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1293         RHSKnownZero |= HighBits;  // high bits known zero.
1294       }
1295     }
1296     break;
1297   case Instruction::AShr:
1298     // If this is an arithmetic shift right and only the low-bit is set, we can
1299     // always convert this into a logical shr, even if the shift amount is
1300     // variable.  The low bit of the shift cannot be an input sign bit unless
1301     // the shift amount is >= the size of the datatype, which is undefined.
1302     if (DemandedMask == 1) {
1303       // Perform the logical shift right.
1304       Instruction *NewVal = BinaryOperator::CreateLShr(
1305                         I->getOperand(0), I->getOperand(1), I->getName());
1306       return InsertNewInstBefore(NewVal, *I);
1307     }    
1308
1309     // If the sign bit is the only bit demanded by this ashr, then there is no
1310     // need to do it, the shift doesn't change the high bit.
1311     if (DemandedMask.isSignBit())
1312       return I->getOperand(0);
1313     
1314     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1316       
1317       // Signed shift right.
1318       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1319       // If any of the "high bits" are demanded, we should set the sign bit as
1320       // demanded.
1321       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1322         DemandedMaskIn.set(BitWidth-1);
1323       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1324                                RHSKnownZero, RHSKnownOne, Depth+1))
1325         return I;
1326       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1327       // Compute the new bits that are at the top now.
1328       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1329       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1330       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1331         
1332       // Handle the sign bits.
1333       APInt SignBit(APInt::getSignBit(BitWidth));
1334       // Adjust to where it is now in the mask.
1335       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1336         
1337       // If the input sign bit is known to be zero, or if none of the top bits
1338       // are demanded, turn this into an unsigned shift right.
1339       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1340           (HighBits & ~DemandedMask) == HighBits) {
1341         // Perform the logical shift right.
1342         Instruction *NewVal = BinaryOperator::CreateLShr(
1343                           I->getOperand(0), SA, I->getName());
1344         return InsertNewInstBefore(NewVal, *I);
1345       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1346         RHSKnownOne |= HighBits;
1347       }
1348     }
1349     break;
1350   case Instruction::SRem:
1351     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1352       APInt RA = Rem->getValue().abs();
1353       if (RA.isPowerOf2()) {
1354         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1355           return I->getOperand(0);
1356
1357         APInt LowBits = RA - 1;
1358         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1359         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1360                                  LHSKnownZero, LHSKnownOne, Depth+1))
1361           return I;
1362
1363         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1364           LHSKnownZero |= ~LowBits;
1365
1366         KnownZero |= LHSKnownZero & DemandedMask;
1367
1368         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1369       }
1370     }
1371     break;
1372   case Instruction::URem: {
1373     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1374     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1375     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1376                              KnownZero2, KnownOne2, Depth+1) ||
1377         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1378                              KnownZero2, KnownOne2, Depth+1))
1379       return I;
1380
1381     unsigned Leaders = KnownZero2.countLeadingOnes();
1382     Leaders = std::max(Leaders,
1383                        KnownZero2.countLeadingOnes());
1384     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1385     break;
1386   }
1387   case Instruction::Call:
1388     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1389       switch (II->getIntrinsicID()) {
1390       default: break;
1391       case Intrinsic::bswap: {
1392         // If the only bits demanded come from one byte of the bswap result,
1393         // just shift the input byte into position to eliminate the bswap.
1394         unsigned NLZ = DemandedMask.countLeadingZeros();
1395         unsigned NTZ = DemandedMask.countTrailingZeros();
1396           
1397         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1398         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1399         // have 14 leading zeros, round to 8.
1400         NLZ &= ~7;
1401         NTZ &= ~7;
1402         // If we need exactly one byte, we can do this transformation.
1403         if (BitWidth-NLZ-NTZ == 8) {
1404           unsigned ResultBit = NTZ;
1405           unsigned InputBit = BitWidth-NTZ-8;
1406           
1407           // Replace this with either a left or right shift to get the byte into
1408           // the right place.
1409           Instruction *NewVal;
1410           if (InputBit > ResultBit)
1411             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1412                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1413           else
1414             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1415                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1416           NewVal->takeName(I);
1417           return InsertNewInstBefore(NewVal, *I);
1418         }
1419           
1420         // TODO: Could compute known zero/one bits based on the input.
1421         break;
1422       }
1423       }
1424     }
1425     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1426     break;
1427   }
1428   
1429   // If the client is only demanding bits that we know, return the known
1430   // constant.
1431   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1432     Constant *C = Context->getConstantInt(RHSKnownOne);
1433     if (isa<PointerType>(V->getType()))
1434       C = Context->getConstantExprIntToPtr(C, V->getType());
1435     return C;
1436   }
1437   return false;
1438 }
1439
1440
1441 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1442 /// any number of elements. DemandedElts contains the set of elements that are
1443 /// actually used by the caller.  This method analyzes which elements of the
1444 /// operand are undef and returns that information in UndefElts.
1445 ///
1446 /// If the information about demanded elements can be used to simplify the
1447 /// operation, the operation is simplified, then the resultant value is
1448 /// returned.  This returns null if no change was made.
1449 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1450                                                 APInt& UndefElts,
1451                                                 unsigned Depth) {
1452   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1453   APInt EltMask(APInt::getAllOnesValue(VWidth));
1454   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1455
1456   if (isa<UndefValue>(V)) {
1457     // If the entire vector is undefined, just return this info.
1458     UndefElts = EltMask;
1459     return 0;
1460   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1461     UndefElts = EltMask;
1462     return Context->getUndef(V->getType());
1463   }
1464
1465   UndefElts = 0;
1466   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1467     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1468     Constant *Undef = Context->getUndef(EltTy);
1469
1470     std::vector<Constant*> Elts;
1471     for (unsigned i = 0; i != VWidth; ++i)
1472       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1473         Elts.push_back(Undef);
1474         UndefElts.set(i);
1475       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1476         Elts.push_back(Undef);
1477         UndefElts.set(i);
1478       } else {                               // Otherwise, defined.
1479         Elts.push_back(CP->getOperand(i));
1480       }
1481
1482     // If we changed the constant, return it.
1483     Constant *NewCP = Context->getConstantVector(Elts);
1484     return NewCP != CP ? NewCP : 0;
1485   } else if (isa<ConstantAggregateZero>(V)) {
1486     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1487     // set to undef.
1488     
1489     // Check if this is identity. If so, return 0 since we are not simplifying
1490     // anything.
1491     if (DemandedElts == ((1ULL << VWidth) -1))
1492       return 0;
1493     
1494     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1495     Constant *Zero = Context->getNullValue(EltTy);
1496     Constant *Undef = Context->getUndef(EltTy);
1497     std::vector<Constant*> Elts;
1498     for (unsigned i = 0; i != VWidth; ++i) {
1499       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1500       Elts.push_back(Elt);
1501     }
1502     UndefElts = DemandedElts ^ EltMask;
1503     return Context->getConstantVector(Elts);
1504   }
1505   
1506   // Limit search depth.
1507   if (Depth == 10)
1508     return 0;
1509
1510   // If multiple users are using the root value, procede with
1511   // simplification conservatively assuming that all elements
1512   // are needed.
1513   if (!V->hasOneUse()) {
1514     // Quit if we find multiple users of a non-root value though.
1515     // They'll be handled when it's their turn to be visited by
1516     // the main instcombine process.
1517     if (Depth != 0)
1518       // TODO: Just compute the UndefElts information recursively.
1519       return 0;
1520
1521     // Conservatively assume that all elements are needed.
1522     DemandedElts = EltMask;
1523   }
1524   
1525   Instruction *I = dyn_cast<Instruction>(V);
1526   if (!I) return 0;        // Only analyze instructions.
1527   
1528   bool MadeChange = false;
1529   APInt UndefElts2(VWidth, 0);
1530   Value *TmpV;
1531   switch (I->getOpcode()) {
1532   default: break;
1533     
1534   case Instruction::InsertElement: {
1535     // If this is a variable index, we don't know which element it overwrites.
1536     // demand exactly the same input as we produce.
1537     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1538     if (Idx == 0) {
1539       // Note that we can't propagate undef elt info, because we don't know
1540       // which elt is getting updated.
1541       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1542                                         UndefElts2, Depth+1);
1543       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544       break;
1545     }
1546     
1547     // If this is inserting an element that isn't demanded, remove this
1548     // insertelement.
1549     unsigned IdxNo = Idx->getZExtValue();
1550     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1551       return AddSoonDeadInstToWorklist(*I, 0);
1552     
1553     // Otherwise, the element inserted overwrites whatever was there, so the
1554     // input demanded set is simpler than the output set.
1555     APInt DemandedElts2 = DemandedElts;
1556     DemandedElts2.clear(IdxNo);
1557     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1558                                       UndefElts, Depth+1);
1559     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1560
1561     // The inserted element is defined.
1562     UndefElts.clear(IdxNo);
1563     break;
1564   }
1565   case Instruction::ShuffleVector: {
1566     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1567     uint64_t LHSVWidth =
1568       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1569     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1570     for (unsigned i = 0; i < VWidth; i++) {
1571       if (DemandedElts[i]) {
1572         unsigned MaskVal = Shuffle->getMaskValue(i);
1573         if (MaskVal != -1u) {
1574           assert(MaskVal < LHSVWidth * 2 &&
1575                  "shufflevector mask index out of range!");
1576           if (MaskVal < LHSVWidth)
1577             LeftDemanded.set(MaskVal);
1578           else
1579             RightDemanded.set(MaskVal - LHSVWidth);
1580         }
1581       }
1582     }
1583
1584     APInt UndefElts4(LHSVWidth, 0);
1585     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1586                                       UndefElts4, Depth+1);
1587     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1588
1589     APInt UndefElts3(LHSVWidth, 0);
1590     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1591                                       UndefElts3, Depth+1);
1592     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1593
1594     bool NewUndefElts = false;
1595     for (unsigned i = 0; i < VWidth; i++) {
1596       unsigned MaskVal = Shuffle->getMaskValue(i);
1597       if (MaskVal == -1u) {
1598         UndefElts.set(i);
1599       } else if (MaskVal < LHSVWidth) {
1600         if (UndefElts4[MaskVal]) {
1601           NewUndefElts = true;
1602           UndefElts.set(i);
1603         }
1604       } else {
1605         if (UndefElts3[MaskVal - LHSVWidth]) {
1606           NewUndefElts = true;
1607           UndefElts.set(i);
1608         }
1609       }
1610     }
1611
1612     if (NewUndefElts) {
1613       // Add additional discovered undefs.
1614       std::vector<Constant*> Elts;
1615       for (unsigned i = 0; i < VWidth; ++i) {
1616         if (UndefElts[i])
1617           Elts.push_back(Context->getUndef(Type::Int32Ty));
1618         else
1619           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1620                                           Shuffle->getMaskValue(i)));
1621       }
1622       I->setOperand(2, Context->getConstantVector(Elts));
1623       MadeChange = true;
1624     }
1625     break;
1626   }
1627   case Instruction::BitCast: {
1628     // Vector->vector casts only.
1629     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1630     if (!VTy) break;
1631     unsigned InVWidth = VTy->getNumElements();
1632     APInt InputDemandedElts(InVWidth, 0);
1633     unsigned Ratio;
1634
1635     if (VWidth == InVWidth) {
1636       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1637       // elements as are demanded of us.
1638       Ratio = 1;
1639       InputDemandedElts = DemandedElts;
1640     } else if (VWidth > InVWidth) {
1641       // Untested so far.
1642       break;
1643       
1644       // If there are more elements in the result than there are in the source,
1645       // then an input element is live if any of the corresponding output
1646       // elements are live.
1647       Ratio = VWidth/InVWidth;
1648       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1649         if (DemandedElts[OutIdx])
1650           InputDemandedElts.set(OutIdx/Ratio);
1651       }
1652     } else {
1653       // Untested so far.
1654       break;
1655       
1656       // If there are more elements in the source than there are in the result,
1657       // then an input element is live if the corresponding output element is
1658       // live.
1659       Ratio = InVWidth/VWidth;
1660       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1661         if (DemandedElts[InIdx/Ratio])
1662           InputDemandedElts.set(InIdx);
1663     }
1664     
1665     // div/rem demand all inputs, because they don't want divide by zero.
1666     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1667                                       UndefElts2, Depth+1);
1668     if (TmpV) {
1669       I->setOperand(0, TmpV);
1670       MadeChange = true;
1671     }
1672     
1673     UndefElts = UndefElts2;
1674     if (VWidth > InVWidth) {
1675       llvm_unreachable("Unimp");
1676       // If there are more elements in the result than there are in the source,
1677       // then an output element is undef if the corresponding input element is
1678       // undef.
1679       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1680         if (UndefElts2[OutIdx/Ratio])
1681           UndefElts.set(OutIdx);
1682     } else if (VWidth < InVWidth) {
1683       llvm_unreachable("Unimp");
1684       // If there are more elements in the source than there are in the result,
1685       // then a result element is undef if all of the corresponding input
1686       // elements are undef.
1687       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1688       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1689         if (!UndefElts2[InIdx])            // Not undef?
1690           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1691     }
1692     break;
1693   }
1694   case Instruction::And:
1695   case Instruction::Or:
1696   case Instruction::Xor:
1697   case Instruction::Add:
1698   case Instruction::Sub:
1699   case Instruction::Mul:
1700     // div/rem demand all inputs, because they don't want divide by zero.
1701     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1702                                       UndefElts, Depth+1);
1703     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1705                                       UndefElts2, Depth+1);
1706     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1707       
1708     // Output elements are undefined if both are undefined.  Consider things
1709     // like undef&0.  The result is known zero, not undef.
1710     UndefElts &= UndefElts2;
1711     break;
1712     
1713   case Instruction::Call: {
1714     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1715     if (!II) break;
1716     switch (II->getIntrinsicID()) {
1717     default: break;
1718       
1719     // Binary vector operations that work column-wise.  A dest element is a
1720     // function of the corresponding input elements from the two inputs.
1721     case Intrinsic::x86_sse_sub_ss:
1722     case Intrinsic::x86_sse_mul_ss:
1723     case Intrinsic::x86_sse_min_ss:
1724     case Intrinsic::x86_sse_max_ss:
1725     case Intrinsic::x86_sse2_sub_sd:
1726     case Intrinsic::x86_sse2_mul_sd:
1727     case Intrinsic::x86_sse2_min_sd:
1728     case Intrinsic::x86_sse2_max_sd:
1729       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1730                                         UndefElts, Depth+1);
1731       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1732       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1733                                         UndefElts2, Depth+1);
1734       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1735
1736       // If only the low elt is demanded and this is a scalarizable intrinsic,
1737       // scalarize it now.
1738       if (DemandedElts == 1) {
1739         switch (II->getIntrinsicID()) {
1740         default: break;
1741         case Intrinsic::x86_sse_sub_ss:
1742         case Intrinsic::x86_sse_mul_ss:
1743         case Intrinsic::x86_sse2_sub_sd:
1744         case Intrinsic::x86_sse2_mul_sd:
1745           // TODO: Lower MIN/MAX/ABS/etc
1746           Value *LHS = II->getOperand(1);
1747           Value *RHS = II->getOperand(2);
1748           // Extract the element as scalars.
1749           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 
1750             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1751           RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1752             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1753           
1754           switch (II->getIntrinsicID()) {
1755           default: llvm_unreachable("Case stmts out of sync!");
1756           case Intrinsic::x86_sse_sub_ss:
1757           case Intrinsic::x86_sse2_sub_sd:
1758             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1759                                                         II->getName()), *II);
1760             break;
1761           case Intrinsic::x86_sse_mul_ss:
1762           case Intrinsic::x86_sse2_mul_sd:
1763             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1764                                                          II->getName()), *II);
1765             break;
1766           }
1767           
1768           Instruction *New =
1769             InsertElementInst::Create(
1770               Context->getUndef(II->getType()), TmpV,
1771               Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1772           InsertNewInstBefore(New, *II);
1773           AddSoonDeadInstToWorklist(*II, 0);
1774           return New;
1775         }            
1776       }
1777         
1778       // Output elements are undefined if both are undefined.  Consider things
1779       // like undef&0.  The result is known zero, not undef.
1780       UndefElts &= UndefElts2;
1781       break;
1782     }
1783     break;
1784   }
1785   }
1786   return MadeChange ? I : 0;
1787 }
1788
1789
1790 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1791 /// function is designed to check a chain of associative operators for a
1792 /// potential to apply a certain optimization.  Since the optimization may be
1793 /// applicable if the expression was reassociated, this checks the chain, then
1794 /// reassociates the expression as necessary to expose the optimization
1795 /// opportunity.  This makes use of a special Functor, which must define
1796 /// 'shouldApply' and 'apply' methods.
1797 ///
1798 template<typename Functor>
1799 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1800                                    LLVMContext *Context) {
1801   unsigned Opcode = Root.getOpcode();
1802   Value *LHS = Root.getOperand(0);
1803
1804   // Quick check, see if the immediate LHS matches...
1805   if (F.shouldApply(LHS))
1806     return F.apply(Root);
1807
1808   // Otherwise, if the LHS is not of the same opcode as the root, return.
1809   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1810   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1811     // Should we apply this transform to the RHS?
1812     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1813
1814     // If not to the RHS, check to see if we should apply to the LHS...
1815     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1816       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1817       ShouldApply = true;
1818     }
1819
1820     // If the functor wants to apply the optimization to the RHS of LHSI,
1821     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1822     if (ShouldApply) {
1823       // Now all of the instructions are in the current basic block, go ahead
1824       // and perform the reassociation.
1825       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1826
1827       // First move the selected RHS to the LHS of the root...
1828       Root.setOperand(0, LHSI->getOperand(1));
1829
1830       // Make what used to be the LHS of the root be the user of the root...
1831       Value *ExtraOperand = TmpLHSI->getOperand(1);
1832       if (&Root == TmpLHSI) {
1833         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1834         return 0;
1835       }
1836       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1837       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1838       BasicBlock::iterator ARI = &Root; ++ARI;
1839       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1840       ARI = Root;
1841
1842       // Now propagate the ExtraOperand down the chain of instructions until we
1843       // get to LHSI.
1844       while (TmpLHSI != LHSI) {
1845         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1846         // Move the instruction to immediately before the chain we are
1847         // constructing to avoid breaking dominance properties.
1848         NextLHSI->moveBefore(ARI);
1849         ARI = NextLHSI;
1850
1851         Value *NextOp = NextLHSI->getOperand(1);
1852         NextLHSI->setOperand(1, ExtraOperand);
1853         TmpLHSI = NextLHSI;
1854         ExtraOperand = NextOp;
1855       }
1856
1857       // Now that the instructions are reassociated, have the functor perform
1858       // the transformation...
1859       return F.apply(Root);
1860     }
1861
1862     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1863   }
1864   return 0;
1865 }
1866
1867 namespace {
1868
1869 // AddRHS - Implements: X + X --> X << 1
1870 struct AddRHS {
1871   Value *RHS;
1872   LLVMContext *Context;
1873   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1874   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1875   Instruction *apply(BinaryOperator &Add) const {
1876     return BinaryOperator::CreateShl(Add.getOperand(0),
1877                                      Context->getConstantInt(Add.getType(), 1));
1878   }
1879 };
1880
1881 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1882 //                 iff C1&C2 == 0
1883 struct AddMaskingAnd {
1884   Constant *C2;
1885   LLVMContext *Context;
1886   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1887   bool shouldApply(Value *LHS) const {
1888     ConstantInt *C1;
1889     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1890            Context->getConstantExprAnd(C1, C2)->isNullValue();
1891   }
1892   Instruction *apply(BinaryOperator &Add) const {
1893     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1894   }
1895 };
1896
1897 }
1898
1899 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1900                                              InstCombiner *IC) {
1901   LLVMContext *Context = IC->getContext();
1902   
1903   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1904     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1905   }
1906
1907   // Figure out if the constant is the left or the right argument.
1908   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1909   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1910
1911   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1912     if (ConstIsRHS)
1913       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1914     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1915   }
1916
1917   Value *Op0 = SO, *Op1 = ConstOperand;
1918   if (!ConstIsRHS)
1919     std::swap(Op0, Op1);
1920   Instruction *New;
1921   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1922     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1923   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1924     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1925                           Op0, Op1, SO->getName()+".cmp");
1926   else {
1927     llvm_unreachable("Unknown binary instruction type!");
1928   }
1929   return IC->InsertNewInstBefore(New, I);
1930 }
1931
1932 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1933 // constant as the other operand, try to fold the binary operator into the
1934 // select arguments.  This also works for Cast instructions, which obviously do
1935 // not have a second operand.
1936 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1937                                      InstCombiner *IC) {
1938   // Don't modify shared select instructions
1939   if (!SI->hasOneUse()) return 0;
1940   Value *TV = SI->getOperand(1);
1941   Value *FV = SI->getOperand(2);
1942
1943   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1944     // Bool selects with constant operands can be folded to logical ops.
1945     if (SI->getType() == Type::Int1Ty) return 0;
1946
1947     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1948     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1949
1950     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1951                               SelectFalseVal);
1952   }
1953   return 0;
1954 }
1955
1956
1957 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1958 /// node as operand #0, see if we can fold the instruction into the PHI (which
1959 /// is only possible if all operands to the PHI are constants).
1960 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1961   PHINode *PN = cast<PHINode>(I.getOperand(0));
1962   unsigned NumPHIValues = PN->getNumIncomingValues();
1963   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1964
1965   // Check to see if all of the operands of the PHI are constants.  If there is
1966   // one non-constant value, remember the BB it is.  If there is more than one
1967   // or if *it* is a PHI, bail out.
1968   BasicBlock *NonConstBB = 0;
1969   for (unsigned i = 0; i != NumPHIValues; ++i)
1970     if (!isa<Constant>(PN->getIncomingValue(i))) {
1971       if (NonConstBB) return 0;  // More than one non-const value.
1972       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1973       NonConstBB = PN->getIncomingBlock(i);
1974       
1975       // If the incoming non-constant value is in I's block, we have an infinite
1976       // loop.
1977       if (NonConstBB == I.getParent())
1978         return 0;
1979     }
1980   
1981   // If there is exactly one non-constant value, we can insert a copy of the
1982   // operation in that block.  However, if this is a critical edge, we would be
1983   // inserting the computation one some other paths (e.g. inside a loop).  Only
1984   // do this if the pred block is unconditionally branching into the phi block.
1985   if (NonConstBB) {
1986     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1987     if (!BI || !BI->isUnconditional()) return 0;
1988   }
1989
1990   // Okay, we can do the transformation: create the new PHI node.
1991   PHINode *NewPN = PHINode::Create(I.getType(), "");
1992   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1993   InsertNewInstBefore(NewPN, *PN);
1994   NewPN->takeName(PN);
1995
1996   // Next, add all of the operands to the PHI.
1997   if (I.getNumOperands() == 2) {
1998     Constant *C = cast<Constant>(I.getOperand(1));
1999     for (unsigned i = 0; i != NumPHIValues; ++i) {
2000       Value *InV = 0;
2001       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2002         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2003           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2004         else
2005           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2006       } else {
2007         assert(PN->getIncomingBlock(i) == NonConstBB);
2008         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2009           InV = BinaryOperator::Create(BO->getOpcode(),
2010                                        PN->getIncomingValue(i), C, "phitmp",
2011                                        NonConstBB->getTerminator());
2012         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2013           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2014                                 CI->getPredicate(),
2015                                 PN->getIncomingValue(i), C, "phitmp",
2016                                 NonConstBB->getTerminator());
2017         else
2018           llvm_unreachable("Unknown binop!");
2019         
2020         AddToWorkList(cast<Instruction>(InV));
2021       }
2022       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2023     }
2024   } else { 
2025     CastInst *CI = cast<CastInst>(&I);
2026     const Type *RetTy = CI->getType();
2027     for (unsigned i = 0; i != NumPHIValues; ++i) {
2028       Value *InV;
2029       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2030         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2031       } else {
2032         assert(PN->getIncomingBlock(i) == NonConstBB);
2033         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2034                                I.getType(), "phitmp", 
2035                                NonConstBB->getTerminator());
2036         AddToWorkList(cast<Instruction>(InV));
2037       }
2038       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2039     }
2040   }
2041   return ReplaceInstUsesWith(I, NewPN);
2042 }
2043
2044
2045 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2046 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2047 /// This basically requires proving that the add in the original type would not
2048 /// overflow to change the sign bit or have a carry out.
2049 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2050   // There are different heuristics we can use for this.  Here are some simple
2051   // ones.
2052   
2053   // Add has the property that adding any two 2's complement numbers can only 
2054   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2055   // have at least two sign bits, we know that the addition of the two values will
2056   // sign extend fine.
2057   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2058     return true;
2059   
2060   
2061   // If one of the operands only has one non-zero bit, and if the other operand
2062   // has a known-zero bit in a more significant place than it (not including the
2063   // sign bit) the ripple may go up to and fill the zero, but won't change the
2064   // sign.  For example, (X & ~4) + 1.
2065   
2066   // TODO: Implement.
2067   
2068   return false;
2069 }
2070
2071
2072 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2073   bool Changed = SimplifyCommutative(I);
2074   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2075
2076   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2077     // X + undef -> undef
2078     if (isa<UndefValue>(RHS))
2079       return ReplaceInstUsesWith(I, RHS);
2080
2081     // X + 0 --> X
2082     if (RHSC->isNullValue())
2083       return ReplaceInstUsesWith(I, LHS);
2084
2085     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2086       // X + (signbit) --> X ^ signbit
2087       const APInt& Val = CI->getValue();
2088       uint32_t BitWidth = Val.getBitWidth();
2089       if (Val == APInt::getSignBit(BitWidth))
2090         return BinaryOperator::CreateXor(LHS, RHS);
2091       
2092       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2093       // (X & 254)+1 -> (X&254)|1
2094       if (SimplifyDemandedInstructionBits(I))
2095         return &I;
2096
2097       // zext(bool) + C -> bool ? C + 1 : C
2098       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2099         if (ZI->getSrcTy() == Type::Int1Ty)
2100           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2101     }
2102
2103     if (isa<PHINode>(LHS))
2104       if (Instruction *NV = FoldOpIntoPhi(I))
2105         return NV;
2106     
2107     ConstantInt *XorRHS = 0;
2108     Value *XorLHS = 0;
2109     if (isa<ConstantInt>(RHSC) &&
2110         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2111       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2112       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2113       
2114       uint32_t Size = TySizeBits / 2;
2115       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2116       APInt CFF80Val(-C0080Val);
2117       do {
2118         if (TySizeBits > Size) {
2119           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2120           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2121           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2122               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2123             // This is a sign extend if the top bits are known zero.
2124             if (!MaskedValueIsZero(XorLHS, 
2125                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2126               Size = 0;  // Not a sign ext, but can't be any others either.
2127             break;
2128           }
2129         }
2130         Size >>= 1;
2131         C0080Val = APIntOps::lshr(C0080Val, Size);
2132         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2133       } while (Size >= 1);
2134       
2135       // FIXME: This shouldn't be necessary. When the backends can handle types
2136       // with funny bit widths then this switch statement should be removed. It
2137       // is just here to get the size of the "middle" type back up to something
2138       // that the back ends can handle.
2139       const Type *MiddleType = 0;
2140       switch (Size) {
2141         default: break;
2142         case 32: MiddleType = Type::Int32Ty; break;
2143         case 16: MiddleType = Type::Int16Ty; break;
2144         case  8: MiddleType = Type::Int8Ty; break;
2145       }
2146       if (MiddleType) {
2147         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2148         InsertNewInstBefore(NewTrunc, I);
2149         return new SExtInst(NewTrunc, I.getType(), I.getName());
2150       }
2151     }
2152   }
2153
2154   if (I.getType() == Type::Int1Ty)
2155     return BinaryOperator::CreateXor(LHS, RHS);
2156
2157   // X + X --> X << 1
2158   if (I.getType()->isInteger()) {
2159     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2160       return Result;
2161
2162     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2163       if (RHSI->getOpcode() == Instruction::Sub)
2164         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2165           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2166     }
2167     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2168       if (LHSI->getOpcode() == Instruction::Sub)
2169         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2170           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2171     }
2172   }
2173
2174   // -A + B  -->  B - A
2175   // -A + -B  -->  -(A + B)
2176   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2177     if (LHS->getType()->isIntOrIntVector()) {
2178       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2179         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2180         InsertNewInstBefore(NewAdd, I);
2181         return BinaryOperator::CreateNeg(*Context, NewAdd);
2182       }
2183     }
2184     
2185     return BinaryOperator::CreateSub(RHS, LHSV);
2186   }
2187
2188   // A + -B  -->  A - B
2189   if (!isa<Constant>(RHS))
2190     if (Value *V = dyn_castNegVal(RHS, Context))
2191       return BinaryOperator::CreateSub(LHS, V);
2192
2193
2194   ConstantInt *C2;
2195   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2196     if (X == RHS)   // X*C + X --> X * (C+1)
2197       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2198
2199     // X*C1 + X*C2 --> X * (C1+C2)
2200     ConstantInt *C1;
2201     if (X == dyn_castFoldableMul(RHS, C1, Context))
2202       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2203   }
2204
2205   // X + X*C --> X * (C+1)
2206   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2207     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2208
2209   // X + ~X --> -1   since   ~X = -X-1
2210   if (dyn_castNotVal(LHS, Context) == RHS ||
2211       dyn_castNotVal(RHS, Context) == LHS)
2212     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2213   
2214
2215   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2216   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2217     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2218       return R;
2219   
2220   // A+B --> A|B iff A and B have no bits set in common.
2221   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2222     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2223     APInt LHSKnownOne(IT->getBitWidth(), 0);
2224     APInt LHSKnownZero(IT->getBitWidth(), 0);
2225     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2226     if (LHSKnownZero != 0) {
2227       APInt RHSKnownOne(IT->getBitWidth(), 0);
2228       APInt RHSKnownZero(IT->getBitWidth(), 0);
2229       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2230       
2231       // No bits in common -> bitwise or.
2232       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2233         return BinaryOperator::CreateOr(LHS, RHS);
2234     }
2235   }
2236
2237   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2238   if (I.getType()->isIntOrIntVector()) {
2239     Value *W, *X, *Y, *Z;
2240     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2241         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2242       if (W != Y) {
2243         if (W == Z) {
2244           std::swap(Y, Z);
2245         } else if (Y == X) {
2246           std::swap(W, X);
2247         } else if (X == Z) {
2248           std::swap(Y, Z);
2249           std::swap(W, X);
2250         }
2251       }
2252
2253       if (W == Y) {
2254         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2255                                                             LHS->getName()), I);
2256         return BinaryOperator::CreateMul(W, NewAdd);
2257       }
2258     }
2259   }
2260
2261   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2262     Value *X = 0;
2263     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2264       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2265
2266     // (X & FF00) + xx00  -> (X+xx00) & FF00
2267     if (LHS->hasOneUse() &&
2268         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2269       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2270       if (Anded == CRHS) {
2271         // See if all bits from the first bit set in the Add RHS up are included
2272         // in the mask.  First, get the rightmost bit.
2273         const APInt& AddRHSV = CRHS->getValue();
2274
2275         // Form a mask of all bits from the lowest bit added through the top.
2276         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2277
2278         // See if the and mask includes all of these bits.
2279         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2280
2281         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2282           // Okay, the xform is safe.  Insert the new add pronto.
2283           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2284                                                             LHS->getName()), I);
2285           return BinaryOperator::CreateAnd(NewAdd, C2);
2286         }
2287       }
2288     }
2289
2290     // Try to fold constant add into select arguments.
2291     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2292       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2293         return R;
2294   }
2295
2296   // add (cast *A to intptrtype) B -> 
2297   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2298   {
2299     CastInst *CI = dyn_cast<CastInst>(LHS);
2300     Value *Other = RHS;
2301     if (!CI) {
2302       CI = dyn_cast<CastInst>(RHS);
2303       Other = LHS;
2304     }
2305     if (CI && CI->getType()->isSized() && 
2306         (CI->getType()->getScalarSizeInBits() ==
2307          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2308         && isa<PointerType>(CI->getOperand(0)->getType())) {
2309       unsigned AS =
2310         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2311       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2312                                   Context->getPointerType(Type::Int8Ty, AS), I);
2313       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2314       return new PtrToIntInst(I2, CI->getType());
2315     }
2316   }
2317   
2318   // add (select X 0 (sub n A)) A  -->  select X A n
2319   {
2320     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2321     Value *A = RHS;
2322     if (!SI) {
2323       SI = dyn_cast<SelectInst>(RHS);
2324       A = LHS;
2325     }
2326     if (SI && SI->hasOneUse()) {
2327       Value *TV = SI->getTrueValue();
2328       Value *FV = SI->getFalseValue();
2329       Value *N;
2330
2331       // Can we fold the add into the argument of the select?
2332       // We check both true and false select arguments for a matching subtract.
2333       if (match(FV, m_Zero(), *Context) &&
2334           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2335         // Fold the add into the true select value.
2336         return SelectInst::Create(SI->getCondition(), N, A);
2337       if (match(TV, m_Zero(), *Context) &&
2338           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2339         // Fold the add into the false select value.
2340         return SelectInst::Create(SI->getCondition(), A, N);
2341     }
2342   }
2343
2344   // Check for (add (sext x), y), see if we can merge this into an
2345   // integer add followed by a sext.
2346   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2347     // (add (sext x), cst) --> (sext (add x, cst'))
2348     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2349       Constant *CI = 
2350         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2351       if (LHSConv->hasOneUse() &&
2352           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2353           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354         // Insert the new, smaller add.
2355         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2356                                                         CI, "addconv");
2357         InsertNewInstBefore(NewAdd, I);
2358         return new SExtInst(NewAdd, I.getType());
2359       }
2360     }
2361     
2362     // (add (sext x), (sext y)) --> (sext (add int x, y))
2363     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2364       // Only do this if x/y have the same type, if at last one of them has a
2365       // single use (so we don't increase the number of sexts), and if the
2366       // integer add will not overflow.
2367       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2368           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2369           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2370                                    RHSConv->getOperand(0))) {
2371         // Insert the new integer add.
2372         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2373                                                         RHSConv->getOperand(0),
2374                                                         "addconv");
2375         InsertNewInstBefore(NewAdd, I);
2376         return new SExtInst(NewAdd, I.getType());
2377       }
2378     }
2379   }
2380
2381   return Changed ? &I : 0;
2382 }
2383
2384 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2385   bool Changed = SimplifyCommutative(I);
2386   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2387
2388   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2389     // X + 0 --> X
2390     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2391       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2392                               (I.getType())->getValueAPF()))
2393         return ReplaceInstUsesWith(I, LHS);
2394     }
2395
2396     if (isa<PHINode>(LHS))
2397       if (Instruction *NV = FoldOpIntoPhi(I))
2398         return NV;
2399   }
2400
2401   // -A + B  -->  B - A
2402   // -A + -B  -->  -(A + B)
2403   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2404     return BinaryOperator::CreateFSub(RHS, LHSV);
2405
2406   // A + -B  -->  A - B
2407   if (!isa<Constant>(RHS))
2408     if (Value *V = dyn_castFNegVal(RHS, Context))
2409       return BinaryOperator::CreateFSub(LHS, V);
2410
2411   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2412   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2413     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2414       return ReplaceInstUsesWith(I, LHS);
2415
2416   // Check for (add double (sitofp x), y), see if we can merge this into an
2417   // integer add followed by a promotion.
2418   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2419     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2420     // ... if the constant fits in the integer value.  This is useful for things
2421     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2422     // requires a constant pool load, and generally allows the add to be better
2423     // instcombined.
2424     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2425       Constant *CI = 
2426       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2427       if (LHSConv->hasOneUse() &&
2428           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2429           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2430         // Insert the new integer add.
2431         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2432                                                         CI, "addconv");
2433         InsertNewInstBefore(NewAdd, I);
2434         return new SIToFPInst(NewAdd, I.getType());
2435       }
2436     }
2437     
2438     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2439     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2440       // Only do this if x/y have the same type, if at last one of them has a
2441       // single use (so we don't increase the number of int->fp conversions),
2442       // and if the integer add will not overflow.
2443       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2444           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2445           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2446                                    RHSConv->getOperand(0))) {
2447         // Insert the new integer add.
2448         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2449                                                         RHSConv->getOperand(0),
2450                                                         "addconv");
2451         InsertNewInstBefore(NewAdd, I);
2452         return new SIToFPInst(NewAdd, I.getType());
2453       }
2454     }
2455   }
2456   
2457   return Changed ? &I : 0;
2458 }
2459
2460 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2461   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2462
2463   if (Op0 == Op1)                        // sub X, X  -> 0
2464     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2465
2466   // If this is a 'B = x-(-A)', change to B = x+A...
2467   if (Value *V = dyn_castNegVal(Op1, Context))
2468     return BinaryOperator::CreateAdd(Op0, V);
2469
2470   if (isa<UndefValue>(Op0))
2471     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2472   if (isa<UndefValue>(Op1))
2473     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2474
2475   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2476     // Replace (-1 - A) with (~A)...
2477     if (C->isAllOnesValue())
2478       return BinaryOperator::CreateNot(*Context, Op1);
2479
2480     // C - ~X == X + (1+C)
2481     Value *X = 0;
2482     if (match(Op1, m_Not(m_Value(X)), *Context))
2483       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2484
2485     // -(X >>u 31) -> (X >>s 31)
2486     // -(X >>s 31) -> (X >>u 31)
2487     if (C->isZero()) {
2488       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2489         if (SI->getOpcode() == Instruction::LShr) {
2490           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2491             // Check to see if we are shifting out everything but the sign bit.
2492             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2493                 SI->getType()->getPrimitiveSizeInBits()-1) {
2494               // Ok, the transformation is safe.  Insert AShr.
2495               return BinaryOperator::Create(Instruction::AShr, 
2496                                           SI->getOperand(0), CU, SI->getName());
2497             }
2498           }
2499         }
2500         else if (SI->getOpcode() == Instruction::AShr) {
2501           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2502             // Check to see if we are shifting out everything but the sign bit.
2503             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2504                 SI->getType()->getPrimitiveSizeInBits()-1) {
2505               // Ok, the transformation is safe.  Insert LShr. 
2506               return BinaryOperator::CreateLShr(
2507                                           SI->getOperand(0), CU, SI->getName());
2508             }
2509           }
2510         }
2511       }
2512     }
2513
2514     // Try to fold constant sub into select arguments.
2515     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2516       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2517         return R;
2518
2519     // C - zext(bool) -> bool ? C - 1 : C
2520     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2521       if (ZI->getSrcTy() == Type::Int1Ty)
2522         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2523   }
2524
2525   if (I.getType() == Type::Int1Ty)
2526     return BinaryOperator::CreateXor(Op0, Op1);
2527
2528   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2529     if (Op1I->getOpcode() == Instruction::Add) {
2530       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2531         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2532                                          I.getName());
2533       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2534         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2535                                          I.getName());
2536       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2537         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2538           // C1-(X+C2) --> (C1-C2)-X
2539           return BinaryOperator::CreateSub(
2540             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2541       }
2542     }
2543
2544     if (Op1I->hasOneUse()) {
2545       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2546       // is not used by anyone else...
2547       //
2548       if (Op1I->getOpcode() == Instruction::Sub) {
2549         // Swap the two operands of the subexpr...
2550         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2551         Op1I->setOperand(0, IIOp1);
2552         Op1I->setOperand(1, IIOp0);
2553
2554         // Create the new top level add instruction...
2555         return BinaryOperator::CreateAdd(Op0, Op1);
2556       }
2557
2558       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2559       //
2560       if (Op1I->getOpcode() == Instruction::And &&
2561           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2562         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2563
2564         Value *NewNot =
2565           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2566                                                         OtherOp, "B.not"), I);
2567         return BinaryOperator::CreateAnd(Op0, NewNot);
2568       }
2569
2570       // 0 - (X sdiv C)  -> (X sdiv -C)
2571       if (Op1I->getOpcode() == Instruction::SDiv)
2572         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2573           if (CSI->isZero())
2574             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2575               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2576                                           Context->getConstantExprNeg(DivRHS));
2577
2578       // X - X*C --> X * (1-C)
2579       ConstantInt *C2 = 0;
2580       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2581         Constant *CP1 = 
2582           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2583                                              C2);
2584         return BinaryOperator::CreateMul(Op0, CP1);
2585       }
2586     }
2587   }
2588
2589   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2590     if (Op0I->getOpcode() == Instruction::Add) {
2591       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2592         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2593       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2594         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2595     } else if (Op0I->getOpcode() == Instruction::Sub) {
2596       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2597         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2598                                          I.getName());
2599     }
2600   }
2601
2602   ConstantInt *C1;
2603   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2604     if (X == Op1)  // X*C - X --> X * (C-1)
2605       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2606
2607     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2608     if (X == dyn_castFoldableMul(Op1, C2, Context))
2609       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2610   }
2611   return 0;
2612 }
2613
2614 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2615   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2616
2617   // If this is a 'B = x-(-A)', change to B = x+A...
2618   if (Value *V = dyn_castFNegVal(Op1, Context))
2619     return BinaryOperator::CreateFAdd(Op0, V);
2620
2621   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2622     if (Op1I->getOpcode() == Instruction::FAdd) {
2623       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2624         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2625                                           I.getName());
2626       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2627         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2628                                           I.getName());
2629     }
2630   }
2631
2632   return 0;
2633 }
2634
2635 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2636 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2637 /// TrueIfSigned if the result of the comparison is true when the input value is
2638 /// signed.
2639 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2640                            bool &TrueIfSigned) {
2641   switch (pred) {
2642   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2643     TrueIfSigned = true;
2644     return RHS->isZero();
2645   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2646     TrueIfSigned = true;
2647     return RHS->isAllOnesValue();
2648   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2649     TrueIfSigned = false;
2650     return RHS->isAllOnesValue();
2651   case ICmpInst::ICMP_UGT:
2652     // True if LHS u> RHS and RHS == high-bit-mask - 1
2653     TrueIfSigned = true;
2654     return RHS->getValue() ==
2655       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2656   case ICmpInst::ICMP_UGE: 
2657     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2658     TrueIfSigned = true;
2659     return RHS->getValue().isSignBit();
2660   default:
2661     return false;
2662   }
2663 }
2664
2665 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2666   bool Changed = SimplifyCommutative(I);
2667   Value *Op0 = I.getOperand(0);
2668
2669   // TODO: If Op1 is undef and Op0 is finite, return zero.
2670   if (!I.getType()->isFPOrFPVector() &&
2671       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2672     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2673
2674   // Simplify mul instructions with a constant RHS...
2675   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2676     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2677
2678       // ((X << C1)*C2) == (X * (C2 << C1))
2679       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2680         if (SI->getOpcode() == Instruction::Shl)
2681           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2682             return BinaryOperator::CreateMul(SI->getOperand(0),
2683                                         Context->getConstantExprShl(CI, ShOp));
2684
2685       if (CI->isZero())
2686         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2687       if (CI->equalsInt(1))                  // X * 1  == X
2688         return ReplaceInstUsesWith(I, Op0);
2689       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2690         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2691
2692       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2693       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2694         return BinaryOperator::CreateShl(Op0,
2695                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2696       }
2697     } else if (isa<VectorType>(Op1->getType())) {
2698       if (Op1->isNullValue())
2699         return ReplaceInstUsesWith(I, Op1);
2700
2701       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2702         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2703           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2704
2705         // As above, vector X*splat(1.0) -> X in all defined cases.
2706         if (Constant *Splat = Op1V->getSplatValue()) {
2707           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2708             if (CI->equalsInt(1))
2709               return ReplaceInstUsesWith(I, Op0);
2710         }
2711       }
2712     }
2713     
2714     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2715       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2716           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2717         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2718         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2719                                                      Op1, "tmp");
2720         InsertNewInstBefore(Add, I);
2721         Value *C1C2 = Context->getConstantExprMul(Op1, 
2722                                            cast<Constant>(Op0I->getOperand(1)));
2723         return BinaryOperator::CreateAdd(Add, C1C2);
2724         
2725       }
2726
2727     // Try to fold constant mul into select arguments.
2728     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2729       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2730         return R;
2731
2732     if (isa<PHINode>(Op0))
2733       if (Instruction *NV = FoldOpIntoPhi(I))
2734         return NV;
2735   }
2736
2737   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2738     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2739       return BinaryOperator::CreateMul(Op0v, Op1v);
2740
2741   // (X / Y) *  Y = X - (X % Y)
2742   // (X / Y) * -Y = (X % Y) - X
2743   {
2744     Value *Op1 = I.getOperand(1);
2745     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2746     if (!BO ||
2747         (BO->getOpcode() != Instruction::UDiv && 
2748          BO->getOpcode() != Instruction::SDiv)) {
2749       Op1 = Op0;
2750       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2751     }
2752     Value *Neg = dyn_castNegVal(Op1, Context);
2753     if (BO && BO->hasOneUse() &&
2754         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2755         (BO->getOpcode() == Instruction::UDiv ||
2756          BO->getOpcode() == Instruction::SDiv)) {
2757       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2758
2759       Instruction *Rem;
2760       if (BO->getOpcode() == Instruction::UDiv)
2761         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2762       else
2763         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2764
2765       InsertNewInstBefore(Rem, I);
2766       Rem->takeName(BO);
2767
2768       if (Op1BO == Op1)
2769         return BinaryOperator::CreateSub(Op0BO, Rem);
2770       else
2771         return BinaryOperator::CreateSub(Rem, Op0BO);
2772     }
2773   }
2774
2775   if (I.getType() == Type::Int1Ty)
2776     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2777
2778   // If one of the operands of the multiply is a cast from a boolean value, then
2779   // we know the bool is either zero or one, so this is a 'masking' multiply.
2780   // See if we can simplify things based on how the boolean was originally
2781   // formed.
2782   CastInst *BoolCast = 0;
2783   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2784     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2785       BoolCast = CI;
2786   if (!BoolCast)
2787     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2788       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2789         BoolCast = CI;
2790   if (BoolCast) {
2791     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2792       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2793       const Type *SCOpTy = SCIOp0->getType();
2794       bool TIS = false;
2795       
2796       // If the icmp is true iff the sign bit of X is set, then convert this
2797       // multiply into a shift/and combination.
2798       if (isa<ConstantInt>(SCIOp1) &&
2799           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2800           TIS) {
2801         // Shift the X value right to turn it into "all signbits".
2802         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2803                                           SCOpTy->getPrimitiveSizeInBits()-1);
2804         Value *V =
2805           InsertNewInstBefore(
2806             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2807                                             BoolCast->getOperand(0)->getName()+
2808                                             ".mask"), I);
2809
2810         // If the multiply type is not the same as the source type, sign extend
2811         // or truncate to the multiply type.
2812         if (I.getType() != V->getType()) {
2813           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2814           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2815           Instruction::CastOps opcode = 
2816             (SrcBits == DstBits ? Instruction::BitCast : 
2817              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2818           V = InsertCastBefore(opcode, V, I.getType(), I);
2819         }
2820
2821         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2822         return BinaryOperator::CreateAnd(V, OtherOp);
2823       }
2824     }
2825   }
2826
2827   return Changed ? &I : 0;
2828 }
2829
2830 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2831   bool Changed = SimplifyCommutative(I);
2832   Value *Op0 = I.getOperand(0);
2833
2834   // Simplify mul instructions with a constant RHS...
2835   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2836     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2837       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2838       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2839       if (Op1F->isExactlyValue(1.0))
2840         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2841     } else if (isa<VectorType>(Op1->getType())) {
2842       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2843         // As above, vector X*splat(1.0) -> X in all defined cases.
2844         if (Constant *Splat = Op1V->getSplatValue()) {
2845           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2846             if (F->isExactlyValue(1.0))
2847               return ReplaceInstUsesWith(I, Op0);
2848         }
2849       }
2850     }
2851
2852     // Try to fold constant mul into select arguments.
2853     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2854       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2855         return R;
2856
2857     if (isa<PHINode>(Op0))
2858       if (Instruction *NV = FoldOpIntoPhi(I))
2859         return NV;
2860   }
2861
2862   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2863     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2864       return BinaryOperator::CreateFMul(Op0v, Op1v);
2865
2866   return Changed ? &I : 0;
2867 }
2868
2869 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2870 /// instruction.
2871 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2872   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2873   
2874   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2875   int NonNullOperand = -1;
2876   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2877     if (ST->isNullValue())
2878       NonNullOperand = 2;
2879   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2880   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2881     if (ST->isNullValue())
2882       NonNullOperand = 1;
2883   
2884   if (NonNullOperand == -1)
2885     return false;
2886   
2887   Value *SelectCond = SI->getOperand(0);
2888   
2889   // Change the div/rem to use 'Y' instead of the select.
2890   I.setOperand(1, SI->getOperand(NonNullOperand));
2891   
2892   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2893   // problem.  However, the select, or the condition of the select may have
2894   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2895   // propagate the known value for the select into other uses of it, and
2896   // propagate a known value of the condition into its other users.
2897   
2898   // If the select and condition only have a single use, don't bother with this,
2899   // early exit.
2900   if (SI->use_empty() && SelectCond->hasOneUse())
2901     return true;
2902   
2903   // Scan the current block backward, looking for other uses of SI.
2904   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2905   
2906   while (BBI != BBFront) {
2907     --BBI;
2908     // If we found a call to a function, we can't assume it will return, so
2909     // information from below it cannot be propagated above it.
2910     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2911       break;
2912     
2913     // Replace uses of the select or its condition with the known values.
2914     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2915          I != E; ++I) {
2916       if (*I == SI) {
2917         *I = SI->getOperand(NonNullOperand);
2918         AddToWorkList(BBI);
2919       } else if (*I == SelectCond) {
2920         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2921                                    Context->getConstantIntFalse();
2922         AddToWorkList(BBI);
2923       }
2924     }
2925     
2926     // If we past the instruction, quit looking for it.
2927     if (&*BBI == SI)
2928       SI = 0;
2929     if (&*BBI == SelectCond)
2930       SelectCond = 0;
2931     
2932     // If we ran out of things to eliminate, break out of the loop.
2933     if (SelectCond == 0 && SI == 0)
2934       break;
2935     
2936   }
2937   return true;
2938 }
2939
2940
2941 /// This function implements the transforms on div instructions that work
2942 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2943 /// used by the visitors to those instructions.
2944 /// @brief Transforms common to all three div instructions
2945 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2946   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2947
2948   // undef / X -> 0        for integer.
2949   // undef / X -> undef    for FP (the undef could be a snan).
2950   if (isa<UndefValue>(Op0)) {
2951     if (Op0->getType()->isFPOrFPVector())
2952       return ReplaceInstUsesWith(I, Op0);
2953     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2954   }
2955
2956   // X / undef -> undef
2957   if (isa<UndefValue>(Op1))
2958     return ReplaceInstUsesWith(I, Op1);
2959
2960   return 0;
2961 }
2962
2963 /// This function implements the transforms common to both integer division
2964 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2965 /// division instructions.
2966 /// @brief Common integer divide transforms
2967 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2968   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2969
2970   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2971   if (Op0 == Op1) {
2972     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2973       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2974       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2975       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2976     }
2977
2978     Constant *CI = Context->getConstantInt(I.getType(), 1);
2979     return ReplaceInstUsesWith(I, CI);
2980   }
2981   
2982   if (Instruction *Common = commonDivTransforms(I))
2983     return Common;
2984   
2985   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2986   // This does not apply for fdiv.
2987   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2988     return &I;
2989
2990   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2991     // div X, 1 == X
2992     if (RHS->equalsInt(1))
2993       return ReplaceInstUsesWith(I, Op0);
2994
2995     // (X / C1) / C2  -> X / (C1*C2)
2996     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2997       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2998         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2999           if (MultiplyOverflows(RHS, LHSRHS,
3000                                 I.getOpcode()==Instruction::SDiv, Context))
3001             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3002           else 
3003             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3004                                       Context->getConstantExprMul(RHS, LHSRHS));
3005         }
3006
3007     if (!RHS->isZero()) { // avoid X udiv 0
3008       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3009         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3010           return R;
3011       if (isa<PHINode>(Op0))
3012         if (Instruction *NV = FoldOpIntoPhi(I))
3013           return NV;
3014     }
3015   }
3016
3017   // 0 / X == 0, we don't need to preserve faults!
3018   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3019     if (LHS->equalsInt(0))
3020       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3021
3022   // It can't be division by zero, hence it must be division by one.
3023   if (I.getType() == Type::Int1Ty)
3024     return ReplaceInstUsesWith(I, Op0);
3025
3026   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3027     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3028       // div X, 1 == X
3029       if (X->isOne())
3030         return ReplaceInstUsesWith(I, Op0);
3031   }
3032
3033   return 0;
3034 }
3035
3036 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3037   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039   // Handle the integer div common cases
3040   if (Instruction *Common = commonIDivTransforms(I))
3041     return Common;
3042
3043   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3044     // X udiv C^2 -> X >> C
3045     // Check to see if this is an unsigned division with an exact power of 2,
3046     // if so, convert to a right shift.
3047     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3048       return BinaryOperator::CreateLShr(Op0, 
3049             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3050
3051     // X udiv C, where C >= signbit
3052     if (C->getValue().isNegative()) {
3053       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3054                                                     ICmpInst::ICMP_ULT, Op0, C),
3055                                       I);
3056       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3057                                 Context->getConstantInt(I.getType(), 1));
3058     }
3059   }
3060
3061   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3062   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3063     if (RHSI->getOpcode() == Instruction::Shl &&
3064         isa<ConstantInt>(RHSI->getOperand(0))) {
3065       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3066       if (C1.isPowerOf2()) {
3067         Value *N = RHSI->getOperand(1);
3068         const Type *NTy = N->getType();
3069         if (uint32_t C2 = C1.logBase2()) {
3070           Constant *C2V = Context->getConstantInt(NTy, C2);
3071           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3072         }
3073         return BinaryOperator::CreateLShr(Op0, N);
3074       }
3075     }
3076   }
3077   
3078   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3079   // where C1&C2 are powers of two.
3080   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3081     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3082       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3083         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3084         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3085           // Compute the shift amounts
3086           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3087           // Construct the "on true" case of the select
3088           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3089           Instruction *TSI = BinaryOperator::CreateLShr(
3090                                                  Op0, TC, SI->getName()+".t");
3091           TSI = InsertNewInstBefore(TSI, I);
3092   
3093           // Construct the "on false" case of the select
3094           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3095           Instruction *FSI = BinaryOperator::CreateLShr(
3096                                                  Op0, FC, SI->getName()+".f");
3097           FSI = InsertNewInstBefore(FSI, I);
3098
3099           // construct the select instruction and return it.
3100           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3101         }
3102       }
3103   return 0;
3104 }
3105
3106 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3107   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3108
3109   // Handle the integer div common cases
3110   if (Instruction *Common = commonIDivTransforms(I))
3111     return Common;
3112
3113   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3114     // sdiv X, -1 == -X
3115     if (RHS->isAllOnesValue())
3116       return BinaryOperator::CreateNeg(*Context, Op0);
3117   }
3118
3119   // If the sign bits of both operands are zero (i.e. we can prove they are
3120   // unsigned inputs), turn this into a udiv.
3121   if (I.getType()->isInteger()) {
3122     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3123     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3124       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3125       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3126     }
3127   }      
3128   
3129   return 0;
3130 }
3131
3132 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3133   return commonDivTransforms(I);
3134 }
3135
3136 /// This function implements the transforms on rem instructions that work
3137 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3138 /// is used by the visitors to those instructions.
3139 /// @brief Transforms common to all three rem instructions
3140 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3141   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3142
3143   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3144     if (I.getType()->isFPOrFPVector())
3145       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3146     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3147   }
3148   if (isa<UndefValue>(Op1))
3149     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3150
3151   // Handle cases involving: rem X, (select Cond, Y, Z)
3152   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3153     return &I;
3154
3155   return 0;
3156 }
3157
3158 /// This function implements the transforms common to both integer remainder
3159 /// instructions (urem and srem). It is called by the visitors to those integer
3160 /// remainder instructions.
3161 /// @brief Common integer remainder transforms
3162 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3163   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3164
3165   if (Instruction *common = commonRemTransforms(I))
3166     return common;
3167
3168   // 0 % X == 0 for integer, we don't need to preserve faults!
3169   if (Constant *LHS = dyn_cast<Constant>(Op0))
3170     if (LHS->isNullValue())
3171       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3172
3173   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3174     // X % 0 == undef, we don't need to preserve faults!
3175     if (RHS->equalsInt(0))
3176       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3177     
3178     if (RHS->equalsInt(1))  // X % 1 == 0
3179       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3180
3181     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3182       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3183         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3184           return R;
3185       } else if (isa<PHINode>(Op0I)) {
3186         if (Instruction *NV = FoldOpIntoPhi(I))
3187           return NV;
3188       }
3189
3190       // See if we can fold away this rem instruction.
3191       if (SimplifyDemandedInstructionBits(I))
3192         return &I;
3193     }
3194   }
3195
3196   return 0;
3197 }
3198
3199 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3200   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3201
3202   if (Instruction *common = commonIRemTransforms(I))
3203     return common;
3204   
3205   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3206     // X urem C^2 -> X and C
3207     // Check to see if this is an unsigned remainder with an exact power of 2,
3208     // if so, convert to a bitwise and.
3209     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3210       if (C->getValue().isPowerOf2())
3211         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3212   }
3213
3214   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3215     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3216     if (RHSI->getOpcode() == Instruction::Shl &&
3217         isa<ConstantInt>(RHSI->getOperand(0))) {
3218       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3219         Constant *N1 = Context->getAllOnesValue(I.getType());
3220         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3221                                                                    "tmp"), I);
3222         return BinaryOperator::CreateAnd(Op0, Add);
3223       }
3224     }
3225   }
3226
3227   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3228   // where C1&C2 are powers of two.
3229   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3230     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3231       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3232         // STO == 0 and SFO == 0 handled above.
3233         if ((STO->getValue().isPowerOf2()) && 
3234             (SFO->getValue().isPowerOf2())) {
3235           Value *TrueAnd = InsertNewInstBefore(
3236             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3237                                       SI->getName()+".t"), I);
3238           Value *FalseAnd = InsertNewInstBefore(
3239             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3240                                       SI->getName()+".f"), I);
3241           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3242         }
3243       }
3244   }
3245   
3246   return 0;
3247 }
3248
3249 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3250   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3251
3252   // Handle the integer rem common cases
3253   if (Instruction *common = commonIRemTransforms(I))
3254     return common;
3255   
3256   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3257     if (!isa<Constant>(RHSNeg) ||
3258         (isa<ConstantInt>(RHSNeg) &&
3259          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3260       // X % -Y -> X % Y
3261       AddUsesToWorkList(I);
3262       I.setOperand(1, RHSNeg);
3263       return &I;
3264     }
3265
3266   // If the sign bits of both operands are zero (i.e. we can prove they are
3267   // unsigned inputs), turn this into a urem.
3268   if (I.getType()->isInteger()) {
3269     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3270     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3271       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3272       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3273     }
3274   }
3275
3276   // If it's a constant vector, flip any negative values positive.
3277   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3278     unsigned VWidth = RHSV->getNumOperands();
3279
3280     bool hasNegative = false;
3281     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3282       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3283         if (RHS->getValue().isNegative())
3284           hasNegative = true;
3285
3286     if (hasNegative) {
3287       std::vector<Constant *> Elts(VWidth);
3288       for (unsigned i = 0; i != VWidth; ++i) {
3289         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3290           if (RHS->getValue().isNegative())
3291             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3292           else
3293             Elts[i] = RHS;
3294         }
3295       }
3296
3297       Constant *NewRHSV = Context->getConstantVector(Elts);
3298       if (NewRHSV != RHSV) {
3299         AddUsesToWorkList(I);
3300         I.setOperand(1, NewRHSV);
3301         return &I;
3302       }
3303     }
3304   }
3305
3306   return 0;
3307 }
3308
3309 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3310   return commonRemTransforms(I);
3311 }
3312
3313 // isOneBitSet - Return true if there is exactly one bit set in the specified
3314 // constant.
3315 static bool isOneBitSet(const ConstantInt *CI) {
3316   return CI->getValue().isPowerOf2();
3317 }
3318
3319 // isHighOnes - Return true if the constant is of the form 1+0+.
3320 // This is the same as lowones(~X).
3321 static bool isHighOnes(const ConstantInt *CI) {
3322   return (~CI->getValue() + 1).isPowerOf2();
3323 }
3324
3325 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3326 /// are carefully arranged to allow folding of expressions such as:
3327 ///
3328 ///      (A < B) | (A > B) --> (A != B)
3329 ///
3330 /// Note that this is only valid if the first and second predicates have the
3331 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3332 ///
3333 /// Three bits are used to represent the condition, as follows:
3334 ///   0  A > B
3335 ///   1  A == B
3336 ///   2  A < B
3337 ///
3338 /// <=>  Value  Definition
3339 /// 000     0   Always false
3340 /// 001     1   A >  B
3341 /// 010     2   A == B
3342 /// 011     3   A >= B
3343 /// 100     4   A <  B
3344 /// 101     5   A != B
3345 /// 110     6   A <= B
3346 /// 111     7   Always true
3347 ///  
3348 static unsigned getICmpCode(const ICmpInst *ICI) {
3349   switch (ICI->getPredicate()) {
3350     // False -> 0
3351   case ICmpInst::ICMP_UGT: return 1;  // 001
3352   case ICmpInst::ICMP_SGT: return 1;  // 001
3353   case ICmpInst::ICMP_EQ:  return 2;  // 010
3354   case ICmpInst::ICMP_UGE: return 3;  // 011
3355   case ICmpInst::ICMP_SGE: return 3;  // 011
3356   case ICmpInst::ICMP_ULT: return 4;  // 100
3357   case ICmpInst::ICMP_SLT: return 4;  // 100
3358   case ICmpInst::ICMP_NE:  return 5;  // 101
3359   case ICmpInst::ICMP_ULE: return 6;  // 110
3360   case ICmpInst::ICMP_SLE: return 6;  // 110
3361     // True -> 7
3362   default:
3363     llvm_unreachable("Invalid ICmp predicate!");
3364     return 0;
3365   }
3366 }
3367
3368 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3369 /// predicate into a three bit mask. It also returns whether it is an ordered
3370 /// predicate by reference.
3371 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3372   isOrdered = false;
3373   switch (CC) {
3374   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3375   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3376   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3377   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3378   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3379   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3380   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3381   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3382   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3383   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3384   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3385   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3386   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3387   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3388     // True -> 7
3389   default:
3390     // Not expecting FCMP_FALSE and FCMP_TRUE;
3391     llvm_unreachable("Unexpected FCmp predicate!");
3392     return 0;
3393   }
3394 }
3395
3396 /// getICmpValue - This is the complement of getICmpCode, which turns an
3397 /// opcode and two operands into either a constant true or false, or a brand 
3398 /// new ICmp instruction. The sign is passed in to determine which kind
3399 /// of predicate to use in the new icmp instruction.
3400 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3401                            LLVMContext *Context) {
3402   switch (code) {
3403   default: llvm_unreachable("Illegal ICmp code!");
3404   case  0: return Context->getConstantIntFalse();
3405   case  1: 
3406     if (sign)
3407       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3408     else
3409       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3410   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3411   case  3: 
3412     if (sign)
3413       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3414     else
3415       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3416   case  4: 
3417     if (sign)
3418       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3419     else
3420       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3421   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3422   case  6: 
3423     if (sign)
3424       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3425     else
3426       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3427   case  7: return Context->getConstantIntTrue();
3428   }
3429 }
3430
3431 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3432 /// opcode and two operands into either a FCmp instruction. isordered is passed
3433 /// in to determine which kind of predicate to use in the new fcmp instruction.
3434 static Value *getFCmpValue(bool isordered, unsigned code,
3435                            Value *LHS, Value *RHS, LLVMContext *Context) {
3436   switch (code) {
3437   default: llvm_unreachable("Illegal FCmp code!");
3438   case  0:
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3443   case  1: 
3444     if (isordered)
3445       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3446     else
3447       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3448   case  2: 
3449     if (isordered)
3450       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3451     else
3452       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3453   case  3: 
3454     if (isordered)
3455       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3456     else
3457       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3458   case  4: 
3459     if (isordered)
3460       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3461     else
3462       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3463   case  5: 
3464     if (isordered)
3465       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3466     else
3467       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3468   case  6: 
3469     if (isordered)
3470       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3471     else
3472       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3473   case  7: return Context->getConstantIntTrue();
3474   }
3475 }
3476
3477 /// PredicatesFoldable - Return true if both predicates match sign or if at
3478 /// least one of them is an equality comparison (which is signless).
3479 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3480   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3481          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3482          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3483 }
3484
3485 namespace { 
3486 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3487 struct FoldICmpLogical {
3488   InstCombiner &IC;
3489   Value *LHS, *RHS;
3490   ICmpInst::Predicate pred;
3491   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3492     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3493       pred(ICI->getPredicate()) {}
3494   bool shouldApply(Value *V) const {
3495     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3496       if (PredicatesFoldable(pred, ICI->getPredicate()))
3497         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3498                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3499     return false;
3500   }
3501   Instruction *apply(Instruction &Log) const {
3502     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3503     if (ICI->getOperand(0) != LHS) {
3504       assert(ICI->getOperand(1) == LHS);
3505       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3506     }
3507
3508     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3509     unsigned LHSCode = getICmpCode(ICI);
3510     unsigned RHSCode = getICmpCode(RHSICI);
3511     unsigned Code;
3512     switch (Log.getOpcode()) {
3513     case Instruction::And: Code = LHSCode & RHSCode; break;
3514     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3515     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3516     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3517     }
3518
3519     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3520                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3521       
3522     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3523     if (Instruction *I = dyn_cast<Instruction>(RV))
3524       return I;
3525     // Otherwise, it's a constant boolean value...
3526     return IC.ReplaceInstUsesWith(Log, RV);
3527   }
3528 };
3529 } // end anonymous namespace
3530
3531 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3532 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3533 // guaranteed to be a binary operator.
3534 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3535                                     ConstantInt *OpRHS,
3536                                     ConstantInt *AndRHS,
3537                                     BinaryOperator &TheAnd) {
3538   Value *X = Op->getOperand(0);
3539   Constant *Together = 0;
3540   if (!Op->isShift())
3541     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3542
3543   switch (Op->getOpcode()) {
3544   case Instruction::Xor:
3545     if (Op->hasOneUse()) {
3546       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3547       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3548       InsertNewInstBefore(And, TheAnd);
3549       And->takeName(Op);
3550       return BinaryOperator::CreateXor(And, Together);
3551     }
3552     break;
3553   case Instruction::Or:
3554     if (Together == AndRHS) // (X | C) & C --> C
3555       return ReplaceInstUsesWith(TheAnd, AndRHS);
3556
3557     if (Op->hasOneUse() && Together != OpRHS) {
3558       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3559       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3560       InsertNewInstBefore(Or, TheAnd);
3561       Or->takeName(Op);
3562       return BinaryOperator::CreateAnd(Or, AndRHS);
3563     }
3564     break;
3565   case Instruction::Add:
3566     if (Op->hasOneUse()) {
3567       // Adding a one to a single bit bit-field should be turned into an XOR
3568       // of the bit.  First thing to check is to see if this AND is with a
3569       // single bit constant.
3570       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3571
3572       // If there is only one bit set...
3573       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3574         // Ok, at this point, we know that we are masking the result of the
3575         // ADD down to exactly one bit.  If the constant we are adding has
3576         // no bits set below this bit, then we can eliminate the ADD.
3577         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3578
3579         // Check to see if any bits below the one bit set in AndRHSV are set.
3580         if ((AddRHS & (AndRHSV-1)) == 0) {
3581           // If not, the only thing that can effect the output of the AND is
3582           // the bit specified by AndRHSV.  If that bit is set, the effect of
3583           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3584           // no effect.
3585           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3586             TheAnd.setOperand(0, X);
3587             return &TheAnd;
3588           } else {
3589             // Pull the XOR out of the AND.
3590             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3591             InsertNewInstBefore(NewAnd, TheAnd);
3592             NewAnd->takeName(Op);
3593             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3594           }
3595         }
3596       }
3597     }
3598     break;
3599
3600   case Instruction::Shl: {
3601     // We know that the AND will not produce any of the bits shifted in, so if
3602     // the anded constant includes them, clear them now!
3603     //
3604     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3605     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3606     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3607     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3608
3609     if (CI->getValue() == ShlMask) { 
3610     // Masking out bits that the shift already masks
3611       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3612     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3613       TheAnd.setOperand(1, CI);
3614       return &TheAnd;
3615     }
3616     break;
3617   }
3618   case Instruction::LShr:
3619   {
3620     // We know that the AND will not produce any of the bits shifted in, so if
3621     // the anded constant includes them, clear them now!  This only applies to
3622     // unsigned shifts, because a signed shr may bring in set bits!
3623     //
3624     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3625     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3626     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3627     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3628
3629     if (CI->getValue() == ShrMask) {   
3630     // Masking out bits that the shift already masks.
3631       return ReplaceInstUsesWith(TheAnd, Op);
3632     } else if (CI != AndRHS) {
3633       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3634       return &TheAnd;
3635     }
3636     break;
3637   }
3638   case Instruction::AShr:
3639     // Signed shr.
3640     // See if this is shifting in some sign extension, then masking it out
3641     // with an and.
3642     if (Op->hasOneUse()) {
3643       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3644       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3645       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3646       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3647       if (C == AndRHS) {          // Masking out bits shifted in.
3648         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3649         // Make the argument unsigned.
3650         Value *ShVal = Op->getOperand(0);
3651         ShVal = InsertNewInstBefore(
3652             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3653                                    Op->getName()), TheAnd);
3654         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3655       }
3656     }
3657     break;
3658   }
3659   return 0;
3660 }
3661
3662
3663 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3664 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3665 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3666 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3667 /// insert new instructions.
3668 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3669                                            bool isSigned, bool Inside, 
3670                                            Instruction &IB) {
3671   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3672             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3673          "Lo is not <= Hi in range emission code!");
3674     
3675   if (Inside) {
3676     if (Lo == Hi)  // Trivially false.
3677       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3678
3679     // V >= Min && V < Hi --> V < Hi
3680     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3681       ICmpInst::Predicate pred = (isSigned ? 
3682         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3683       return new ICmpInst(*Context, pred, V, Hi);
3684     }
3685
3686     // Emit V-Lo <u Hi-Lo
3687     Constant *NegLo = Context->getConstantExprNeg(Lo);
3688     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3689     InsertNewInstBefore(Add, IB);
3690     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3691     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3692   }
3693
3694   if (Lo == Hi)  // Trivially true.
3695     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3696
3697   // V < Min || V >= Hi -> V > Hi-1
3698   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3699   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3700     ICmpInst::Predicate pred = (isSigned ? 
3701         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3702     return new ICmpInst(*Context, pred, V, Hi);
3703   }
3704
3705   // Emit V-Lo >u Hi-1-Lo
3706   // Note that Hi has already had one subtracted from it, above.
3707   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3708   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3709   InsertNewInstBefore(Add, IB);
3710   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3711   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3712 }
3713
3714 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3715 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3716 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3717 // not, since all 1s are not contiguous.
3718 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3719   const APInt& V = Val->getValue();
3720   uint32_t BitWidth = Val->getType()->getBitWidth();
3721   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3722
3723   // look for the first zero bit after the run of ones
3724   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3725   // look for the first non-zero bit
3726   ME = V.getActiveBits(); 
3727   return true;
3728 }
3729
3730 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3731 /// where isSub determines whether the operator is a sub.  If we can fold one of
3732 /// the following xforms:
3733 /// 
3734 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3735 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3736 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3737 ///
3738 /// return (A +/- B).
3739 ///
3740 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3741                                         ConstantInt *Mask, bool isSub,
3742                                         Instruction &I) {
3743   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3744   if (!LHSI || LHSI->getNumOperands() != 2 ||
3745       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3746
3747   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3748
3749   switch (LHSI->getOpcode()) {
3750   default: return 0;
3751   case Instruction::And:
3752     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3753       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3754       if ((Mask->getValue().countLeadingZeros() + 
3755            Mask->getValue().countPopulation()) == 
3756           Mask->getValue().getBitWidth())
3757         break;
3758
3759       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3760       // part, we don't need any explicit masks to take them out of A.  If that
3761       // is all N is, ignore it.
3762       uint32_t MB = 0, ME = 0;
3763       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3764         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3765         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3766         if (MaskedValueIsZero(RHS, Mask))
3767           break;
3768       }
3769     }
3770     return 0;
3771   case Instruction::Or:
3772   case Instruction::Xor:
3773     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3774     if ((Mask->getValue().countLeadingZeros() + 
3775          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3776         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3777       break;
3778     return 0;
3779   }
3780   
3781   Instruction *New;
3782   if (isSub)
3783     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3784   else
3785     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3786   return InsertNewInstBefore(New, I);
3787 }
3788
3789 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3790 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3791                                           ICmpInst *LHS, ICmpInst *RHS) {
3792   Value *Val, *Val2;
3793   ConstantInt *LHSCst, *RHSCst;
3794   ICmpInst::Predicate LHSCC, RHSCC;
3795   
3796   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3797   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3798                          m_ConstantInt(LHSCst)), *Context) ||
3799       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3800                          m_ConstantInt(RHSCst)), *Context))
3801     return 0;
3802   
3803   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3804   // where C is a power of 2
3805   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3806       LHSCst->getValue().isPowerOf2()) {
3807     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3808     InsertNewInstBefore(NewOr, I);
3809     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3810   }
3811   
3812   // From here on, we only handle:
3813   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3814   if (Val != Val2) return 0;
3815   
3816   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3817   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3818       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3819       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3820       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3821     return 0;
3822   
3823   // We can't fold (ugt x, C) & (sgt x, C2).
3824   if (!PredicatesFoldable(LHSCC, RHSCC))
3825     return 0;
3826     
3827   // Ensure that the larger constant is on the RHS.
3828   bool ShouldSwap;
3829   if (ICmpInst::isSignedPredicate(LHSCC) ||
3830       (ICmpInst::isEquality(LHSCC) && 
3831        ICmpInst::isSignedPredicate(RHSCC)))
3832     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3833   else
3834     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3835     
3836   if (ShouldSwap) {
3837     std::swap(LHS, RHS);
3838     std::swap(LHSCst, RHSCst);
3839     std::swap(LHSCC, RHSCC);
3840   }
3841
3842   // At this point, we know we have have two icmp instructions
3843   // comparing a value against two constants and and'ing the result
3844   // together.  Because of the above check, we know that we only have
3845   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3846   // (from the FoldICmpLogical check above), that the two constants 
3847   // are not equal and that the larger constant is on the RHS
3848   assert(LHSCst != RHSCst && "Compares not folded above?");
3849
3850   switch (LHSCC) {
3851   default: llvm_unreachable("Unknown integer condition code!");
3852   case ICmpInst::ICMP_EQ:
3853     switch (RHSCC) {
3854     default: llvm_unreachable("Unknown integer condition code!");
3855     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3856     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3857     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3858       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3859     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3860     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3861     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3862       return ReplaceInstUsesWith(I, LHS);
3863     }
3864   case ICmpInst::ICMP_NE:
3865     switch (RHSCC) {
3866     default: llvm_unreachable("Unknown integer condition code!");
3867     case ICmpInst::ICMP_ULT:
3868       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3869         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3870       break;                        // (X != 13 & X u< 15) -> no change
3871     case ICmpInst::ICMP_SLT:
3872       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3873         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3874       break;                        // (X != 13 & X s< 15) -> no change
3875     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3876     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3877     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3878       return ReplaceInstUsesWith(I, RHS);
3879     case ICmpInst::ICMP_NE:
3880       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3881         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3882         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3883                                                      Val->getName()+".off");
3884         InsertNewInstBefore(Add, I);
3885         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3886                             Context->getConstantInt(Add->getType(), 1));
3887       }
3888       break;                        // (X != 13 & X != 15) -> no change
3889     }
3890     break;
3891   case ICmpInst::ICMP_ULT:
3892     switch (RHSCC) {
3893     default: llvm_unreachable("Unknown integer condition code!");
3894     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3895     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3896       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3897     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3898       break;
3899     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3900     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3901       return ReplaceInstUsesWith(I, LHS);
3902     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3903       break;
3904     }
3905     break;
3906   case ICmpInst::ICMP_SLT:
3907     switch (RHSCC) {
3908     default: llvm_unreachable("Unknown integer condition code!");
3909     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3910     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3911       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3912     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3913       break;
3914     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3915     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3916       return ReplaceInstUsesWith(I, LHS);
3917     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3918       break;
3919     }
3920     break;
3921   case ICmpInst::ICMP_UGT:
3922     switch (RHSCC) {
3923     default: llvm_unreachable("Unknown integer condition code!");
3924     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3925     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3926       return ReplaceInstUsesWith(I, RHS);
3927     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3928       break;
3929     case ICmpInst::ICMP_NE:
3930       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3931         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3932       break;                        // (X u> 13 & X != 15) -> no change
3933     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3934       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3935                              RHSCst, false, true, I);
3936     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3937       break;
3938     }
3939     break;
3940   case ICmpInst::ICMP_SGT:
3941     switch (RHSCC) {
3942     default: llvm_unreachable("Unknown integer condition code!");
3943     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3944     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3945       return ReplaceInstUsesWith(I, RHS);
3946     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3947       break;
3948     case ICmpInst::ICMP_NE:
3949       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3950         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3951       break;                        // (X s> 13 & X != 15) -> no change
3952     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3953       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3954                              RHSCst, true, true, I);
3955     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3956       break;
3957     }
3958     break;
3959   }
3960  
3961   return 0;
3962 }
3963
3964
3965 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3966   bool Changed = SimplifyCommutative(I);
3967   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3968
3969   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3970     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3971
3972   // and X, X = X
3973   if (Op0 == Op1)
3974     return ReplaceInstUsesWith(I, Op1);
3975
3976   // See if we can simplify any instructions used by the instruction whose sole 
3977   // purpose is to compute bits we don't care about.
3978   if (SimplifyDemandedInstructionBits(I))
3979     return &I;
3980   if (isa<VectorType>(I.getType())) {
3981     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3982       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3983         return ReplaceInstUsesWith(I, I.getOperand(0));
3984     } else if (isa<ConstantAggregateZero>(Op1)) {
3985       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3986     }
3987   }
3988
3989   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3990     const APInt& AndRHSMask = AndRHS->getValue();
3991     APInt NotAndRHS(~AndRHSMask);
3992
3993     // Optimize a variety of ((val OP C1) & C2) combinations...
3994     if (isa<BinaryOperator>(Op0)) {
3995       Instruction *Op0I = cast<Instruction>(Op0);
3996       Value *Op0LHS = Op0I->getOperand(0);
3997       Value *Op0RHS = Op0I->getOperand(1);
3998       switch (Op0I->getOpcode()) {
3999       case Instruction::Xor:
4000       case Instruction::Or:
4001         // If the mask is only needed on one incoming arm, push it up.
4002         if (Op0I->hasOneUse()) {
4003           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4004             // Not masking anything out for the LHS, move to RHS.
4005             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4006                                                    Op0RHS->getName()+".masked");
4007             InsertNewInstBefore(NewRHS, I);
4008             return BinaryOperator::Create(
4009                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4010           }
4011           if (!isa<Constant>(Op0RHS) &&
4012               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4013             // Not masking anything out for the RHS, move to LHS.
4014             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4015                                                    Op0LHS->getName()+".masked");
4016             InsertNewInstBefore(NewLHS, I);
4017             return BinaryOperator::Create(
4018                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4019           }
4020         }
4021
4022         break;
4023       case Instruction::Add:
4024         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4025         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4026         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4027         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4028           return BinaryOperator::CreateAnd(V, AndRHS);
4029         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4030           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4031         break;
4032
4033       case Instruction::Sub:
4034         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4035         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4036         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4037         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4038           return BinaryOperator::CreateAnd(V, AndRHS);
4039
4040         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4041         // has 1's for all bits that the subtraction with A might affect.
4042         if (Op0I->hasOneUse()) {
4043           uint32_t BitWidth = AndRHSMask.getBitWidth();
4044           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4045           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4046
4047           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4048           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4049               MaskedValueIsZero(Op0LHS, Mask)) {
4050             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4051             InsertNewInstBefore(NewNeg, I);
4052             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4053           }
4054         }
4055         break;
4056
4057       case Instruction::Shl:
4058       case Instruction::LShr:
4059         // (1 << x) & 1 --> zext(x == 0)
4060         // (1 >> x) & 1 --> zext(x == 0)
4061         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4062           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4063                                     Op0RHS, Context->getNullValue(I.getType()));
4064           InsertNewInstBefore(NewICmp, I);
4065           return new ZExtInst(NewICmp, I.getType());
4066         }
4067         break;
4068       }
4069
4070       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4071         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4072           return Res;
4073     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4074       // If this is an integer truncation or change from signed-to-unsigned, and
4075       // if the source is an and/or with immediate, transform it.  This
4076       // frequently occurs for bitfield accesses.
4077       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4078         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4079             CastOp->getNumOperands() == 2)
4080           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4081             if (CastOp->getOpcode() == Instruction::And) {
4082               // Change: and (cast (and X, C1) to T), C2
4083               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4084               // This will fold the two constants together, which may allow 
4085               // other simplifications.
4086               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4087                 CastOp->getOperand(0), I.getType(), 
4088                 CastOp->getName()+".shrunk");
4089               NewCast = InsertNewInstBefore(NewCast, I);
4090               // trunc_or_bitcast(C1)&C2
4091               Constant *C3 =
4092                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4093               C3 = Context->getConstantExprAnd(C3, AndRHS);
4094               return BinaryOperator::CreateAnd(NewCast, C3);
4095             } else if (CastOp->getOpcode() == Instruction::Or) {
4096               // Change: and (cast (or X, C1) to T), C2
4097               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4098               Constant *C3 =
4099                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4100               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4101                 // trunc(C1)&C2
4102                 return ReplaceInstUsesWith(I, AndRHS);
4103             }
4104           }
4105       }
4106     }
4107
4108     // Try to fold constant and into select arguments.
4109     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4110       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4111         return R;
4112     if (isa<PHINode>(Op0))
4113       if (Instruction *NV = FoldOpIntoPhi(I))
4114         return NV;
4115   }
4116
4117   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4118   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4119
4120   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4121     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4122
4123   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4124   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4125     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4126                                                I.getName()+".demorgan");
4127     InsertNewInstBefore(Or, I);
4128     return BinaryOperator::CreateNot(*Context, Or);
4129   }
4130   
4131   {
4132     Value *A = 0, *B = 0, *C = 0, *D = 0;
4133     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4134       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4135         return ReplaceInstUsesWith(I, Op1);
4136     
4137       // (A|B) & ~(A&B) -> A^B
4138       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4139         if ((A == C && B == D) || (A == D && B == C))
4140           return BinaryOperator::CreateXor(A, B);
4141       }
4142     }
4143     
4144     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4145       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4146         return ReplaceInstUsesWith(I, Op0);
4147
4148       // ~(A&B) & (A|B) -> A^B
4149       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4150         if ((A == C && B == D) || (A == D && B == C))
4151           return BinaryOperator::CreateXor(A, B);
4152       }
4153     }
4154     
4155     if (Op0->hasOneUse() &&
4156         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4157       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4158         I.swapOperands();     // Simplify below
4159         std::swap(Op0, Op1);
4160       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4161         cast<BinaryOperator>(Op0)->swapOperands();
4162         I.swapOperands();     // Simplify below
4163         std::swap(Op0, Op1);
4164       }
4165     }
4166
4167     if (Op1->hasOneUse() &&
4168         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4169       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4170         cast<BinaryOperator>(Op1)->swapOperands();
4171         std::swap(A, B);
4172       }
4173       if (A == Op0) {                                // A&(A^B) -> A & ~B
4174         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4175         InsertNewInstBefore(NotB, I);
4176         return BinaryOperator::CreateAnd(A, NotB);
4177       }
4178     }
4179
4180     // (A&((~A)|B)) -> A&B
4181     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4182         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4183       return BinaryOperator::CreateAnd(A, Op1);
4184     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4185         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4186       return BinaryOperator::CreateAnd(A, Op0);
4187   }
4188   
4189   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4190     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4191     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4192       return R;
4193
4194     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4195       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4196         return Res;
4197   }
4198
4199   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4200   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4201     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4202       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4203         const Type *SrcTy = Op0C->getOperand(0)->getType();
4204         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4205             // Only do this if the casts both really cause code to be generated.
4206             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4207                               I.getType(), TD) &&
4208             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4209                               I.getType(), TD)) {
4210           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4211                                                          Op1C->getOperand(0),
4212                                                          I.getName());
4213           InsertNewInstBefore(NewOp, I);
4214           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4215         }
4216       }
4217     
4218   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4219   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4220     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4221       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4222           SI0->getOperand(1) == SI1->getOperand(1) &&
4223           (SI0->hasOneUse() || SI1->hasOneUse())) {
4224         Instruction *NewOp =
4225           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4226                                                         SI1->getOperand(0),
4227                                                         SI0->getName()), I);
4228         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4229                                       SI1->getOperand(1));
4230       }
4231   }
4232
4233   // If and'ing two fcmp, try combine them into one.
4234   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4235     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4236       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4237           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4238         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4239         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4240           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4241             // If either of the constants are nans, then the whole thing returns
4242             // false.
4243             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4244               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4245             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4246                                 LHS->getOperand(0), RHS->getOperand(0));
4247           }
4248       } else {
4249         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4250         FCmpInst::Predicate Op0CC, Op1CC;
4251         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4252                   m_Value(Op0RHS)), *Context) &&
4253             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4254                   m_Value(Op1RHS)), *Context)) {
4255           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4256             // Swap RHS operands to match LHS.
4257             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4258             std::swap(Op1LHS, Op1RHS);
4259           }
4260           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4261             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4262             if (Op0CC == Op1CC)
4263               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4264                                   Op0LHS, Op0RHS);
4265             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4266                      Op1CC == FCmpInst::FCMP_FALSE)
4267               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4268             else if (Op0CC == FCmpInst::FCMP_TRUE)
4269               return ReplaceInstUsesWith(I, Op1);
4270             else if (Op1CC == FCmpInst::FCMP_TRUE)
4271               return ReplaceInstUsesWith(I, Op0);
4272             bool Op0Ordered;
4273             bool Op1Ordered;
4274             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4275             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4276             if (Op1Pred == 0) {
4277               std::swap(Op0, Op1);
4278               std::swap(Op0Pred, Op1Pred);
4279               std::swap(Op0Ordered, Op1Ordered);
4280             }
4281             if (Op0Pred == 0) {
4282               // uno && ueq -> uno && (uno || eq) -> ueq
4283               // ord && olt -> ord && (ord && lt) -> olt
4284               if (Op0Ordered == Op1Ordered)
4285                 return ReplaceInstUsesWith(I, Op1);
4286               // uno && oeq -> uno && (ord && eq) -> false
4287               // uno && ord -> false
4288               if (!Op0Ordered)
4289                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4290               // ord && ueq -> ord && (uno || eq) -> oeq
4291               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4292                                                     Op0LHS, Op0RHS, Context));
4293             }
4294           }
4295         }
4296       }
4297     }
4298   }
4299
4300   return Changed ? &I : 0;
4301 }
4302
4303 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4304 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4305 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4306 /// the expression came from the corresponding "byte swapped" byte in some other
4307 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4308 /// we know that the expression deposits the low byte of %X into the high byte
4309 /// of the bswap result and that all other bytes are zero.  This expression is
4310 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4311 /// match.
4312 ///
4313 /// This function returns true if the match was unsuccessful and false if so.
4314 /// On entry to the function the "OverallLeftShift" is a signed integer value
4315 /// indicating the number of bytes that the subexpression is later shifted.  For
4316 /// example, if the expression is later right shifted by 16 bits, the
4317 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4318 /// byte of ByteValues is actually being set.
4319 ///
4320 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4321 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4322 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4323 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4324 /// always in the local (OverallLeftShift) coordinate space.
4325 ///
4326 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4327                               SmallVector<Value*, 8> &ByteValues) {
4328   if (Instruction *I = dyn_cast<Instruction>(V)) {
4329     // If this is an or instruction, it may be an inner node of the bswap.
4330     if (I->getOpcode() == Instruction::Or) {
4331       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4332                                ByteValues) ||
4333              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4334                                ByteValues);
4335     }
4336   
4337     // If this is a logical shift by a constant multiple of 8, recurse with
4338     // OverallLeftShift and ByteMask adjusted.
4339     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4340       unsigned ShAmt = 
4341         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4342       // Ensure the shift amount is defined and of a byte value.
4343       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4344         return true;
4345
4346       unsigned ByteShift = ShAmt >> 3;
4347       if (I->getOpcode() == Instruction::Shl) {
4348         // X << 2 -> collect(X, +2)
4349         OverallLeftShift += ByteShift;
4350         ByteMask >>= ByteShift;
4351       } else {
4352         // X >>u 2 -> collect(X, -2)
4353         OverallLeftShift -= ByteShift;
4354         ByteMask <<= ByteShift;
4355         ByteMask &= (~0U >> (32-ByteValues.size()));
4356       }
4357
4358       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4359       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4360
4361       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4362                                ByteValues);
4363     }
4364
4365     // If this is a logical 'and' with a mask that clears bytes, clear the
4366     // corresponding bytes in ByteMask.
4367     if (I->getOpcode() == Instruction::And &&
4368         isa<ConstantInt>(I->getOperand(1))) {
4369       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4370       unsigned NumBytes = ByteValues.size();
4371       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4372       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4373       
4374       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4375         // If this byte is masked out by a later operation, we don't care what
4376         // the and mask is.
4377         if ((ByteMask & (1 << i)) == 0)
4378           continue;
4379         
4380         // If the AndMask is all zeros for this byte, clear the bit.
4381         APInt MaskB = AndMask & Byte;
4382         if (MaskB == 0) {
4383           ByteMask &= ~(1U << i);
4384           continue;
4385         }
4386         
4387         // If the AndMask is not all ones for this byte, it's not a bytezap.
4388         if (MaskB != Byte)
4389           return true;
4390
4391         // Otherwise, this byte is kept.
4392       }
4393
4394       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4395                                ByteValues);
4396     }
4397   }
4398   
4399   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4400   // the input value to the bswap.  Some observations: 1) if more than one byte
4401   // is demanded from this input, then it could not be successfully assembled
4402   // into a byteswap.  At least one of the two bytes would not be aligned with
4403   // their ultimate destination.
4404   if (!isPowerOf2_32(ByteMask)) return true;
4405   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4406   
4407   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4408   // is demanded, it needs to go into byte 0 of the result.  This means that the
4409   // byte needs to be shifted until it lands in the right byte bucket.  The
4410   // shift amount depends on the position: if the byte is coming from the high
4411   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4412   // low part, it must be shifted left.
4413   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4414   if (InputByteNo < ByteValues.size()/2) {
4415     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4416       return true;
4417   } else {
4418     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419       return true;
4420   }
4421   
4422   // If the destination byte value is already defined, the values are or'd
4423   // together, which isn't a bswap (unless it's an or of the same bits).
4424   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4425     return true;
4426   ByteValues[DestByteNo] = V;
4427   return false;
4428 }
4429
4430 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4431 /// If so, insert the new bswap intrinsic and return it.
4432 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4433   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4434   if (!ITy || ITy->getBitWidth() % 16 || 
4435       // ByteMask only allows up to 32-byte values.
4436       ITy->getBitWidth() > 32*8) 
4437     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4438   
4439   /// ByteValues - For each byte of the result, we keep track of which value
4440   /// defines each byte.
4441   SmallVector<Value*, 8> ByteValues;
4442   ByteValues.resize(ITy->getBitWidth()/8);
4443     
4444   // Try to find all the pieces corresponding to the bswap.
4445   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4446   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4447     return 0;
4448   
4449   // Check to see if all of the bytes come from the same value.
4450   Value *V = ByteValues[0];
4451   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4452   
4453   // Check to make sure that all of the bytes come from the same value.
4454   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4455     if (ByteValues[i] != V)
4456       return 0;
4457   const Type *Tys[] = { ITy };
4458   Module *M = I.getParent()->getParent()->getParent();
4459   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4460   return CallInst::Create(F, V);
4461 }
4462
4463 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4464 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4465 /// we can simplify this expression to "cond ? C : D or B".
4466 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4467                                          Value *C, Value *D,
4468                                          LLVMContext *Context) {
4469   // If A is not a select of -1/0, this cannot match.
4470   Value *Cond = 0;
4471   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4472     return 0;
4473
4474   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4475   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4476     return SelectInst::Create(Cond, C, B);
4477   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4478     return SelectInst::Create(Cond, C, B);
4479   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4480   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4481     return SelectInst::Create(Cond, C, D);
4482   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4483     return SelectInst::Create(Cond, C, D);
4484   return 0;
4485 }
4486
4487 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4488 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4489                                          ICmpInst *LHS, ICmpInst *RHS) {
4490   Value *Val, *Val2;
4491   ConstantInt *LHSCst, *RHSCst;
4492   ICmpInst::Predicate LHSCC, RHSCC;
4493   
4494   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4495   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4496              m_ConstantInt(LHSCst)), *Context) ||
4497       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4498              m_ConstantInt(RHSCst)), *Context))
4499     return 0;
4500   
4501   // From here on, we only handle:
4502   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4503   if (Val != Val2) return 0;
4504   
4505   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4506   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4507       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4508       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4509       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4510     return 0;
4511   
4512   // We can't fold (ugt x, C) | (sgt x, C2).
4513   if (!PredicatesFoldable(LHSCC, RHSCC))
4514     return 0;
4515   
4516   // Ensure that the larger constant is on the RHS.
4517   bool ShouldSwap;
4518   if (ICmpInst::isSignedPredicate(LHSCC) ||
4519       (ICmpInst::isEquality(LHSCC) && 
4520        ICmpInst::isSignedPredicate(RHSCC)))
4521     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4522   else
4523     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4524   
4525   if (ShouldSwap) {
4526     std::swap(LHS, RHS);
4527     std::swap(LHSCst, RHSCst);
4528     std::swap(LHSCC, RHSCC);
4529   }
4530   
4531   // At this point, we know we have have two icmp instructions
4532   // comparing a value against two constants and or'ing the result
4533   // together.  Because of the above check, we know that we only have
4534   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4535   // FoldICmpLogical check above), that the two constants are not
4536   // equal.
4537   assert(LHSCst != RHSCst && "Compares not folded above?");
4538
4539   switch (LHSCC) {
4540   default: llvm_unreachable("Unknown integer condition code!");
4541   case ICmpInst::ICMP_EQ:
4542     switch (RHSCC) {
4543     default: llvm_unreachable("Unknown integer condition code!");
4544     case ICmpInst::ICMP_EQ:
4545       if (LHSCst == SubOne(RHSCst, Context)) {
4546         // (X == 13 | X == 14) -> X-13 <u 2
4547         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4548         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4549                                                      Val->getName()+".off");
4550         InsertNewInstBefore(Add, I);
4551         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4552         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4553       }
4554       break;                         // (X == 13 | X == 15) -> no change
4555     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4556     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4557       break;
4558     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4559     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4560     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4561       return ReplaceInstUsesWith(I, RHS);
4562     }
4563     break;
4564   case ICmpInst::ICMP_NE:
4565     switch (RHSCC) {
4566     default: llvm_unreachable("Unknown integer condition code!");
4567     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4568     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4569     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4570       return ReplaceInstUsesWith(I, LHS);
4571     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4572     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4573     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4574       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4575     }
4576     break;
4577   case ICmpInst::ICMP_ULT:
4578     switch (RHSCC) {
4579     default: llvm_unreachable("Unknown integer condition code!");
4580     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4581       break;
4582     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4583       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4584       // this can cause overflow.
4585       if (RHSCst->isMaxValue(false))
4586         return ReplaceInstUsesWith(I, LHS);
4587       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4588                              false, false, I);
4589     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4590       break;
4591     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4592     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4593       return ReplaceInstUsesWith(I, RHS);
4594     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4595       break;
4596     }
4597     break;
4598   case ICmpInst::ICMP_SLT:
4599     switch (RHSCC) {
4600     default: llvm_unreachable("Unknown integer condition code!");
4601     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4602       break;
4603     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4604       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4605       // this can cause overflow.
4606       if (RHSCst->isMaxValue(true))
4607         return ReplaceInstUsesWith(I, LHS);
4608       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4609                              true, false, I);
4610     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4611       break;
4612     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4613     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4614       return ReplaceInstUsesWith(I, RHS);
4615     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4616       break;
4617     }
4618     break;
4619   case ICmpInst::ICMP_UGT:
4620     switch (RHSCC) {
4621     default: llvm_unreachable("Unknown integer condition code!");
4622     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4623     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4624       return ReplaceInstUsesWith(I, LHS);
4625     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4626       break;
4627     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4628     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4629       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4630     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4631       break;
4632     }
4633     break;
4634   case ICmpInst::ICMP_SGT:
4635     switch (RHSCC) {
4636     default: llvm_unreachable("Unknown integer condition code!");
4637     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4638     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4639       return ReplaceInstUsesWith(I, LHS);
4640     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4641       break;
4642     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4643     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4644       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4645     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4646       break;
4647     }
4648     break;
4649   }
4650   return 0;
4651 }
4652
4653 /// FoldOrWithConstants - This helper function folds:
4654 ///
4655 ///     ((A | B) & C1) | (B & C2)
4656 ///
4657 /// into:
4658 /// 
4659 ///     (A & C1) | B
4660 ///
4661 /// when the XOR of the two constants is "all ones" (-1).
4662 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4663                                                Value *A, Value *B, Value *C) {
4664   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4665   if (!CI1) return 0;
4666
4667   Value *V1 = 0;
4668   ConstantInt *CI2 = 0;
4669   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4670
4671   APInt Xor = CI1->getValue() ^ CI2->getValue();
4672   if (!Xor.isAllOnesValue()) return 0;
4673
4674   if (V1 == A || V1 == B) {
4675     Instruction *NewOp =
4676       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4677     return BinaryOperator::CreateOr(NewOp, V1);
4678   }
4679
4680   return 0;
4681 }
4682
4683 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4684   bool Changed = SimplifyCommutative(I);
4685   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4686
4687   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4688     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4689
4690   // or X, X = X
4691   if (Op0 == Op1)
4692     return ReplaceInstUsesWith(I, Op0);
4693
4694   // See if we can simplify any instructions used by the instruction whose sole 
4695   // purpose is to compute bits we don't care about.
4696   if (SimplifyDemandedInstructionBits(I))
4697     return &I;
4698   if (isa<VectorType>(I.getType())) {
4699     if (isa<ConstantAggregateZero>(Op1)) {
4700       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4701     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4702       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4703         return ReplaceInstUsesWith(I, I.getOperand(1));
4704     }
4705   }
4706
4707   // or X, -1 == -1
4708   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4709     ConstantInt *C1 = 0; Value *X = 0;
4710     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4711     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4712         isOnlyUse(Op0)) {
4713       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4714       InsertNewInstBefore(Or, I);
4715       Or->takeName(Op0);
4716       return BinaryOperator::CreateAnd(Or, 
4717                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4718     }
4719
4720     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4721     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4722         isOnlyUse(Op0)) {
4723       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4724       InsertNewInstBefore(Or, I);
4725       Or->takeName(Op0);
4726       return BinaryOperator::CreateXor(Or,
4727                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4728     }
4729
4730     // Try to fold constant and into select arguments.
4731     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4732       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4733         return R;
4734     if (isa<PHINode>(Op0))
4735       if (Instruction *NV = FoldOpIntoPhi(I))
4736         return NV;
4737   }
4738
4739   Value *A = 0, *B = 0;
4740   ConstantInt *C1 = 0, *C2 = 0;
4741
4742   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4743     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4744       return ReplaceInstUsesWith(I, Op1);
4745   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4746     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4747       return ReplaceInstUsesWith(I, Op0);
4748
4749   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4750   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4751   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4752       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4753       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4754        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4755     if (Instruction *BSwap = MatchBSwap(I))
4756       return BSwap;
4757   }
4758   
4759   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4760   if (Op0->hasOneUse() &&
4761       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4762       MaskedValueIsZero(Op1, C1->getValue())) {
4763     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4764     InsertNewInstBefore(NOr, I);
4765     NOr->takeName(Op0);
4766     return BinaryOperator::CreateXor(NOr, C1);
4767   }
4768
4769   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4770   if (Op1->hasOneUse() &&
4771       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4772       MaskedValueIsZero(Op0, C1->getValue())) {
4773     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4774     InsertNewInstBefore(NOr, I);
4775     NOr->takeName(Op0);
4776     return BinaryOperator::CreateXor(NOr, C1);
4777   }
4778
4779   // (A & C)|(B & D)
4780   Value *C = 0, *D = 0;
4781   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4782       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4783     Value *V1 = 0, *V2 = 0, *V3 = 0;
4784     C1 = dyn_cast<ConstantInt>(C);
4785     C2 = dyn_cast<ConstantInt>(D);
4786     if (C1 && C2) {  // (A & C1)|(B & C2)
4787       // If we have: ((V + N) & C1) | (V & C2)
4788       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4789       // replace with V+N.
4790       if (C1->getValue() == ~C2->getValue()) {
4791         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4792             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4793           // Add commutes, try both ways.
4794           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4795             return ReplaceInstUsesWith(I, A);
4796           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4797             return ReplaceInstUsesWith(I, A);
4798         }
4799         // Or commutes, try both ways.
4800         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4801             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4802           // Add commutes, try both ways.
4803           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4804             return ReplaceInstUsesWith(I, B);
4805           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4806             return ReplaceInstUsesWith(I, B);
4807         }
4808       }
4809       V1 = 0; V2 = 0; V3 = 0;
4810     }
4811     
4812     // Check to see if we have any common things being and'ed.  If so, find the
4813     // terms for V1 & (V2|V3).
4814     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4815       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4816         V1 = A, V2 = C, V3 = D;
4817       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4818         V1 = A, V2 = B, V3 = C;
4819       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4820         V1 = C, V2 = A, V3 = D;
4821       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4822         V1 = C, V2 = A, V3 = B;
4823       
4824       if (V1) {
4825         Value *Or =
4826           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4827         return BinaryOperator::CreateAnd(V1, Or);
4828       }
4829     }
4830
4831     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4832     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4833       return Match;
4834     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4835       return Match;
4836     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4837       return Match;
4838     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4839       return Match;
4840
4841     // ((A&~B)|(~A&B)) -> A^B
4842     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4843          match(B, m_Not(m_Specific(A)), *Context)))
4844       return BinaryOperator::CreateXor(A, D);
4845     // ((~B&A)|(~A&B)) -> A^B
4846     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4847          match(B, m_Not(m_Specific(C)), *Context)))
4848       return BinaryOperator::CreateXor(C, D);
4849     // ((A&~B)|(B&~A)) -> A^B
4850     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4851          match(D, m_Not(m_Specific(A)), *Context)))
4852       return BinaryOperator::CreateXor(A, B);
4853     // ((~B&A)|(B&~A)) -> A^B
4854     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4855          match(D, m_Not(m_Specific(C)), *Context)))
4856       return BinaryOperator::CreateXor(C, B);
4857   }
4858   
4859   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4860   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4861     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4862       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4863           SI0->getOperand(1) == SI1->getOperand(1) &&
4864           (SI0->hasOneUse() || SI1->hasOneUse())) {
4865         Instruction *NewOp =
4866         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4867                                                      SI1->getOperand(0),
4868                                                      SI0->getName()), I);
4869         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4870                                       SI1->getOperand(1));
4871       }
4872   }
4873
4874   // ((A|B)&1)|(B&-2) -> (A&1) | B
4875   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4876       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4877     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4878     if (Ret) return Ret;
4879   }
4880   // (B&-2)|((A|B)&1) -> (A&1) | B
4881   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4882       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4883     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4884     if (Ret) return Ret;
4885   }
4886
4887   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4888     if (A == Op1)   // ~A | A == -1
4889       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4890   } else {
4891     A = 0;
4892   }
4893   // Note, A is still live here!
4894   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4895     if (Op0 == B)
4896       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4897
4898     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4899     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4900       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4901                                               I.getName()+".demorgan"), I);
4902       return BinaryOperator::CreateNot(*Context, And);
4903     }
4904   }
4905
4906   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4907   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4908     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4909       return R;
4910
4911     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4912       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4913         return Res;
4914   }
4915     
4916   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4917   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4918     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4919       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4920         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4921             !isa<ICmpInst>(Op1C->getOperand(0))) {
4922           const Type *SrcTy = Op0C->getOperand(0)->getType();
4923           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4924               // Only do this if the casts both really cause code to be
4925               // generated.
4926               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4927                                 I.getType(), TD) &&
4928               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4929                                 I.getType(), TD)) {
4930             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4931                                                           Op1C->getOperand(0),
4932                                                           I.getName());
4933             InsertNewInstBefore(NewOp, I);
4934             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4935           }
4936         }
4937       }
4938   }
4939   
4940     
4941   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4942   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4943     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4944       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4945           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4946           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4947         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4948           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4949             // If either of the constants are nans, then the whole thing returns
4950             // true.
4951             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4952               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4953             
4954             // Otherwise, no need to compare the two constants, compare the
4955             // rest.
4956             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4957                                 LHS->getOperand(0), RHS->getOperand(0));
4958           }
4959       } else {
4960         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4961         FCmpInst::Predicate Op0CC, Op1CC;
4962         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4963                   m_Value(Op0RHS)), *Context) &&
4964             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4965                   m_Value(Op1RHS)), *Context)) {
4966           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4967             // Swap RHS operands to match LHS.
4968             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4969             std::swap(Op1LHS, Op1RHS);
4970           }
4971           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4972             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4973             if (Op0CC == Op1CC)
4974               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4975                                   Op0LHS, Op0RHS);
4976             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4977                      Op1CC == FCmpInst::FCMP_TRUE)
4978               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4979             else if (Op0CC == FCmpInst::FCMP_FALSE)
4980               return ReplaceInstUsesWith(I, Op1);
4981             else if (Op1CC == FCmpInst::FCMP_FALSE)
4982               return ReplaceInstUsesWith(I, Op0);
4983             bool Op0Ordered;
4984             bool Op1Ordered;
4985             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4986             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4987             if (Op0Ordered == Op1Ordered) {
4988               // If both are ordered or unordered, return a new fcmp with
4989               // or'ed predicates.
4990               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4991                                        Op0LHS, Op0RHS, Context);
4992               if (Instruction *I = dyn_cast<Instruction>(RV))
4993                 return I;
4994               // Otherwise, it's a constant boolean value...
4995               return ReplaceInstUsesWith(I, RV);
4996             }
4997           }
4998         }
4999       }
5000     }
5001   }
5002
5003   return Changed ? &I : 0;
5004 }
5005
5006 namespace {
5007
5008 // XorSelf - Implements: X ^ X --> 0
5009 struct XorSelf {
5010   Value *RHS;
5011   XorSelf(Value *rhs) : RHS(rhs) {}
5012   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5013   Instruction *apply(BinaryOperator &Xor) const {
5014     return &Xor;
5015   }
5016 };
5017
5018 }
5019
5020 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5021   bool Changed = SimplifyCommutative(I);
5022   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5023
5024   if (isa<UndefValue>(Op1)) {
5025     if (isa<UndefValue>(Op0))
5026       // Handle undef ^ undef -> 0 special case. This is a common
5027       // idiom (misuse).
5028       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5029     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5030   }
5031
5032   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5033   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5034     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5035     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5036   }
5037   
5038   // See if we can simplify any instructions used by the instruction whose sole 
5039   // purpose is to compute bits we don't care about.
5040   if (SimplifyDemandedInstructionBits(I))
5041     return &I;
5042   if (isa<VectorType>(I.getType()))
5043     if (isa<ConstantAggregateZero>(Op1))
5044       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5045
5046   // Is this a ~ operation?
5047   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5048     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5049     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5050     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5051       if (Op0I->getOpcode() == Instruction::And || 
5052           Op0I->getOpcode() == Instruction::Or) {
5053         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5054         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5055           Instruction *NotY =
5056             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5057                                       Op0I->getOperand(1)->getName()+".not");
5058           InsertNewInstBefore(NotY, I);
5059           if (Op0I->getOpcode() == Instruction::And)
5060             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5061           else
5062             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5063         }
5064       }
5065     }
5066   }
5067   
5068   
5069   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5070     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5071       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5072       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5073         return new ICmpInst(*Context, ICI->getInversePredicate(),
5074                             ICI->getOperand(0), ICI->getOperand(1));
5075
5076       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5077         return new FCmpInst(*Context, FCI->getInversePredicate(),
5078                             FCI->getOperand(0), FCI->getOperand(1));
5079     }
5080
5081     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5082     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5083       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5084         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5085           Instruction::CastOps Opcode = Op0C->getOpcode();
5086           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5087             if (RHS == Context->getConstantExprCast(Opcode, 
5088                                              Context->getConstantIntTrue(),
5089                                              Op0C->getDestTy())) {
5090               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5091                                      *Context,
5092                                      CI->getOpcode(), CI->getInversePredicate(),
5093                                      CI->getOperand(0), CI->getOperand(1)), I);
5094               NewCI->takeName(CI);
5095               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5096             }
5097           }
5098         }
5099       }
5100     }
5101
5102     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5103       // ~(c-X) == X-c-1 == X+(-c-1)
5104       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5105         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5106           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5107           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5108                                       Context->getConstantInt(I.getType(), 1));
5109           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5110         }
5111           
5112       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5113         if (Op0I->getOpcode() == Instruction::Add) {
5114           // ~(X-c) --> (-c-1)-X
5115           if (RHS->isAllOnesValue()) {
5116             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5117             return BinaryOperator::CreateSub(
5118                            Context->getConstantExprSub(NegOp0CI,
5119                                       Context->getConstantInt(I.getType(), 1)),
5120                                       Op0I->getOperand(0));
5121           } else if (RHS->getValue().isSignBit()) {
5122             // (X + C) ^ signbit -> (X + C + signbit)
5123             Constant *C =
5124                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5125             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5126
5127           }
5128         } else if (Op0I->getOpcode() == Instruction::Or) {
5129           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5130           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5131             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5132             // Anything in both C1 and C2 is known to be zero, remove it from
5133             // NewRHS.
5134             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5135             NewRHS = Context->getConstantExprAnd(NewRHS, 
5136                                        Context->getConstantExprNot(CommonBits));
5137             AddToWorkList(Op0I);
5138             I.setOperand(0, Op0I->getOperand(0));
5139             I.setOperand(1, NewRHS);
5140             return &I;
5141           }
5142         }
5143       }
5144     }
5145
5146     // Try to fold constant and into select arguments.
5147     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5148       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5149         return R;
5150     if (isa<PHINode>(Op0))
5151       if (Instruction *NV = FoldOpIntoPhi(I))
5152         return NV;
5153   }
5154
5155   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5156     if (X == Op1)
5157       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5158
5159   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5160     if (X == Op0)
5161       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5162
5163   
5164   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5165   if (Op1I) {
5166     Value *A, *B;
5167     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5168       if (A == Op0) {              // B^(B|A) == (A|B)^B
5169         Op1I->swapOperands();
5170         I.swapOperands();
5171         std::swap(Op0, Op1);
5172       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5173         I.swapOperands();     // Simplified below.
5174         std::swap(Op0, Op1);
5175       }
5176     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5177       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5178     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5179       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5180     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5181                Op1I->hasOneUse()){
5182       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5183         Op1I->swapOperands();
5184         std::swap(A, B);
5185       }
5186       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5187         I.swapOperands();     // Simplified below.
5188         std::swap(Op0, Op1);
5189       }
5190     }
5191   }
5192   
5193   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5194   if (Op0I) {
5195     Value *A, *B;
5196     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5197         Op0I->hasOneUse()) {
5198       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5199         std::swap(A, B);
5200       if (B == Op1) {                                // (A|B)^B == A & ~B
5201         Instruction *NotB =
5202           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5203                                                         Op1, "tmp"), I);
5204         return BinaryOperator::CreateAnd(A, NotB);
5205       }
5206     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5207       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5208     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5209       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5210     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5211                Op0I->hasOneUse()){
5212       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5213         std::swap(A, B);
5214       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5215           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5216         Instruction *N =
5217           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5218         return BinaryOperator::CreateAnd(N, Op1);
5219       }
5220     }
5221   }
5222   
5223   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5224   if (Op0I && Op1I && Op0I->isShift() && 
5225       Op0I->getOpcode() == Op1I->getOpcode() && 
5226       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5227       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5228     Instruction *NewOp =
5229       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5230                                                     Op1I->getOperand(0),
5231                                                     Op0I->getName()), I);
5232     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5233                                   Op1I->getOperand(1));
5234   }
5235     
5236   if (Op0I && Op1I) {
5237     Value *A, *B, *C, *D;
5238     // (A & B)^(A | B) -> A ^ B
5239     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5240         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5241       if ((A == C && B == D) || (A == D && B == C)) 
5242         return BinaryOperator::CreateXor(A, B);
5243     }
5244     // (A | B)^(A & B) -> A ^ B
5245     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5246         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5247       if ((A == C && B == D) || (A == D && B == C)) 
5248         return BinaryOperator::CreateXor(A, B);
5249     }
5250     
5251     // (A & B)^(C & D)
5252     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5253         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5254         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5255       // (X & Y)^(X & Y) -> (Y^Z) & X
5256       Value *X = 0, *Y = 0, *Z = 0;
5257       if (A == C)
5258         X = A, Y = B, Z = D;
5259       else if (A == D)
5260         X = A, Y = B, Z = C;
5261       else if (B == C)
5262         X = B, Y = A, Z = D;
5263       else if (B == D)
5264         X = B, Y = A, Z = C;
5265       
5266       if (X) {
5267         Instruction *NewOp =
5268         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5269         return BinaryOperator::CreateAnd(NewOp, X);
5270       }
5271     }
5272   }
5273     
5274   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5275   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5276     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5277       return R;
5278
5279   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5280   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5281     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5282       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5283         const Type *SrcTy = Op0C->getOperand(0)->getType();
5284         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5285             // Only do this if the casts both really cause code to be generated.
5286             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5287                               I.getType(), TD) &&
5288             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5289                               I.getType(), TD)) {
5290           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5291                                                          Op1C->getOperand(0),
5292                                                          I.getName());
5293           InsertNewInstBefore(NewOp, I);
5294           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5295         }
5296       }
5297   }
5298
5299   return Changed ? &I : 0;
5300 }
5301
5302 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5303                                    LLVMContext *Context) {
5304   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5305 }
5306
5307 static bool HasAddOverflow(ConstantInt *Result,
5308                            ConstantInt *In1, ConstantInt *In2,
5309                            bool IsSigned) {
5310   if (IsSigned)
5311     if (In2->getValue().isNegative())
5312       return Result->getValue().sgt(In1->getValue());
5313     else
5314       return Result->getValue().slt(In1->getValue());
5315   else
5316     return Result->getValue().ult(In1->getValue());
5317 }
5318
5319 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5320 /// overflowed for this type.
5321 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5322                             Constant *In2, LLVMContext *Context,
5323                             bool IsSigned = false) {
5324   Result = Context->getConstantExprAdd(In1, In2);
5325
5326   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5327     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5328       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5329       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5330                          ExtractElement(In1, Idx, Context),
5331                          ExtractElement(In2, Idx, Context),
5332                          IsSigned))
5333         return true;
5334     }
5335     return false;
5336   }
5337
5338   return HasAddOverflow(cast<ConstantInt>(Result),
5339                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5340                         IsSigned);
5341 }
5342
5343 static bool HasSubOverflow(ConstantInt *Result,
5344                            ConstantInt *In1, ConstantInt *In2,
5345                            bool IsSigned) {
5346   if (IsSigned)
5347     if (In2->getValue().isNegative())
5348       return Result->getValue().slt(In1->getValue());
5349     else
5350       return Result->getValue().sgt(In1->getValue());
5351   else
5352     return Result->getValue().ugt(In1->getValue());
5353 }
5354
5355 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5356 /// overflowed for this type.
5357 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5358                             Constant *In2, LLVMContext *Context,
5359                             bool IsSigned = false) {
5360   Result = Context->getConstantExprSub(In1, In2);
5361
5362   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5363     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5364       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5365       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5366                          ExtractElement(In1, Idx, Context),
5367                          ExtractElement(In2, Idx, Context),
5368                          IsSigned))
5369         return true;
5370     }
5371     return false;
5372   }
5373
5374   return HasSubOverflow(cast<ConstantInt>(Result),
5375                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5376                         IsSigned);
5377 }
5378
5379 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5380 /// code necessary to compute the offset from the base pointer (without adding
5381 /// in the base pointer).  Return the result as a signed integer of intptr size.
5382 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5383   TargetData &TD = IC.getTargetData();
5384   gep_type_iterator GTI = gep_type_begin(GEP);
5385   const Type *IntPtrTy = TD.getIntPtrType();
5386   LLVMContext *Context = IC.getContext();
5387   Value *Result = Context->getNullValue(IntPtrTy);
5388
5389   // Build a mask for high order bits.
5390   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5391   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5392
5393   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5394        ++i, ++GTI) {
5395     Value *Op = *i;
5396     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5397     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5398       if (OpC->isZero()) continue;
5399       
5400       // Handle a struct index, which adds its field offset to the pointer.
5401       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5402         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5403         
5404         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5405           Result = 
5406              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5407         else
5408           Result = IC.InsertNewInstBefore(
5409                    BinaryOperator::CreateAdd(Result,
5410                                         Context->getConstantInt(IntPtrTy, Size),
5411                                              GEP->getName()+".offs"), I);
5412         continue;
5413       }
5414       
5415       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5416       Constant *OC =
5417               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5418       Scale = Context->getConstantExprMul(OC, Scale);
5419       if (Constant *RC = dyn_cast<Constant>(Result))
5420         Result = Context->getConstantExprAdd(RC, Scale);
5421       else {
5422         // Emit an add instruction.
5423         Result = IC.InsertNewInstBefore(
5424            BinaryOperator::CreateAdd(Result, Scale,
5425                                      GEP->getName()+".offs"), I);
5426       }
5427       continue;
5428     }
5429     // Convert to correct type.
5430     if (Op->getType() != IntPtrTy) {
5431       if (Constant *OpC = dyn_cast<Constant>(Op))
5432         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5433       else
5434         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5435                                                                 true,
5436                                                       Op->getName()+".c"), I);
5437     }
5438     if (Size != 1) {
5439       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5440       if (Constant *OpC = dyn_cast<Constant>(Op))
5441         Op = Context->getConstantExprMul(OpC, Scale);
5442       else    // We'll let instcombine(mul) convert this to a shl if possible.
5443         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5444                                                   GEP->getName()+".idx"), I);
5445     }
5446
5447     // Emit an add instruction.
5448     if (isa<Constant>(Op) && isa<Constant>(Result))
5449       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5450                                     cast<Constant>(Result));
5451     else
5452       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5453                                                   GEP->getName()+".offs"), I);
5454   }
5455   return Result;
5456 }
5457
5458
5459 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5460 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5461 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5462 /// be complex, and scales are involved.  The above expression would also be
5463 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5464 /// This later form is less amenable to optimization though, and we are allowed
5465 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5466 ///
5467 /// If we can't emit an optimized form for this expression, this returns null.
5468 /// 
5469 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5470                                           InstCombiner &IC) {
5471   TargetData &TD = IC.getTargetData();
5472   gep_type_iterator GTI = gep_type_begin(GEP);
5473
5474   // Check to see if this gep only has a single variable index.  If so, and if
5475   // any constant indices are a multiple of its scale, then we can compute this
5476   // in terms of the scale of the variable index.  For example, if the GEP
5477   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5478   // because the expression will cross zero at the same point.
5479   unsigned i, e = GEP->getNumOperands();
5480   int64_t Offset = 0;
5481   for (i = 1; i != e; ++i, ++GTI) {
5482     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5483       // Compute the aggregate offset of constant indices.
5484       if (CI->isZero()) continue;
5485
5486       // Handle a struct index, which adds its field offset to the pointer.
5487       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5488         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5489       } else {
5490         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5491         Offset += Size*CI->getSExtValue();
5492       }
5493     } else {
5494       // Found our variable index.
5495       break;
5496     }
5497   }
5498   
5499   // If there are no variable indices, we must have a constant offset, just
5500   // evaluate it the general way.
5501   if (i == e) return 0;
5502   
5503   Value *VariableIdx = GEP->getOperand(i);
5504   // Determine the scale factor of the variable element.  For example, this is
5505   // 4 if the variable index is into an array of i32.
5506   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5507   
5508   // Verify that there are no other variable indices.  If so, emit the hard way.
5509   for (++i, ++GTI; i != e; ++i, ++GTI) {
5510     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5511     if (!CI) return 0;
5512    
5513     // Compute the aggregate offset of constant indices.
5514     if (CI->isZero()) continue;
5515     
5516     // Handle a struct index, which adds its field offset to the pointer.
5517     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5518       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5519     } else {
5520       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5521       Offset += Size*CI->getSExtValue();
5522     }
5523   }
5524   
5525   // Okay, we know we have a single variable index, which must be a
5526   // pointer/array/vector index.  If there is no offset, life is simple, return
5527   // the index.
5528   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5529   if (Offset == 0) {
5530     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5531     // we don't need to bother extending: the extension won't affect where the
5532     // computation crosses zero.
5533     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5534       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5535                                   VariableIdx->getNameStart(), &I);
5536     return VariableIdx;
5537   }
5538   
5539   // Otherwise, there is an index.  The computation we will do will be modulo
5540   // the pointer size, so get it.
5541   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5542   
5543   Offset &= PtrSizeMask;
5544   VariableScale &= PtrSizeMask;
5545
5546   // To do this transformation, any constant index must be a multiple of the
5547   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5548   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5549   // multiple of the variable scale.
5550   int64_t NewOffs = Offset / (int64_t)VariableScale;
5551   if (Offset != NewOffs*(int64_t)VariableScale)
5552     return 0;
5553
5554   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5555   const Type *IntPtrTy = TD.getIntPtrType();
5556   if (VariableIdx->getType() != IntPtrTy)
5557     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5558                                               true /*SExt*/, 
5559                                               VariableIdx->getNameStart(), &I);
5560   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5561   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5562 }
5563
5564
5565 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5566 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5567 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5568                                        ICmpInst::Predicate Cond,
5569                                        Instruction &I) {
5570   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5571
5572   // Look through bitcasts.
5573   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5574     RHS = BCI->getOperand(0);
5575
5576   Value *PtrBase = GEPLHS->getOperand(0);
5577   if (PtrBase == RHS) {
5578     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5579     // This transformation (ignoring the base and scales) is valid because we
5580     // know pointers can't overflow.  See if we can output an optimized form.
5581     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5582     
5583     // If not, synthesize the offset the hard way.
5584     if (Offset == 0)
5585       Offset = EmitGEPOffset(GEPLHS, I, *this);
5586     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5587                         Context->getNullValue(Offset->getType()));
5588   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5589     // If the base pointers are different, but the indices are the same, just
5590     // compare the base pointer.
5591     if (PtrBase != GEPRHS->getOperand(0)) {
5592       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5593       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5594                         GEPRHS->getOperand(0)->getType();
5595       if (IndicesTheSame)
5596         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5597           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5598             IndicesTheSame = false;
5599             break;
5600           }
5601
5602       // If all indices are the same, just compare the base pointers.
5603       if (IndicesTheSame)
5604         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5605                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5606
5607       // Otherwise, the base pointers are different and the indices are
5608       // different, bail out.
5609       return 0;
5610     }
5611
5612     // If one of the GEPs has all zero indices, recurse.
5613     bool AllZeros = true;
5614     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5615       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5616           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5617         AllZeros = false;
5618         break;
5619       }
5620     if (AllZeros)
5621       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5622                           ICmpInst::getSwappedPredicate(Cond), I);
5623
5624     // If the other GEP has all zero indices, recurse.
5625     AllZeros = true;
5626     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5627       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5628           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5629         AllZeros = false;
5630         break;
5631       }
5632     if (AllZeros)
5633       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5634
5635     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5636       // If the GEPs only differ by one index, compare it.
5637       unsigned NumDifferences = 0;  // Keep track of # differences.
5638       unsigned DiffOperand = 0;     // The operand that differs.
5639       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5640         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5641           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5642                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5643             // Irreconcilable differences.
5644             NumDifferences = 2;
5645             break;
5646           } else {
5647             if (NumDifferences++) break;
5648             DiffOperand = i;
5649           }
5650         }
5651
5652       if (NumDifferences == 0)   // SAME GEP?
5653         return ReplaceInstUsesWith(I, // No comparison is needed here.
5654                                    Context->getConstantInt(Type::Int1Ty,
5655                                              ICmpInst::isTrueWhenEqual(Cond)));
5656
5657       else if (NumDifferences == 1) {
5658         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5659         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5660         // Make sure we do a signed comparison here.
5661         return new ICmpInst(*Context,
5662                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5663       }
5664     }
5665
5666     // Only lower this if the icmp is the only user of the GEP or if we expect
5667     // the result to fold to a constant!
5668     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5669         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5670       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5671       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5672       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5673       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5674     }
5675   }
5676   return 0;
5677 }
5678
5679 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5680 ///
5681 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5682                                                 Instruction *LHSI,
5683                                                 Constant *RHSC) {
5684   if (!isa<ConstantFP>(RHSC)) return 0;
5685   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5686   
5687   // Get the width of the mantissa.  We don't want to hack on conversions that
5688   // might lose information from the integer, e.g. "i64 -> float"
5689   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5690   if (MantissaWidth == -1) return 0;  // Unknown.
5691   
5692   // Check to see that the input is converted from an integer type that is small
5693   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5694   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5695   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5696   
5697   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5698   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5699   if (LHSUnsigned)
5700     ++InputSize;
5701   
5702   // If the conversion would lose info, don't hack on this.
5703   if ((int)InputSize > MantissaWidth)
5704     return 0;
5705   
5706   // Otherwise, we can potentially simplify the comparison.  We know that it
5707   // will always come through as an integer value and we know the constant is
5708   // not a NAN (it would have been previously simplified).
5709   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5710   
5711   ICmpInst::Predicate Pred;
5712   switch (I.getPredicate()) {
5713   default: llvm_unreachable("Unexpected predicate!");
5714   case FCmpInst::FCMP_UEQ:
5715   case FCmpInst::FCMP_OEQ:
5716     Pred = ICmpInst::ICMP_EQ;
5717     break;
5718   case FCmpInst::FCMP_UGT:
5719   case FCmpInst::FCMP_OGT:
5720     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5721     break;
5722   case FCmpInst::FCMP_UGE:
5723   case FCmpInst::FCMP_OGE:
5724     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5725     break;
5726   case FCmpInst::FCMP_ULT:
5727   case FCmpInst::FCMP_OLT:
5728     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5729     break;
5730   case FCmpInst::FCMP_ULE:
5731   case FCmpInst::FCMP_OLE:
5732     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5733     break;
5734   case FCmpInst::FCMP_UNE:
5735   case FCmpInst::FCMP_ONE:
5736     Pred = ICmpInst::ICMP_NE;
5737     break;
5738   case FCmpInst::FCMP_ORD:
5739     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5740   case FCmpInst::FCMP_UNO:
5741     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5742   }
5743   
5744   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5745   
5746   // Now we know that the APFloat is a normal number, zero or inf.
5747   
5748   // See if the FP constant is too large for the integer.  For example,
5749   // comparing an i8 to 300.0.
5750   unsigned IntWidth = IntTy->getScalarSizeInBits();
5751   
5752   if (!LHSUnsigned) {
5753     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5754     // and large values.
5755     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5756     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5757                           APFloat::rmNearestTiesToEven);
5758     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5759       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5760           Pred == ICmpInst::ICMP_SLE)
5761         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5762       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5763     }
5764   } else {
5765     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5766     // +INF and large values.
5767     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5768     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5769                           APFloat::rmNearestTiesToEven);
5770     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5771       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5772           Pred == ICmpInst::ICMP_ULE)
5773         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5774       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5775     }
5776   }
5777   
5778   if (!LHSUnsigned) {
5779     // See if the RHS value is < SignedMin.
5780     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5781     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5782                           APFloat::rmNearestTiesToEven);
5783     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5784       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5785           Pred == ICmpInst::ICMP_SGE)
5786         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5787       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5788     }
5789   }
5790
5791   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5792   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5793   // casting the FP value to the integer value and back, checking for equality.
5794   // Don't do this for zero, because -0.0 is not fractional.
5795   Constant *RHSInt = LHSUnsigned
5796     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5797     : Context->getConstantExprFPToSI(RHSC, IntTy);
5798   if (!RHS.isZero()) {
5799     bool Equal = LHSUnsigned
5800       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5801       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5802     if (!Equal) {
5803       // If we had a comparison against a fractional value, we have to adjust
5804       // the compare predicate and sometimes the value.  RHSC is rounded towards
5805       // zero at this point.
5806       switch (Pred) {
5807       default: llvm_unreachable("Unexpected integer comparison!");
5808       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5809         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5810       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5811         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5812       case ICmpInst::ICMP_ULE:
5813         // (float)int <= 4.4   --> int <= 4
5814         // (float)int <= -4.4  --> false
5815         if (RHS.isNegative())
5816           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5817         break;
5818       case ICmpInst::ICMP_SLE:
5819         // (float)int <= 4.4   --> int <= 4
5820         // (float)int <= -4.4  --> int < -4
5821         if (RHS.isNegative())
5822           Pred = ICmpInst::ICMP_SLT;
5823         break;
5824       case ICmpInst::ICMP_ULT:
5825         // (float)int < -4.4   --> false
5826         // (float)int < 4.4    --> int <= 4
5827         if (RHS.isNegative())
5828           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5829         Pred = ICmpInst::ICMP_ULE;
5830         break;
5831       case ICmpInst::ICMP_SLT:
5832         // (float)int < -4.4   --> int < -4
5833         // (float)int < 4.4    --> int <= 4
5834         if (!RHS.isNegative())
5835           Pred = ICmpInst::ICMP_SLE;
5836         break;
5837       case ICmpInst::ICMP_UGT:
5838         // (float)int > 4.4    --> int > 4
5839         // (float)int > -4.4   --> true
5840         if (RHS.isNegative())
5841           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5842         break;
5843       case ICmpInst::ICMP_SGT:
5844         // (float)int > 4.4    --> int > 4
5845         // (float)int > -4.4   --> int >= -4
5846         if (RHS.isNegative())
5847           Pred = ICmpInst::ICMP_SGE;
5848         break;
5849       case ICmpInst::ICMP_UGE:
5850         // (float)int >= -4.4   --> true
5851         // (float)int >= 4.4    --> int > 4
5852         if (!RHS.isNegative())
5853           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5854         Pred = ICmpInst::ICMP_UGT;
5855         break;
5856       case ICmpInst::ICMP_SGE:
5857         // (float)int >= -4.4   --> int >= -4
5858         // (float)int >= 4.4    --> int > 4
5859         if (!RHS.isNegative())
5860           Pred = ICmpInst::ICMP_SGT;
5861         break;
5862       }
5863     }
5864   }
5865
5866   // Lower this FP comparison into an appropriate integer version of the
5867   // comparison.
5868   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5869 }
5870
5871 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5872   bool Changed = SimplifyCompare(I);
5873   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5874
5875   // Fold trivial predicates.
5876   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5877     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5878   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5879     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5880   
5881   // Simplify 'fcmp pred X, X'
5882   if (Op0 == Op1) {
5883     switch (I.getPredicate()) {
5884     default: llvm_unreachable("Unknown predicate!");
5885     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5886     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5887     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5888       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5889     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5890     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5891     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5892       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5893       
5894     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5895     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5896     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5897     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5898       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5899       I.setPredicate(FCmpInst::FCMP_UNO);
5900       I.setOperand(1, Context->getNullValue(Op0->getType()));
5901       return &I;
5902       
5903     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5904     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5905     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5906     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5907       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5908       I.setPredicate(FCmpInst::FCMP_ORD);
5909       I.setOperand(1, Context->getNullValue(Op0->getType()));
5910       return &I;
5911     }
5912   }
5913     
5914   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5915     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5916
5917   // Handle fcmp with constant RHS
5918   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5919     // If the constant is a nan, see if we can fold the comparison based on it.
5920     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5921       if (CFP->getValueAPF().isNaN()) {
5922         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5923           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5924         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5925                "Comparison must be either ordered or unordered!");
5926         // True if unordered.
5927         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5928       }
5929     }
5930     
5931     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5932       switch (LHSI->getOpcode()) {
5933       case Instruction::PHI:
5934         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5935         // block.  If in the same block, we're encouraging jump threading.  If
5936         // not, we are just pessimizing the code by making an i1 phi.
5937         if (LHSI->getParent() == I.getParent())
5938           if (Instruction *NV = FoldOpIntoPhi(I))
5939             return NV;
5940         break;
5941       case Instruction::SIToFP:
5942       case Instruction::UIToFP:
5943         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5944           return NV;
5945         break;
5946       case Instruction::Select:
5947         // If either operand of the select is a constant, we can fold the
5948         // comparison into the select arms, which will cause one to be
5949         // constant folded and the select turned into a bitwise or.
5950         Value *Op1 = 0, *Op2 = 0;
5951         if (LHSI->hasOneUse()) {
5952           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5953             // Fold the known value into the constant operand.
5954             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5955             // Insert a new FCmp of the other select operand.
5956             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5957                                                       LHSI->getOperand(2), RHSC,
5958                                                       I.getName()), I);
5959           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5960             // Fold the known value into the constant operand.
5961             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5962             // Insert a new FCmp of the other select operand.
5963             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5964                                                       LHSI->getOperand(1), RHSC,
5965                                                       I.getName()), I);
5966           }
5967         }
5968
5969         if (Op1)
5970           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5971         break;
5972       }
5973   }
5974
5975   return Changed ? &I : 0;
5976 }
5977
5978 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5979   bool Changed = SimplifyCompare(I);
5980   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5981   const Type *Ty = Op0->getType();
5982
5983   // icmp X, X
5984   if (Op0 == Op1)
5985     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5986                                                    I.isTrueWhenEqual()));
5987
5988   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5989     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5990   
5991   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5992   // addresses never equal each other!  We already know that Op0 != Op1.
5993   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5994        isa<ConstantPointerNull>(Op0)) &&
5995       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5996        isa<ConstantPointerNull>(Op1)))
5997     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5998                                                    !I.isTrueWhenEqual()));
5999
6000   // icmp's with boolean values can always be turned into bitwise operations
6001   if (Ty == Type::Int1Ty) {
6002     switch (I.getPredicate()) {
6003     default: llvm_unreachable("Invalid icmp instruction!");
6004     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6005       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6006       InsertNewInstBefore(Xor, I);
6007       return BinaryOperator::CreateNot(*Context, Xor);
6008     }
6009     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6010       return BinaryOperator::CreateXor(Op0, Op1);
6011
6012     case ICmpInst::ICMP_UGT:
6013       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6014       // FALL THROUGH
6015     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6016       Instruction *Not = BinaryOperator::CreateNot(*Context,
6017                                                    Op0, I.getName()+"tmp");
6018       InsertNewInstBefore(Not, I);
6019       return BinaryOperator::CreateAnd(Not, Op1);
6020     }
6021     case ICmpInst::ICMP_SGT:
6022       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6023       // FALL THROUGH
6024     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6025       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6026                                                    Op1, I.getName()+"tmp");
6027       InsertNewInstBefore(Not, I);
6028       return BinaryOperator::CreateAnd(Not, Op0);
6029     }
6030     case ICmpInst::ICMP_UGE:
6031       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6032       // FALL THROUGH
6033     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6034       Instruction *Not = BinaryOperator::CreateNot(*Context,
6035                                                    Op0, I.getName()+"tmp");
6036       InsertNewInstBefore(Not, I);
6037       return BinaryOperator::CreateOr(Not, Op1);
6038     }
6039     case ICmpInst::ICMP_SGE:
6040       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6041       // FALL THROUGH
6042     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6043       Instruction *Not = BinaryOperator::CreateNot(*Context,
6044                                                    Op1, I.getName()+"tmp");
6045       InsertNewInstBefore(Not, I);
6046       return BinaryOperator::CreateOr(Not, Op0);
6047     }
6048     }
6049   }
6050
6051   unsigned BitWidth = 0;
6052   if (TD)
6053     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6054   else if (Ty->isIntOrIntVector())
6055     BitWidth = Ty->getScalarSizeInBits();
6056
6057   bool isSignBit = false;
6058
6059   // See if we are doing a comparison with a constant.
6060   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6061     Value *A = 0, *B = 0;
6062     
6063     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6064     if (I.isEquality() && CI->isNullValue() &&
6065         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6066       // (icmp cond A B) if cond is equality
6067       return new ICmpInst(*Context, I.getPredicate(), A, B);
6068     }
6069     
6070     // If we have an icmp le or icmp ge instruction, turn it into the
6071     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6072     // them being folded in the code below.
6073     switch (I.getPredicate()) {
6074     default: break;
6075     case ICmpInst::ICMP_ULE:
6076       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6077         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6078       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6079                           AddOne(CI, Context));
6080     case ICmpInst::ICMP_SLE:
6081       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6082         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6083       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6084                           AddOne(CI, Context));
6085     case ICmpInst::ICMP_UGE:
6086       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6087         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6088       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6089                           SubOne(CI, Context));
6090     case ICmpInst::ICMP_SGE:
6091       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6092         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6093       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6094                           SubOne(CI, Context));
6095     }
6096     
6097     // If this comparison is a normal comparison, it demands all
6098     // bits, if it is a sign bit comparison, it only demands the sign bit.
6099     bool UnusedBit;
6100     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6101   }
6102
6103   // See if we can fold the comparison based on range information we can get
6104   // by checking whether bits are known to be zero or one in the input.
6105   if (BitWidth != 0) {
6106     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6107     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6108
6109     if (SimplifyDemandedBits(I.getOperandUse(0),
6110                              isSignBit ? APInt::getSignBit(BitWidth)
6111                                        : APInt::getAllOnesValue(BitWidth),
6112                              Op0KnownZero, Op0KnownOne, 0))
6113       return &I;
6114     if (SimplifyDemandedBits(I.getOperandUse(1),
6115                              APInt::getAllOnesValue(BitWidth),
6116                              Op1KnownZero, Op1KnownOne, 0))
6117       return &I;
6118
6119     // Given the known and unknown bits, compute a range that the LHS could be
6120     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6121     // EQ and NE we use unsigned values.
6122     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6123     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6124     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6125       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126                                              Op0Min, Op0Max);
6127       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128                                              Op1Min, Op1Max);
6129     } else {
6130       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131                                                Op0Min, Op0Max);
6132       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6133                                                Op1Min, Op1Max);
6134     }
6135
6136     // If Min and Max are known to be the same, then SimplifyDemandedBits
6137     // figured out that the LHS is a constant.  Just constant fold this now so
6138     // that code below can assume that Min != Max.
6139     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6140       return new ICmpInst(*Context, I.getPredicate(),
6141                           Context->getConstantInt(Op0Min), Op1);
6142     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6143       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6144                           Context->getConstantInt(Op1Min));
6145
6146     // Based on the range information we know about the LHS, see if we can
6147     // simplify this comparison.  For example, (x&4) < 8  is always true.
6148     switch (I.getPredicate()) {
6149     default: llvm_unreachable("Unknown icmp opcode!");
6150     case ICmpInst::ICMP_EQ:
6151       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6152         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6153       break;
6154     case ICmpInst::ICMP_NE:
6155       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6156         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6157       break;
6158     case ICmpInst::ICMP_ULT:
6159       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6160         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6161       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6162         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6163       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6164         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6165       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6167           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6168                               SubOne(CI, Context));
6169
6170         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6171         if (CI->isMinValue(true))
6172           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6173                            Context->getAllOnesValue(Op0->getType()));
6174       }
6175       break;
6176     case ICmpInst::ICMP_UGT:
6177       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6178         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6179       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6180         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6181
6182       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6183         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6184       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6186           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187                               AddOne(CI, Context));
6188
6189         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6190         if (CI->isMaxValue(true))
6191           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6192                               Context->getNullValue(Op0->getType()));
6193       }
6194       break;
6195     case ICmpInst::ICMP_SLT:
6196       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6197         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6198       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6199         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6200       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6201         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6202       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6203         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6204           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6205                               SubOne(CI, Context));
6206       }
6207       break;
6208     case ICmpInst::ICMP_SGT:
6209       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6210         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6211       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6212         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6213
6214       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6215         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6216       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6217         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6218           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6219                               AddOne(CI, Context));
6220       }
6221       break;
6222     case ICmpInst::ICMP_SGE:
6223       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6224       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6225         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6226       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6227         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6228       break;
6229     case ICmpInst::ICMP_SLE:
6230       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6231       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6232         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6233       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6234         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6235       break;
6236     case ICmpInst::ICMP_UGE:
6237       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6238       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6239         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6240       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6241         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6242       break;
6243     case ICmpInst::ICMP_ULE:
6244       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6245       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6246         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6247       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6248         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6249       break;
6250     }
6251
6252     // Turn a signed comparison into an unsigned one if both operands
6253     // are known to have the same sign.
6254     if (I.isSignedPredicate() &&
6255         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6256          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6257       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6258   }
6259
6260   // Test if the ICmpInst instruction is used exclusively by a select as
6261   // part of a minimum or maximum operation. If so, refrain from doing
6262   // any other folding. This helps out other analyses which understand
6263   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6264   // and CodeGen. And in this case, at least one of the comparison
6265   // operands has at least one user besides the compare (the select),
6266   // which would often largely negate the benefit of folding anyway.
6267   if (I.hasOneUse())
6268     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6269       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6270           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6271         return 0;
6272
6273   // See if we are doing a comparison between a constant and an instruction that
6274   // can be folded into the comparison.
6275   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6276     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6277     // instruction, see if that instruction also has constants so that the 
6278     // instruction can be folded into the icmp 
6279     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6280       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6281         return Res;
6282   }
6283
6284   // Handle icmp with constant (but not simple integer constant) RHS
6285   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6286     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287       switch (LHSI->getOpcode()) {
6288       case Instruction::GetElementPtr:
6289         if (RHSC->isNullValue()) {
6290           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6291           bool isAllZeros = true;
6292           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6293             if (!isa<Constant>(LHSI->getOperand(i)) ||
6294                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6295               isAllZeros = false;
6296               break;
6297             }
6298           if (isAllZeros)
6299             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6300                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6301         }
6302         break;
6303
6304       case Instruction::PHI:
6305         // Only fold icmp into the PHI if the phi and fcmp are in the same
6306         // block.  If in the same block, we're encouraging jump threading.  If
6307         // not, we are just pessimizing the code by making an i1 phi.
6308         if (LHSI->getParent() == I.getParent())
6309           if (Instruction *NV = FoldOpIntoPhi(I))
6310             return NV;
6311         break;
6312       case Instruction::Select: {
6313         // If either operand of the select is a constant, we can fold the
6314         // comparison into the select arms, which will cause one to be
6315         // constant folded and the select turned into a bitwise or.
6316         Value *Op1 = 0, *Op2 = 0;
6317         if (LHSI->hasOneUse()) {
6318           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6319             // Fold the known value into the constant operand.
6320             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6321             // Insert a new ICmp of the other select operand.
6322             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6323                                                    LHSI->getOperand(2), RHSC,
6324                                                    I.getName()), I);
6325           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6326             // Fold the known value into the constant operand.
6327             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6328             // Insert a new ICmp of the other select operand.
6329             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6330                                                    LHSI->getOperand(1), RHSC,
6331                                                    I.getName()), I);
6332           }
6333         }
6334
6335         if (Op1)
6336           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6337         break;
6338       }
6339       case Instruction::Malloc:
6340         // If we have (malloc != null), and if the malloc has a single use, we
6341         // can assume it is successful and remove the malloc.
6342         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6343           AddToWorkList(LHSI);
6344           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6345                                                          !I.isTrueWhenEqual()));
6346         }
6347         break;
6348       }
6349   }
6350
6351   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6352   if (User *GEP = dyn_castGetElementPtr(Op0))
6353     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6354       return NI;
6355   if (User *GEP = dyn_castGetElementPtr(Op1))
6356     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6357                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6358       return NI;
6359
6360   // Test to see if the operands of the icmp are casted versions of other
6361   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6362   // now.
6363   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6364     if (isa<PointerType>(Op0->getType()) && 
6365         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6366       // We keep moving the cast from the left operand over to the right
6367       // operand, where it can often be eliminated completely.
6368       Op0 = CI->getOperand(0);
6369
6370       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6371       // so eliminate it as well.
6372       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6373         Op1 = CI2->getOperand(0);
6374
6375       // If Op1 is a constant, we can fold the cast into the constant.
6376       if (Op0->getType() != Op1->getType()) {
6377         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6378           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6379         } else {
6380           // Otherwise, cast the RHS right before the icmp
6381           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6382         }
6383       }
6384       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6385     }
6386   }
6387   
6388   if (isa<CastInst>(Op0)) {
6389     // Handle the special case of: icmp (cast bool to X), <cst>
6390     // This comes up when you have code like
6391     //   int X = A < B;
6392     //   if (X) ...
6393     // For generality, we handle any zero-extension of any operand comparison
6394     // with a constant or another cast from the same type.
6395     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6396       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6397         return R;
6398   }
6399   
6400   // See if it's the same type of instruction on the left and right.
6401   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6402     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6403       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6404           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6405         switch (Op0I->getOpcode()) {
6406         default: break;
6407         case Instruction::Add:
6408         case Instruction::Sub:
6409         case Instruction::Xor:
6410           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6411             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6412                                 Op1I->getOperand(0));
6413           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6414           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6415             if (CI->getValue().isSignBit()) {
6416               ICmpInst::Predicate Pred = I.isSignedPredicate()
6417                                              ? I.getUnsignedPredicate()
6418                                              : I.getSignedPredicate();
6419               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6420                                   Op1I->getOperand(0));
6421             }
6422             
6423             if (CI->getValue().isMaxSignedValue()) {
6424               ICmpInst::Predicate Pred = I.isSignedPredicate()
6425                                              ? I.getUnsignedPredicate()
6426                                              : I.getSignedPredicate();
6427               Pred = I.getSwappedPredicate(Pred);
6428               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6429                                   Op1I->getOperand(0));
6430             }
6431           }
6432           break;
6433         case Instruction::Mul:
6434           if (!I.isEquality())
6435             break;
6436
6437           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6438             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6439             // Mask = -1 >> count-trailing-zeros(Cst).
6440             if (!CI->isZero() && !CI->isOne()) {
6441               const APInt &AP = CI->getValue();
6442               ConstantInt *Mask = Context->getConstantInt(
6443                                       APInt::getLowBitsSet(AP.getBitWidth(),
6444                                                            AP.getBitWidth() -
6445                                                       AP.countTrailingZeros()));
6446               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6447                                                             Mask);
6448               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6449                                                             Mask);
6450               InsertNewInstBefore(And1, I);
6451               InsertNewInstBefore(And2, I);
6452               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6453             }
6454           }
6455           break;
6456         }
6457       }
6458     }
6459   }
6460   
6461   // ~x < ~y --> y < x
6462   { Value *A, *B;
6463     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6464         match(Op1, m_Not(m_Value(B)), *Context))
6465       return new ICmpInst(*Context, I.getPredicate(), B, A);
6466   }
6467   
6468   if (I.isEquality()) {
6469     Value *A, *B, *C, *D;
6470     
6471     // -x == -y --> x == y
6472     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6473         match(Op1, m_Neg(m_Value(B)), *Context))
6474       return new ICmpInst(*Context, I.getPredicate(), A, B);
6475     
6476     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6477       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6478         Value *OtherVal = A == Op1 ? B : A;
6479         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6480                             Context->getNullValue(A->getType()));
6481       }
6482
6483       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6484         // A^c1 == C^c2 --> A == C^(c1^c2)
6485         ConstantInt *C1, *C2;
6486         if (match(B, m_ConstantInt(C1), *Context) &&
6487             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6488           Constant *NC = 
6489                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6490           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6491           return new ICmpInst(*Context, I.getPredicate(), A,
6492                               InsertNewInstBefore(Xor, I));
6493         }
6494         
6495         // A^B == A^D -> B == D
6496         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6497         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6498         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6499         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6500       }
6501     }
6502     
6503     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6504         (A == Op0 || B == Op0)) {
6505       // A == (A^B)  ->  B == 0
6506       Value *OtherVal = A == Op0 ? B : A;
6507       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6508                           Context->getNullValue(A->getType()));
6509     }
6510
6511     // (A-B) == A  ->  B == 0
6512     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6513       return new ICmpInst(*Context, I.getPredicate(), B, 
6514                           Context->getNullValue(B->getType()));
6515
6516     // A == (A-B)  ->  B == 0
6517     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6518       return new ICmpInst(*Context, I.getPredicate(), B,
6519                           Context->getNullValue(B->getType()));
6520     
6521     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6522     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6523         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6524         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6525       Value *X = 0, *Y = 0, *Z = 0;
6526       
6527       if (A == C) {
6528         X = B; Y = D; Z = A;
6529       } else if (A == D) {
6530         X = B; Y = C; Z = A;
6531       } else if (B == C) {
6532         X = A; Y = D; Z = B;
6533       } else if (B == D) {
6534         X = A; Y = C; Z = B;
6535       }
6536       
6537       if (X) {   // Build (X^Y) & Z
6538         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6539         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6540         I.setOperand(0, Op1);
6541         I.setOperand(1, Context->getNullValue(Op1->getType()));
6542         return &I;
6543       }
6544     }
6545   }
6546   return Changed ? &I : 0;
6547 }
6548
6549
6550 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6551 /// and CmpRHS are both known to be integer constants.
6552 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6553                                           ConstantInt *DivRHS) {
6554   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6555   const APInt &CmpRHSV = CmpRHS->getValue();
6556   
6557   // FIXME: If the operand types don't match the type of the divide 
6558   // then don't attempt this transform. The code below doesn't have the
6559   // logic to deal with a signed divide and an unsigned compare (and
6560   // vice versa). This is because (x /s C1) <s C2  produces different 
6561   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6562   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6563   // work. :(  The if statement below tests that condition and bails 
6564   // if it finds it. 
6565   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6566   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6567     return 0;
6568   if (DivRHS->isZero())
6569     return 0; // The ProdOV computation fails on divide by zero.
6570   if (DivIsSigned && DivRHS->isAllOnesValue())
6571     return 0; // The overflow computation also screws up here
6572   if (DivRHS->isOne())
6573     return 0; // Not worth bothering, and eliminates some funny cases
6574               // with INT_MIN.
6575
6576   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6577   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6578   // C2 (CI). By solving for X we can turn this into a range check 
6579   // instead of computing a divide. 
6580   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6581
6582   // Determine if the product overflows by seeing if the product is
6583   // not equal to the divide. Make sure we do the same kind of divide
6584   // as in the LHS instruction that we're folding. 
6585   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6586                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6587
6588   // Get the ICmp opcode
6589   ICmpInst::Predicate Pred = ICI.getPredicate();
6590
6591   // Figure out the interval that is being checked.  For example, a comparison
6592   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6593   // Compute this interval based on the constants involved and the signedness of
6594   // the compare/divide.  This computes a half-open interval, keeping track of
6595   // whether either value in the interval overflows.  After analysis each
6596   // overflow variable is set to 0 if it's corresponding bound variable is valid
6597   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6598   int LoOverflow = 0, HiOverflow = 0;
6599   Constant *LoBound = 0, *HiBound = 0;
6600   
6601   if (!DivIsSigned) {  // udiv
6602     // e.g. X/5 op 3  --> [15, 20)
6603     LoBound = Prod;
6604     HiOverflow = LoOverflow = ProdOV;
6605     if (!HiOverflow)
6606       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6607   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6608     if (CmpRHSV == 0) {       // (X / pos) op 0
6609       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6610       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6611                                                                     Context)));
6612       HiBound = DivRHS;
6613     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6614       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6615       HiOverflow = LoOverflow = ProdOV;
6616       if (!HiOverflow)
6617         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6618     } else {                       // (X / pos) op neg
6619       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6620       HiBound = AddOne(Prod, Context);
6621       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6622       if (!LoOverflow) {
6623         ConstantInt* DivNeg =
6624                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6625         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6626                                      true) ? -1 : 0;
6627        }
6628     }
6629   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6630     if (CmpRHSV == 0) {       // (X / neg) op 0
6631       // e.g. X/-5 op 0  --> [-4, 5)
6632       LoBound = AddOne(DivRHS, Context);
6633       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6634       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6635         HiOverflow = 1;            // [INTMIN+1, overflow)
6636         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6637       }
6638     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6639       // e.g. X/-5 op 3  --> [-19, -14)
6640       HiBound = AddOne(Prod, Context);
6641       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6642       if (!LoOverflow)
6643         LoOverflow = AddWithOverflow(LoBound, HiBound,
6644                                      DivRHS, Context, true) ? -1 : 0;
6645     } else {                       // (X / neg) op neg
6646       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6647       LoOverflow = HiOverflow = ProdOV;
6648       if (!HiOverflow)
6649         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6650     }
6651     
6652     // Dividing by a negative swaps the condition.  LT <-> GT
6653     Pred = ICmpInst::getSwappedPredicate(Pred);
6654   }
6655
6656   Value *X = DivI->getOperand(0);
6657   switch (Pred) {
6658   default: llvm_unreachable("Unhandled icmp opcode!");
6659   case ICmpInst::ICMP_EQ:
6660     if (LoOverflow && HiOverflow)
6661       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6662     else if (HiOverflow)
6663       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6664                           ICmpInst::ICMP_UGE, X, LoBound);
6665     else if (LoOverflow)
6666       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6667                           ICmpInst::ICMP_ULT, X, HiBound);
6668     else
6669       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6670   case ICmpInst::ICMP_NE:
6671     if (LoOverflow && HiOverflow)
6672       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6673     else if (HiOverflow)
6674       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6675                           ICmpInst::ICMP_ULT, X, LoBound);
6676     else if (LoOverflow)
6677       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6678                           ICmpInst::ICMP_UGE, X, HiBound);
6679     else
6680       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6681   case ICmpInst::ICMP_ULT:
6682   case ICmpInst::ICMP_SLT:
6683     if (LoOverflow == +1)   // Low bound is greater than input range.
6684       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6685     if (LoOverflow == -1)   // Low bound is less than input range.
6686       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6687     return new ICmpInst(*Context, Pred, X, LoBound);
6688   case ICmpInst::ICMP_UGT:
6689   case ICmpInst::ICMP_SGT:
6690     if (HiOverflow == +1)       // High bound greater than input range.
6691       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6692     else if (HiOverflow == -1)  // High bound less than input range.
6693       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6694     if (Pred == ICmpInst::ICMP_UGT)
6695       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6696     else
6697       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6698   }
6699 }
6700
6701
6702 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6703 ///
6704 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6705                                                           Instruction *LHSI,
6706                                                           ConstantInt *RHS) {
6707   const APInt &RHSV = RHS->getValue();
6708   
6709   switch (LHSI->getOpcode()) {
6710   case Instruction::Trunc:
6711     if (ICI.isEquality() && LHSI->hasOneUse()) {
6712       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6713       // of the high bits truncated out of x are known.
6714       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6715              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6716       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6717       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6718       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6719       
6720       // If all the high bits are known, we can do this xform.
6721       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6722         // Pull in the high bits from known-ones set.
6723         APInt NewRHS(RHS->getValue());
6724         NewRHS.zext(SrcBits);
6725         NewRHS |= KnownOne;
6726         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6727                             Context->getConstantInt(NewRHS));
6728       }
6729     }
6730     break;
6731       
6732   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6733     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6734       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6735       // fold the xor.
6736       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6737           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6738         Value *CompareVal = LHSI->getOperand(0);
6739         
6740         // If the sign bit of the XorCST is not set, there is no change to
6741         // the operation, just stop using the Xor.
6742         if (!XorCST->getValue().isNegative()) {
6743           ICI.setOperand(0, CompareVal);
6744           AddToWorkList(LHSI);
6745           return &ICI;
6746         }
6747         
6748         // Was the old condition true if the operand is positive?
6749         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6750         
6751         // If so, the new one isn't.
6752         isTrueIfPositive ^= true;
6753         
6754         if (isTrueIfPositive)
6755           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6756                               SubOne(RHS, Context));
6757         else
6758           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6759                               AddOne(RHS, Context));
6760       }
6761
6762       if (LHSI->hasOneUse()) {
6763         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6764         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6765           const APInt &SignBit = XorCST->getValue();
6766           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767                                          ? ICI.getUnsignedPredicate()
6768                                          : ICI.getSignedPredicate();
6769           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6770                               Context->getConstantInt(RHSV ^ SignBit));
6771         }
6772
6773         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6774         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6775           const APInt &NotSignBit = XorCST->getValue();
6776           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6777                                          ? ICI.getUnsignedPredicate()
6778                                          : ICI.getSignedPredicate();
6779           Pred = ICI.getSwappedPredicate(Pred);
6780           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6781                               Context->getConstantInt(RHSV ^ NotSignBit));
6782         }
6783       }
6784     }
6785     break;
6786   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6787     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6788         LHSI->getOperand(0)->hasOneUse()) {
6789       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6790       
6791       // If the LHS is an AND of a truncating cast, we can widen the
6792       // and/compare to be the input width without changing the value
6793       // produced, eliminating a cast.
6794       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6795         // We can do this transformation if either the AND constant does not
6796         // have its sign bit set or if it is an equality comparison. 
6797         // Extending a relational comparison when we're checking the sign
6798         // bit would not work.
6799         if (Cast->hasOneUse() &&
6800             (ICI.isEquality() ||
6801              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6802           uint32_t BitWidth = 
6803             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6804           APInt NewCST = AndCST->getValue();
6805           NewCST.zext(BitWidth);
6806           APInt NewCI = RHSV;
6807           NewCI.zext(BitWidth);
6808           Instruction *NewAnd = 
6809             BinaryOperator::CreateAnd(Cast->getOperand(0),
6810                                Context->getConstantInt(NewCST),LHSI->getName());
6811           InsertNewInstBefore(NewAnd, ICI);
6812           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6813                               Context->getConstantInt(NewCI));
6814         }
6815       }
6816       
6817       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6818       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6819       // happens a LOT in code produced by the C front-end, for bitfield
6820       // access.
6821       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6822       if (Shift && !Shift->isShift())
6823         Shift = 0;
6824       
6825       ConstantInt *ShAmt;
6826       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6827       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6828       const Type *AndTy = AndCST->getType();          // Type of the and.
6829       
6830       // We can fold this as long as we can't shift unknown bits
6831       // into the mask.  This can only happen with signed shift
6832       // rights, as they sign-extend.
6833       if (ShAmt) {
6834         bool CanFold = Shift->isLogicalShift();
6835         if (!CanFold) {
6836           // To test for the bad case of the signed shr, see if any
6837           // of the bits shifted in could be tested after the mask.
6838           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6839           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6840           
6841           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6842           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6843                AndCST->getValue()) == 0)
6844             CanFold = true;
6845         }
6846         
6847         if (CanFold) {
6848           Constant *NewCst;
6849           if (Shift->getOpcode() == Instruction::Shl)
6850             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6851           else
6852             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6853           
6854           // Check to see if we are shifting out any of the bits being
6855           // compared.
6856           if (Context->getConstantExpr(Shift->getOpcode(),
6857                                        NewCst, ShAmt) != RHS) {
6858             // If we shifted bits out, the fold is not going to work out.
6859             // As a special case, check to see if this means that the
6860             // result is always true or false now.
6861             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6862               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6863             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6864               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6865           } else {
6866             ICI.setOperand(1, NewCst);
6867             Constant *NewAndCST;
6868             if (Shift->getOpcode() == Instruction::Shl)
6869               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6870             else
6871               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6872             LHSI->setOperand(1, NewAndCST);
6873             LHSI->setOperand(0, Shift->getOperand(0));
6874             AddToWorkList(Shift); // Shift is dead.
6875             AddUsesToWorkList(ICI);
6876             return &ICI;
6877           }
6878         }
6879       }
6880       
6881       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6882       // preferable because it allows the C<<Y expression to be hoisted out
6883       // of a loop if Y is invariant and X is not.
6884       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6885           ICI.isEquality() && !Shift->isArithmeticShift() &&
6886           !isa<Constant>(Shift->getOperand(0))) {
6887         // Compute C << Y.
6888         Value *NS;
6889         if (Shift->getOpcode() == Instruction::LShr) {
6890           NS = BinaryOperator::CreateShl(AndCST, 
6891                                          Shift->getOperand(1), "tmp");
6892         } else {
6893           // Insert a logical shift.
6894           NS = BinaryOperator::CreateLShr(AndCST,
6895                                           Shift->getOperand(1), "tmp");
6896         }
6897         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6898         
6899         // Compute X & (C << Y).
6900         Instruction *NewAnd = 
6901           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6902         InsertNewInstBefore(NewAnd, ICI);
6903         
6904         ICI.setOperand(0, NewAnd);
6905         return &ICI;
6906       }
6907     }
6908     break;
6909     
6910   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6911     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6912     if (!ShAmt) break;
6913     
6914     uint32_t TypeBits = RHSV.getBitWidth();
6915     
6916     // Check that the shift amount is in range.  If not, don't perform
6917     // undefined shifts.  When the shift is visited it will be
6918     // simplified.
6919     if (ShAmt->uge(TypeBits))
6920       break;
6921     
6922     if (ICI.isEquality()) {
6923       // If we are comparing against bits always shifted out, the
6924       // comparison cannot succeed.
6925       Constant *Comp =
6926         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6927                                                                  ShAmt);
6928       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6929         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6930         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6931         return ReplaceInstUsesWith(ICI, Cst);
6932       }
6933       
6934       if (LHSI->hasOneUse()) {
6935         // Otherwise strength reduce the shift into an and.
6936         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6937         Constant *Mask =
6938           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6939                                                        TypeBits-ShAmtVal));
6940         
6941         Instruction *AndI =
6942           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6943                                     Mask, LHSI->getName()+".mask");
6944         Value *And = InsertNewInstBefore(AndI, ICI);
6945         return new ICmpInst(*Context, ICI.getPredicate(), And,
6946                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6947       }
6948     }
6949     
6950     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6951     bool TrueIfSigned = false;
6952     if (LHSI->hasOneUse() &&
6953         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6954       // (X << 31) <s 0  --> (X&1) != 0
6955       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6956                                            (TypeBits-ShAmt->getZExtValue()-1));
6957       Instruction *AndI =
6958         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6959                                   Mask, LHSI->getName()+".mask");
6960       Value *And = InsertNewInstBefore(AndI, ICI);
6961       
6962       return new ICmpInst(*Context,
6963                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6964                           And, Context->getNullValue(And->getType()));
6965     }
6966     break;
6967   }
6968     
6969   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6970   case Instruction::AShr: {
6971     // Only handle equality comparisons of shift-by-constant.
6972     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6973     if (!ShAmt || !ICI.isEquality()) break;
6974
6975     // Check that the shift amount is in range.  If not, don't perform
6976     // undefined shifts.  When the shift is visited it will be
6977     // simplified.
6978     uint32_t TypeBits = RHSV.getBitWidth();
6979     if (ShAmt->uge(TypeBits))
6980       break;
6981     
6982     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6983       
6984     // If we are comparing against bits always shifted out, the
6985     // comparison cannot succeed.
6986     APInt Comp = RHSV << ShAmtVal;
6987     if (LHSI->getOpcode() == Instruction::LShr)
6988       Comp = Comp.lshr(ShAmtVal);
6989     else
6990       Comp = Comp.ashr(ShAmtVal);
6991     
6992     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6993       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6994       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6995       return ReplaceInstUsesWith(ICI, Cst);
6996     }
6997     
6998     // Otherwise, check to see if the bits shifted out are known to be zero.
6999     // If so, we can compare against the unshifted value:
7000     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7001     if (LHSI->hasOneUse() &&
7002         MaskedValueIsZero(LHSI->getOperand(0), 
7003                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7004       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7005                           Context->getConstantExprShl(RHS, ShAmt));
7006     }
7007       
7008     if (LHSI->hasOneUse()) {
7009       // Otherwise strength reduce the shift into an and.
7010       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7011       Constant *Mask = Context->getConstantInt(Val);
7012       
7013       Instruction *AndI =
7014         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7015                                   Mask, LHSI->getName()+".mask");
7016       Value *And = InsertNewInstBefore(AndI, ICI);
7017       return new ICmpInst(*Context, ICI.getPredicate(), And,
7018                           Context->getConstantExprShl(RHS, ShAmt));
7019     }
7020     break;
7021   }
7022     
7023   case Instruction::SDiv:
7024   case Instruction::UDiv:
7025     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026     // Fold this div into the comparison, producing a range check. 
7027     // Determine, based on the divide type, what the range is being 
7028     // checked.  If there is an overflow on the low or high side, remember 
7029     // it, otherwise compute the range [low, hi) bounding the new value.
7030     // See: InsertRangeTest above for the kinds of replacements possible.
7031     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033                                           DivRHS))
7034         return R;
7035     break;
7036
7037   case Instruction::Add:
7038     // Fold: icmp pred (add, X, C1), C2
7039
7040     if (!ICI.isEquality()) {
7041       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042       if (!LHSC) break;
7043       const APInt &LHSV = LHSC->getValue();
7044
7045       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046                             .subtract(LHSV);
7047
7048       if (ICI.isSignedPredicate()) {
7049         if (CR.getLower().isSignBit()) {
7050           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7051                               Context->getConstantInt(CR.getUpper()));
7052         } else if (CR.getUpper().isSignBit()) {
7053           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7054                               Context->getConstantInt(CR.getLower()));
7055         }
7056       } else {
7057         if (CR.getLower().isMinValue()) {
7058           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7059                               Context->getConstantInt(CR.getUpper()));
7060         } else if (CR.getUpper().isMinValue()) {
7061           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7062                               Context->getConstantInt(CR.getLower()));
7063         }
7064       }
7065     }
7066     break;
7067   }
7068   
7069   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070   if (ICI.isEquality()) {
7071     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072     
7073     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7074     // the second operand is a constant, simplify a bit.
7075     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076       switch (BO->getOpcode()) {
7077       case Instruction::SRem:
7078         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7082             Instruction *NewRem =
7083               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7084                                          BO->getName());
7085             InsertNewInstBefore(NewRem, ICI);
7086             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7087                                 Context->getNullValue(BO->getType()));
7088           }
7089         }
7090         break;
7091       case Instruction::Add:
7092         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7093         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7094           if (BO->hasOneUse())
7095             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7096                                 Context->getConstantExprSub(RHS, BOp1C));
7097         } else if (RHSV == 0) {
7098           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7099           // efficiently invertible, or if the add has just this one use.
7100           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7101           
7102           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7103             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7104           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7105             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7106           else if (BO->hasOneUse()) {
7107             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7108             InsertNewInstBefore(Neg, ICI);
7109             Neg->takeName(BO);
7110             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7111           }
7112         }
7113         break;
7114       case Instruction::Xor:
7115         // For the xor case, we can xor two constants together, eliminating
7116         // the explicit xor.
7117         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7118           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7119                               Context->getConstantExprXor(RHS, BOC));
7120         
7121         // FALLTHROUGH
7122       case Instruction::Sub:
7123         // Replace (([sub|xor] A, B) != 0) with (A != B)
7124         if (RHSV == 0)
7125           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7126                               BO->getOperand(1));
7127         break;
7128         
7129       case Instruction::Or:
7130         // If bits are being or'd in that are not present in the constant we
7131         // are comparing against, then the comparison could never succeed!
7132         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7133           Constant *NotCI = Context->getConstantExprNot(RHS);
7134           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7135             return ReplaceInstUsesWith(ICI,
7136                                        Context->getConstantInt(Type::Int1Ty, 
7137                                        isICMP_NE));
7138         }
7139         break;
7140         
7141       case Instruction::And:
7142         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143           // If bits are being compared against that are and'd out, then the
7144           // comparison can never succeed!
7145           if ((RHSV & ~BOC->getValue()) != 0)
7146             return ReplaceInstUsesWith(ICI,
7147                                        Context->getConstantInt(Type::Int1Ty,
7148                                        isICMP_NE));
7149           
7150           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151           if (RHS == BOC && RHSV.isPowerOf2())
7152             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7153                                 ICmpInst::ICMP_NE, LHSI,
7154                                 Context->getNullValue(RHS->getType()));
7155           
7156           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7157           if (BOC->getValue().isSignBit()) {
7158             Value *X = BO->getOperand(0);
7159             Constant *Zero = Context->getNullValue(X->getType());
7160             ICmpInst::Predicate pred = isICMP_NE ? 
7161               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7162             return new ICmpInst(*Context, pred, X, Zero);
7163           }
7164           
7165           // ((X & ~7) == 0) --> X < 8
7166           if (RHSV == 0 && isHighOnes(BOC)) {
7167             Value *X = BO->getOperand(0);
7168             Constant *NegX = Context->getConstantExprNeg(BOC);
7169             ICmpInst::Predicate pred = isICMP_NE ? 
7170               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7171             return new ICmpInst(*Context, pred, X, NegX);
7172           }
7173         }
7174       default: break;
7175       }
7176     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177       // Handle icmp {eq|ne} <intrinsic>, intcst.
7178       if (II->getIntrinsicID() == Intrinsic::bswap) {
7179         AddToWorkList(II);
7180         ICI.setOperand(0, II->getOperand(1));
7181         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7182         return &ICI;
7183       }
7184     }
7185   }
7186   return 0;
7187 }
7188
7189 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190 /// We only handle extending casts so far.
7191 ///
7192 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7194   Value *LHSCIOp        = LHSCI->getOperand(0);
7195   const Type *SrcTy     = LHSCIOp->getType();
7196   const Type *DestTy    = LHSCI->getType();
7197   Value *RHSCIOp;
7198
7199   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7200   // integer type is the same size as the pointer type.
7201   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7202       getTargetData().getPointerSizeInBits() == 
7203          cast<IntegerType>(DestTy)->getBitWidth()) {
7204     Value *RHSOp = 0;
7205     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7206       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7207     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208       RHSOp = RHSC->getOperand(0);
7209       // If the pointer types don't match, insert a bitcast.
7210       if (LHSCIOp->getType() != RHSOp->getType())
7211         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7212     }
7213
7214     if (RHSOp)
7215       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7216   }
7217   
7218   // The code below only handles extension cast instructions, so far.
7219   // Enforce this.
7220   if (LHSCI->getOpcode() != Instruction::ZExt &&
7221       LHSCI->getOpcode() != Instruction::SExt)
7222     return 0;
7223
7224   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225   bool isSignedCmp = ICI.isSignedPredicate();
7226
7227   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7228     // Not an extension from the same type?
7229     RHSCIOp = CI->getOperand(0);
7230     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7231       return 0;
7232     
7233     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7234     // and the other is a zext), then we can't handle this.
7235     if (CI->getOpcode() != LHSCI->getOpcode())
7236       return 0;
7237
7238     // Deal with equality cases early.
7239     if (ICI.isEquality())
7240       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7241
7242     // A signed comparison of sign extended values simplifies into a
7243     // signed comparison.
7244     if (isSignedCmp && isSignedExt)
7245       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7246
7247     // The other three cases all fold into an unsigned comparison.
7248     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7249   }
7250
7251   // If we aren't dealing with a constant on the RHS, exit early
7252   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253   if (!CI)
7254     return 0;
7255
7256   // Compute the constant that would happen if we truncated to SrcTy then
7257   // reextended to DestTy.
7258   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7259   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7260                                                 Res1, DestTy);
7261
7262   // If the re-extended constant didn't change...
7263   if (Res2 == CI) {
7264     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265     // For example, we might have:
7266     //    %A = sext i16 %X to i32
7267     //    %B = icmp ugt i32 %A, 1330
7268     // It is incorrect to transform this into 
7269     //    %B = icmp ugt i16 %X, 1330
7270     // because %A may have negative value. 
7271     //
7272     // However, we allow this when the compare is EQ/NE, because they are
7273     // signless.
7274     if (isSignedExt == isSignedCmp || ICI.isEquality())
7275       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7276     return 0;
7277   }
7278
7279   // The re-extended constant changed so the constant cannot be represented 
7280   // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282   // First, handle some easy cases. We know the result cannot be equal at this
7283   // point so handle the ICI.isEquality() cases
7284   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7285     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7286   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7287     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7288
7289   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290   // should have been folded away previously and not enter in here.
7291   Value *Result;
7292   if (isSignedCmp) {
7293     // We're performing a signed comparison.
7294     if (cast<ConstantInt>(CI)->getValue().isNegative())
7295       Result = Context->getConstantIntFalse();          // X < (small) --> false
7296     else
7297       Result = Context->getConstantIntTrue();           // X < (large) --> true
7298   } else {
7299     // We're performing an unsigned comparison.
7300     if (isSignedExt) {
7301       // We're performing an unsigned comp with a sign extended value.
7302       // This is true if the input is >= 0. [aka >s -1]
7303       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7304       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7305                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7306     } else {
7307       // Unsigned extend & unsigned compare -> always true.
7308       Result = Context->getConstantIntTrue();
7309     }
7310   }
7311
7312   // Finally, return the value computed.
7313   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7314       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7315     return ReplaceInstUsesWith(ICI, Result);
7316
7317   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7318           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7319          "ICmp should be folded!");
7320   if (Constant *CI = dyn_cast<Constant>(Result))
7321     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7322   return BinaryOperator::CreateNot(*Context, Result);
7323 }
7324
7325 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7326   return commonShiftTransforms(I);
7327 }
7328
7329 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7330   return commonShiftTransforms(I);
7331 }
7332
7333 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7334   if (Instruction *R = commonShiftTransforms(I))
7335     return R;
7336   
7337   Value *Op0 = I.getOperand(0);
7338   
7339   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7340   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7341     if (CSI->isAllOnesValue())
7342       return ReplaceInstUsesWith(I, CSI);
7343
7344   // See if we can turn a signed shr into an unsigned shr.
7345   if (MaskedValueIsZero(Op0,
7346                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7347     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7348
7349   // Arithmetic shifting an all-sign-bit value is a no-op.
7350   unsigned NumSignBits = ComputeNumSignBits(Op0);
7351   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7352     return ReplaceInstUsesWith(I, Op0);
7353
7354   return 0;
7355 }
7356
7357 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7358   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7359   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7360
7361   // shl X, 0 == X and shr X, 0 == X
7362   // shl 0, X == 0 and shr 0, X == 0
7363   if (Op1 == Context->getNullValue(Op1->getType()) ||
7364       Op0 == Context->getNullValue(Op0->getType()))
7365     return ReplaceInstUsesWith(I, Op0);
7366   
7367   if (isa<UndefValue>(Op0)) {            
7368     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7369       return ReplaceInstUsesWith(I, Op0);
7370     else                                    // undef << X -> 0, undef >>u X -> 0
7371       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7372   }
7373   if (isa<UndefValue>(Op1)) {
7374     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7375       return ReplaceInstUsesWith(I, Op0);          
7376     else                                     // X << undef, X >>u undef -> 0
7377       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7378   }
7379
7380   // See if we can fold away this shift.
7381   if (SimplifyDemandedInstructionBits(I))
7382     return &I;
7383
7384   // Try to fold constant and into select arguments.
7385   if (isa<Constant>(Op0))
7386     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7387       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7388         return R;
7389
7390   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7391     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7392       return Res;
7393   return 0;
7394 }
7395
7396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7397                                                BinaryOperator &I) {
7398   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7399
7400   // See if we can simplify any instructions used by the instruction whose sole 
7401   // purpose is to compute bits we don't care about.
7402   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7403   
7404   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7405   // a signed shift.
7406   //
7407   if (Op1->uge(TypeBits)) {
7408     if (I.getOpcode() != Instruction::AShr)
7409       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7410     else {
7411       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7412       return &I;
7413     }
7414   }
7415   
7416   // ((X*C1) << C2) == (X * (C1 << C2))
7417   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7418     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7419       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7420         return BinaryOperator::CreateMul(BO->getOperand(0),
7421                                         Context->getConstantExprShl(BOOp, Op1));
7422   
7423   // Try to fold constant and into select arguments.
7424   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7425     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7426       return R;
7427   if (isa<PHINode>(Op0))
7428     if (Instruction *NV = FoldOpIntoPhi(I))
7429       return NV;
7430   
7431   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7432   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7433     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7434     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7435     // place.  Don't try to do this transformation in this case.  Also, we
7436     // require that the input operand is a shift-by-constant so that we have
7437     // confidence that the shifts will get folded together.  We could do this
7438     // xform in more cases, but it is unlikely to be profitable.
7439     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7440         isa<ConstantInt>(TrOp->getOperand(1))) {
7441       // Okay, we'll do this xform.  Make the shift of shift.
7442       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7443       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7444                                                 I.getName());
7445       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7446
7447       // For logical shifts, the truncation has the effect of making the high
7448       // part of the register be zeros.  Emulate this by inserting an AND to
7449       // clear the top bits as needed.  This 'and' will usually be zapped by
7450       // other xforms later if dead.
7451       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7452       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7453       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7454       
7455       // The mask we constructed says what the trunc would do if occurring
7456       // between the shifts.  We want to know the effect *after* the second
7457       // shift.  We know that it is a logical shift by a constant, so adjust the
7458       // mask as appropriate.
7459       if (I.getOpcode() == Instruction::Shl)
7460         MaskV <<= Op1->getZExtValue();
7461       else {
7462         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7463         MaskV = MaskV.lshr(Op1->getZExtValue());
7464       }
7465
7466       Instruction *And =
7467         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7468                                   TI->getName());
7469       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7470
7471       // Return the value truncated to the interesting size.
7472       return new TruncInst(And, I.getType());
7473     }
7474   }
7475   
7476   if (Op0->hasOneUse()) {
7477     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7478       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7479       Value *V1, *V2;
7480       ConstantInt *CC;
7481       switch (Op0BO->getOpcode()) {
7482         default: break;
7483         case Instruction::Add:
7484         case Instruction::And:
7485         case Instruction::Or:
7486         case Instruction::Xor: {
7487           // These operators commute.
7488           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7489           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7490               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7491                     m_Specific(Op1)), *Context)){
7492             Instruction *YS = BinaryOperator::CreateShl(
7493                                             Op0BO->getOperand(0), Op1,
7494                                             Op0BO->getName());
7495             InsertNewInstBefore(YS, I); // (Y << C)
7496             Instruction *X = 
7497               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7498                                      Op0BO->getOperand(1)->getName());
7499             InsertNewInstBefore(X, I);  // (X + (Y << C))
7500             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7501             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7502                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7503           }
7504           
7505           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7506           Value *Op0BOOp1 = Op0BO->getOperand(1);
7507           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7508               match(Op0BOOp1, 
7509                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7510                           m_ConstantInt(CC)), *Context) &&
7511               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7512             Instruction *YS = BinaryOperator::CreateShl(
7513                                                      Op0BO->getOperand(0), Op1,
7514                                                      Op0BO->getName());
7515             InsertNewInstBefore(YS, I); // (Y << C)
7516             Instruction *XM =
7517               BinaryOperator::CreateAnd(V1,
7518                                         Context->getConstantExprShl(CC, Op1),
7519                                         V1->getName()+".mask");
7520             InsertNewInstBefore(XM, I); // X & (CC << C)
7521             
7522             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7523           }
7524         }
7525           
7526         // FALL THROUGH.
7527         case Instruction::Sub: {
7528           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7529           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7530               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7531                     m_Specific(Op1)), *Context)){
7532             Instruction *YS = BinaryOperator::CreateShl(
7533                                                      Op0BO->getOperand(1), Op1,
7534                                                      Op0BO->getName());
7535             InsertNewInstBefore(YS, I); // (Y << C)
7536             Instruction *X =
7537               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7538                                      Op0BO->getOperand(0)->getName());
7539             InsertNewInstBefore(X, I);  // (X + (Y << C))
7540             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7541             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7542                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7543           }
7544           
7545           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7546           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7547               match(Op0BO->getOperand(0),
7548                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7549                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7550               cast<BinaryOperator>(Op0BO->getOperand(0))
7551                   ->getOperand(0)->hasOneUse()) {
7552             Instruction *YS = BinaryOperator::CreateShl(
7553                                                      Op0BO->getOperand(1), Op1,
7554                                                      Op0BO->getName());
7555             InsertNewInstBefore(YS, I); // (Y << C)
7556             Instruction *XM =
7557               BinaryOperator::CreateAnd(V1, 
7558                                         Context->getConstantExprShl(CC, Op1),
7559                                         V1->getName()+".mask");
7560             InsertNewInstBefore(XM, I); // X & (CC << C)
7561             
7562             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7563           }
7564           
7565           break;
7566         }
7567       }
7568       
7569       
7570       // If the operand is an bitwise operator with a constant RHS, and the
7571       // shift is the only use, we can pull it out of the shift.
7572       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7573         bool isValid = true;     // Valid only for And, Or, Xor
7574         bool highBitSet = false; // Transform if high bit of constant set?
7575         
7576         switch (Op0BO->getOpcode()) {
7577           default: isValid = false; break;   // Do not perform transform!
7578           case Instruction::Add:
7579             isValid = isLeftShift;
7580             break;
7581           case Instruction::Or:
7582           case Instruction::Xor:
7583             highBitSet = false;
7584             break;
7585           case Instruction::And:
7586             highBitSet = true;
7587             break;
7588         }
7589         
7590         // If this is a signed shift right, and the high bit is modified
7591         // by the logical operation, do not perform the transformation.
7592         // The highBitSet boolean indicates the value of the high bit of
7593         // the constant which would cause it to be modified for this
7594         // operation.
7595         //
7596         if (isValid && I.getOpcode() == Instruction::AShr)
7597           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7598         
7599         if (isValid) {
7600           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7601           
7602           Instruction *NewShift =
7603             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7604           InsertNewInstBefore(NewShift, I);
7605           NewShift->takeName(Op0BO);
7606           
7607           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7608                                         NewRHS);
7609         }
7610       }
7611     }
7612   }
7613   
7614   // Find out if this is a shift of a shift by a constant.
7615   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7616   if (ShiftOp && !ShiftOp->isShift())
7617     ShiftOp = 0;
7618   
7619   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7620     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7621     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7622     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7623     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7624     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7625     Value *X = ShiftOp->getOperand(0);
7626     
7627     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7628     
7629     const IntegerType *Ty = cast<IntegerType>(I.getType());
7630     
7631     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7632     if (I.getOpcode() == ShiftOp->getOpcode()) {
7633       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7634       // saturates.
7635       if (AmtSum >= TypeBits) {
7636         if (I.getOpcode() != Instruction::AShr)
7637           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7638         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7639       }
7640       
7641       return BinaryOperator::Create(I.getOpcode(), X,
7642                                     Context->getConstantInt(Ty, AmtSum));
7643     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7644                I.getOpcode() == Instruction::AShr) {
7645       if (AmtSum >= TypeBits)
7646         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7647       
7648       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7649       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7650     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7651                I.getOpcode() == Instruction::LShr) {
7652       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7653       if (AmtSum >= TypeBits)
7654         AmtSum = TypeBits-1;
7655       
7656       Instruction *Shift =
7657         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7658       InsertNewInstBefore(Shift, I);
7659
7660       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7661       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7662     }
7663     
7664     // Okay, if we get here, one shift must be left, and the other shift must be
7665     // right.  See if the amounts are equal.
7666     if (ShiftAmt1 == ShiftAmt2) {
7667       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7668       if (I.getOpcode() == Instruction::Shl) {
7669         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7670         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7671       }
7672       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7673       if (I.getOpcode() == Instruction::LShr) {
7674         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7675         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7676       }
7677       // We can simplify ((X << C) >>s C) into a trunc + sext.
7678       // NOTE: we could do this for any C, but that would make 'unusual' integer
7679       // types.  For now, just stick to ones well-supported by the code
7680       // generators.
7681       const Type *SExtType = 0;
7682       switch (Ty->getBitWidth() - ShiftAmt1) {
7683       case 1  :
7684       case 8  :
7685       case 16 :
7686       case 32 :
7687       case 64 :
7688       case 128:
7689         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7690         break;
7691       default: break;
7692       }
7693       if (SExtType) {
7694         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7695         InsertNewInstBefore(NewTrunc, I);
7696         return new SExtInst(NewTrunc, Ty);
7697       }
7698       // Otherwise, we can't handle it yet.
7699     } else if (ShiftAmt1 < ShiftAmt2) {
7700       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7701       
7702       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7703       if (I.getOpcode() == Instruction::Shl) {
7704         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705                ShiftOp->getOpcode() == Instruction::AShr);
7706         Instruction *Shift =
7707           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7708         InsertNewInstBefore(Shift, I);
7709         
7710         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7711         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7712       }
7713       
7714       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7715       if (I.getOpcode() == Instruction::LShr) {
7716         assert(ShiftOp->getOpcode() == Instruction::Shl);
7717         Instruction *Shift =
7718           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7719         InsertNewInstBefore(Shift, I);
7720         
7721         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7722         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7723       }
7724       
7725       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7726     } else {
7727       assert(ShiftAmt2 < ShiftAmt1);
7728       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7729
7730       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7731       if (I.getOpcode() == Instruction::Shl) {
7732         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7733                ShiftOp->getOpcode() == Instruction::AShr);
7734         Instruction *Shift =
7735           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7736                                  Context->getConstantInt(Ty, ShiftDiff));
7737         InsertNewInstBefore(Shift, I);
7738         
7739         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7740         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7741       }
7742       
7743       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7744       if (I.getOpcode() == Instruction::LShr) {
7745         assert(ShiftOp->getOpcode() == Instruction::Shl);
7746         Instruction *Shift =
7747           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7748         InsertNewInstBefore(Shift, I);
7749         
7750         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7751         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7752       }
7753       
7754       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7755     }
7756   }
7757   return 0;
7758 }
7759
7760
7761 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7762 /// expression.  If so, decompose it, returning some value X, such that Val is
7763 /// X*Scale+Offset.
7764 ///
7765 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7766                                         int &Offset, LLVMContext *Context) {
7767   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7768   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7769     Offset = CI->getZExtValue();
7770     Scale  = 0;
7771     return Context->getConstantInt(Type::Int32Ty, 0);
7772   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7773     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7774       if (I->getOpcode() == Instruction::Shl) {
7775         // This is a value scaled by '1 << the shift amt'.
7776         Scale = 1U << RHS->getZExtValue();
7777         Offset = 0;
7778         return I->getOperand(0);
7779       } else if (I->getOpcode() == Instruction::Mul) {
7780         // This value is scaled by 'RHS'.
7781         Scale = RHS->getZExtValue();
7782         Offset = 0;
7783         return I->getOperand(0);
7784       } else if (I->getOpcode() == Instruction::Add) {
7785         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7786         // where C1 is divisible by C2.
7787         unsigned SubScale;
7788         Value *SubVal = 
7789           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7790                                     Offset, Context);
7791         Offset += RHS->getZExtValue();
7792         Scale = SubScale;
7793         return SubVal;
7794       }
7795     }
7796   }
7797
7798   // Otherwise, we can't look past this.
7799   Scale = 1;
7800   Offset = 0;
7801   return Val;
7802 }
7803
7804
7805 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7806 /// try to eliminate the cast by moving the type information into the alloc.
7807 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7808                                                    AllocationInst &AI) {
7809   const PointerType *PTy = cast<PointerType>(CI.getType());
7810   
7811   // Remove any uses of AI that are dead.
7812   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7813   
7814   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7815     Instruction *User = cast<Instruction>(*UI++);
7816     if (isInstructionTriviallyDead(User)) {
7817       while (UI != E && *UI == User)
7818         ++UI; // If this instruction uses AI more than once, don't break UI.
7819       
7820       ++NumDeadInst;
7821       DOUT << "IC: DCE: " << *User;
7822       EraseInstFromFunction(*User);
7823     }
7824   }
7825   
7826   // Get the type really allocated and the type casted to.
7827   const Type *AllocElTy = AI.getAllocatedType();
7828   const Type *CastElTy = PTy->getElementType();
7829   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7830
7831   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7832   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7833   if (CastElTyAlign < AllocElTyAlign) return 0;
7834
7835   // If the allocation has multiple uses, only promote it if we are strictly
7836   // increasing the alignment of the resultant allocation.  If we keep it the
7837   // same, we open the door to infinite loops of various kinds.  (A reference
7838   // from a dbg.declare doesn't count as a use for this purpose.)
7839   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7840       CastElTyAlign == AllocElTyAlign) return 0;
7841
7842   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7843   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7844   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7845
7846   // See if we can satisfy the modulus by pulling a scale out of the array
7847   // size argument.
7848   unsigned ArraySizeScale;
7849   int ArrayOffset;
7850   Value *NumElements = // See if the array size is a decomposable linear expr.
7851     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7852                               ArrayOffset, Context);
7853  
7854   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7855   // do the xform.
7856   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7857       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7858
7859   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7860   Value *Amt = 0;
7861   if (Scale == 1) {
7862     Amt = NumElements;
7863   } else {
7864     // If the allocation size is constant, form a constant mul expression
7865     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7866     if (isa<ConstantInt>(NumElements))
7867       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7868                                  cast<ConstantInt>(Amt));
7869     // otherwise multiply the amount and the number of elements
7870     else {
7871       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7872       Amt = InsertNewInstBefore(Tmp, AI);
7873     }
7874   }
7875   
7876   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7877     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7878     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7879     Amt = InsertNewInstBefore(Tmp, AI);
7880   }
7881   
7882   AllocationInst *New;
7883   if (isa<MallocInst>(AI))
7884     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7885   else
7886     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7887   InsertNewInstBefore(New, AI);
7888   New->takeName(&AI);
7889   
7890   // If the allocation has one real use plus a dbg.declare, just remove the
7891   // declare.
7892   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7893     EraseInstFromFunction(*DI);
7894   }
7895   // If the allocation has multiple real uses, insert a cast and change all
7896   // things that used it to use the new cast.  This will also hack on CI, but it
7897   // will die soon.
7898   else if (!AI.hasOneUse()) {
7899     AddUsesToWorkList(AI);
7900     // New is the allocation instruction, pointer typed. AI is the original
7901     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7902     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7903     InsertNewInstBefore(NewCast, AI);
7904     AI.replaceAllUsesWith(NewCast);
7905   }
7906   return ReplaceInstUsesWith(CI, New);
7907 }
7908
7909 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7910 /// and return it as type Ty without inserting any new casts and without
7911 /// changing the computed value.  This is used by code that tries to decide
7912 /// whether promoting or shrinking integer operations to wider or smaller types
7913 /// will allow us to eliminate a truncate or extend.
7914 ///
7915 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7916 /// extension operation if Ty is larger.
7917 ///
7918 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7919 /// should return true if trunc(V) can be computed by computing V in the smaller
7920 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7921 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7922 /// efficiently truncated.
7923 ///
7924 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7925 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7926 /// the final result.
7927 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7928                                               unsigned CastOpc,
7929                                               int &NumCastsRemoved){
7930   // We can always evaluate constants in another type.
7931   if (isa<Constant>(V))
7932     return true;
7933   
7934   Instruction *I = dyn_cast<Instruction>(V);
7935   if (!I) return false;
7936   
7937   const Type *OrigTy = V->getType();
7938   
7939   // If this is an extension or truncate, we can often eliminate it.
7940   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7941     // If this is a cast from the destination type, we can trivially eliminate
7942     // it, and this will remove a cast overall.
7943     if (I->getOperand(0)->getType() == Ty) {
7944       // If the first operand is itself a cast, and is eliminable, do not count
7945       // this as an eliminable cast.  We would prefer to eliminate those two
7946       // casts first.
7947       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7948         ++NumCastsRemoved;
7949       return true;
7950     }
7951   }
7952
7953   // We can't extend or shrink something that has multiple uses: doing so would
7954   // require duplicating the instruction in general, which isn't profitable.
7955   if (!I->hasOneUse()) return false;
7956
7957   unsigned Opc = I->getOpcode();
7958   switch (Opc) {
7959   case Instruction::Add:
7960   case Instruction::Sub:
7961   case Instruction::Mul:
7962   case Instruction::And:
7963   case Instruction::Or:
7964   case Instruction::Xor:
7965     // These operators can all arbitrarily be extended or truncated.
7966     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7967                                       NumCastsRemoved) &&
7968            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7969                                       NumCastsRemoved);
7970
7971   case Instruction::UDiv:
7972   case Instruction::URem: {
7973     // UDiv and URem can be truncated if all the truncated bits are zero.
7974     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975     uint32_t BitWidth = Ty->getScalarSizeInBits();
7976     if (BitWidth < OrigBitWidth) {
7977       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7978       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7979           MaskedValueIsZero(I->getOperand(1), Mask)) {
7980         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7981                                           NumCastsRemoved) &&
7982                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7983                                           NumCastsRemoved);
7984       }
7985     }
7986     break;
7987   }
7988   case Instruction::Shl:
7989     // If we are truncating the result of this SHL, and if it's a shift of a
7990     // constant amount, we can always perform a SHL in a smaller type.
7991     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7992       uint32_t BitWidth = Ty->getScalarSizeInBits();
7993       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7994           CI->getLimitedValue(BitWidth) < BitWidth)
7995         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7996                                           NumCastsRemoved);
7997     }
7998     break;
7999   case Instruction::LShr:
8000     // If this is a truncate of a logical shr, we can truncate it to a smaller
8001     // lshr iff we know that the bits we would otherwise be shifting in are
8002     // already zeros.
8003     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8004       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8005       uint32_t BitWidth = Ty->getScalarSizeInBits();
8006       if (BitWidth < OrigBitWidth &&
8007           MaskedValueIsZero(I->getOperand(0),
8008             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8009           CI->getLimitedValue(BitWidth) < BitWidth) {
8010         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8011                                           NumCastsRemoved);
8012       }
8013     }
8014     break;
8015   case Instruction::ZExt:
8016   case Instruction::SExt:
8017   case Instruction::Trunc:
8018     // If this is the same kind of case as our original (e.g. zext+zext), we
8019     // can safely replace it.  Note that replacing it does not reduce the number
8020     // of casts in the input.
8021     if (Opc == CastOpc)
8022       return true;
8023
8024     // sext (zext ty1), ty2 -> zext ty2
8025     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8026       return true;
8027     break;
8028   case Instruction::Select: {
8029     SelectInst *SI = cast<SelectInst>(I);
8030     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8031                                       NumCastsRemoved) &&
8032            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8033                                       NumCastsRemoved);
8034   }
8035   case Instruction::PHI: {
8036     // We can change a phi if we can change all operands.
8037     PHINode *PN = cast<PHINode>(I);
8038     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8039       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8040                                       NumCastsRemoved))
8041         return false;
8042     return true;
8043   }
8044   default:
8045     // TODO: Can handle more cases here.
8046     break;
8047   }
8048   
8049   return false;
8050 }
8051
8052 /// EvaluateInDifferentType - Given an expression that 
8053 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8054 /// evaluate the expression.
8055 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8056                                              bool isSigned) {
8057   if (Constant *C = dyn_cast<Constant>(V))
8058     return Context->getConstantExprIntegerCast(C, Ty,
8059                                                isSigned /*Sext or ZExt*/);
8060
8061   // Otherwise, it must be an instruction.
8062   Instruction *I = cast<Instruction>(V);
8063   Instruction *Res = 0;
8064   unsigned Opc = I->getOpcode();
8065   switch (Opc) {
8066   case Instruction::Add:
8067   case Instruction::Sub:
8068   case Instruction::Mul:
8069   case Instruction::And:
8070   case Instruction::Or:
8071   case Instruction::Xor:
8072   case Instruction::AShr:
8073   case Instruction::LShr:
8074   case Instruction::Shl:
8075   case Instruction::UDiv:
8076   case Instruction::URem: {
8077     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8078     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8079     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8080     break;
8081   }    
8082   case Instruction::Trunc:
8083   case Instruction::ZExt:
8084   case Instruction::SExt:
8085     // If the source type of the cast is the type we're trying for then we can
8086     // just return the source.  There's no need to insert it because it is not
8087     // new.
8088     if (I->getOperand(0)->getType() == Ty)
8089       return I->getOperand(0);
8090     
8091     // Otherwise, must be the same type of cast, so just reinsert a new one.
8092     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8093                            Ty);
8094     break;
8095   case Instruction::Select: {
8096     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8097     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8098     Res = SelectInst::Create(I->getOperand(0), True, False);
8099     break;
8100   }
8101   case Instruction::PHI: {
8102     PHINode *OPN = cast<PHINode>(I);
8103     PHINode *NPN = PHINode::Create(Ty);
8104     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8105       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8106       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8107     }
8108     Res = NPN;
8109     break;
8110   }
8111   default: 
8112     // TODO: Can handle more cases here.
8113     llvm_unreachable("Unreachable!");
8114     break;
8115   }
8116   
8117   Res->takeName(I);
8118   return InsertNewInstBefore(Res, *I);
8119 }
8120
8121 /// @brief Implement the transforms common to all CastInst visitors.
8122 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8123   Value *Src = CI.getOperand(0);
8124
8125   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8126   // eliminate it now.
8127   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8128     if (Instruction::CastOps opc = 
8129         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8130       // The first cast (CSrc) is eliminable so we need to fix up or replace
8131       // the second cast (CI). CSrc will then have a good chance of being dead.
8132       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8133     }
8134   }
8135
8136   // If we are casting a select then fold the cast into the select
8137   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8138     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8139       return NV;
8140
8141   // If we are casting a PHI then fold the cast into the PHI
8142   if (isa<PHINode>(Src))
8143     if (Instruction *NV = FoldOpIntoPhi(CI))
8144       return NV;
8145   
8146   return 0;
8147 }
8148
8149 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8150 /// or not there is a sequence of GEP indices into the type that will land us at
8151 /// the specified offset.  If so, fill them into NewIndices and return the
8152 /// resultant element type, otherwise return null.
8153 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8154                                        SmallVectorImpl<Value*> &NewIndices,
8155                                        const TargetData *TD,
8156                                        LLVMContext *Context) {
8157   if (!Ty->isSized()) return 0;
8158   
8159   // Start with the index over the outer type.  Note that the type size
8160   // might be zero (even if the offset isn't zero) if the indexed type
8161   // is something like [0 x {int, int}]
8162   const Type *IntPtrTy = TD->getIntPtrType();
8163   int64_t FirstIdx = 0;
8164   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8165     FirstIdx = Offset/TySize;
8166     Offset -= FirstIdx*TySize;
8167     
8168     // Handle hosts where % returns negative instead of values [0..TySize).
8169     if (Offset < 0) {
8170       --FirstIdx;
8171       Offset += TySize;
8172       assert(Offset >= 0);
8173     }
8174     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8175   }
8176   
8177   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8178     
8179   // Index into the types.  If we fail, set OrigBase to null.
8180   while (Offset) {
8181     // Indexing into tail padding between struct/array elements.
8182     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8183       return 0;
8184     
8185     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8186       const StructLayout *SL = TD->getStructLayout(STy);
8187       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8188              "Offset must stay within the indexed type");
8189       
8190       unsigned Elt = SL->getElementContainingOffset(Offset);
8191       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8192       
8193       Offset -= SL->getElementOffset(Elt);
8194       Ty = STy->getElementType(Elt);
8195     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8196       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8197       assert(EltSize && "Cannot index into a zero-sized array");
8198       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8199       Offset %= EltSize;
8200       Ty = AT->getElementType();
8201     } else {
8202       // Otherwise, we can't index into the middle of this atomic type, bail.
8203       return 0;
8204     }
8205   }
8206   
8207   return Ty;
8208 }
8209
8210 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8211 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8212   Value *Src = CI.getOperand(0);
8213   
8214   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8215     // If casting the result of a getelementptr instruction with no offset, turn
8216     // this into a cast of the original pointer!
8217     if (GEP->hasAllZeroIndices()) {
8218       // Changing the cast operand is usually not a good idea but it is safe
8219       // here because the pointer operand is being replaced with another 
8220       // pointer operand so the opcode doesn't need to change.
8221       AddToWorkList(GEP);
8222       CI.setOperand(0, GEP->getOperand(0));
8223       return &CI;
8224     }
8225     
8226     // If the GEP has a single use, and the base pointer is a bitcast, and the
8227     // GEP computes a constant offset, see if we can convert these three
8228     // instructions into fewer.  This typically happens with unions and other
8229     // non-type-safe code.
8230     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8231       if (GEP->hasAllConstantIndices()) {
8232         // We are guaranteed to get a constant from EmitGEPOffset.
8233         ConstantInt *OffsetV =
8234                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8235         int64_t Offset = OffsetV->getSExtValue();
8236         
8237         // Get the base pointer input of the bitcast, and the type it points to.
8238         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8239         const Type *GEPIdxTy =
8240           cast<PointerType>(OrigBase->getType())->getElementType();
8241         SmallVector<Value*, 8> NewIndices;
8242         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8243           // If we were able to index down into an element, create the GEP
8244           // and bitcast the result.  This eliminates one bitcast, potentially
8245           // two.
8246           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8247                                                         NewIndices.begin(),
8248                                                         NewIndices.end(), "");
8249           InsertNewInstBefore(NGEP, CI);
8250           NGEP->takeName(GEP);
8251           
8252           if (isa<BitCastInst>(CI))
8253             return new BitCastInst(NGEP, CI.getType());
8254           assert(isa<PtrToIntInst>(CI));
8255           return new PtrToIntInst(NGEP, CI.getType());
8256         }
8257       }      
8258     }
8259   }
8260     
8261   return commonCastTransforms(CI);
8262 }
8263
8264 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8265 /// type like i42.  We don't want to introduce operations on random non-legal
8266 /// integer types where they don't already exist in the code.  In the future,
8267 /// we should consider making this based off target-data, so that 32-bit targets
8268 /// won't get i64 operations etc.
8269 static bool isSafeIntegerType(const Type *Ty) {
8270   switch (Ty->getPrimitiveSizeInBits()) {
8271   case 8:
8272   case 16:
8273   case 32:
8274   case 64:
8275     return true;
8276   default: 
8277     return false;
8278   }
8279 }
8280
8281 /// commonIntCastTransforms - This function implements the common transforms
8282 /// for trunc, zext, and sext.
8283 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8284   if (Instruction *Result = commonCastTransforms(CI))
8285     return Result;
8286
8287   Value *Src = CI.getOperand(0);
8288   const Type *SrcTy = Src->getType();
8289   const Type *DestTy = CI.getType();
8290   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8291   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8292
8293   // See if we can simplify any instructions used by the LHS whose sole 
8294   // purpose is to compute bits we don't care about.
8295   if (SimplifyDemandedInstructionBits(CI))
8296     return &CI;
8297
8298   // If the source isn't an instruction or has more than one use then we
8299   // can't do anything more. 
8300   Instruction *SrcI = dyn_cast<Instruction>(Src);
8301   if (!SrcI || !Src->hasOneUse())
8302     return 0;
8303
8304   // Attempt to propagate the cast into the instruction for int->int casts.
8305   int NumCastsRemoved = 0;
8306   // Only do this if the dest type is a simple type, don't convert the
8307   // expression tree to something weird like i93 unless the source is also
8308   // strange.
8309   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8310        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8311       CanEvaluateInDifferentType(SrcI, DestTy,
8312                                  CI.getOpcode(), NumCastsRemoved)) {
8313     // If this cast is a truncate, evaluting in a different type always
8314     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8315     // we need to do an AND to maintain the clear top-part of the computation,
8316     // so we require that the input have eliminated at least one cast.  If this
8317     // is a sign extension, we insert two new casts (to do the extension) so we
8318     // require that two casts have been eliminated.
8319     bool DoXForm = false;
8320     bool JustReplace = false;
8321     switch (CI.getOpcode()) {
8322     default:
8323       // All the others use floating point so we shouldn't actually 
8324       // get here because of the check above.
8325       llvm_unreachable("Unknown cast type");
8326     case Instruction::Trunc:
8327       DoXForm = true;
8328       break;
8329     case Instruction::ZExt: {
8330       DoXForm = NumCastsRemoved >= 1;
8331       if (!DoXForm && 0) {
8332         // If it's unnecessary to issue an AND to clear the high bits, it's
8333         // always profitable to do this xform.
8334         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8335         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8336         if (MaskedValueIsZero(TryRes, Mask))
8337           return ReplaceInstUsesWith(CI, TryRes);
8338         
8339         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8340           if (TryI->use_empty())
8341             EraseInstFromFunction(*TryI);
8342       }
8343       break;
8344     }
8345     case Instruction::SExt: {
8346       DoXForm = NumCastsRemoved >= 2;
8347       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8348         // If we do not have to emit the truncate + sext pair, then it's always
8349         // profitable to do this xform.
8350         //
8351         // It's not safe to eliminate the trunc + sext pair if one of the
8352         // eliminated cast is a truncate. e.g.
8353         // t2 = trunc i32 t1 to i16
8354         // t3 = sext i16 t2 to i32
8355         // !=
8356         // i32 t1
8357         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8358         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8359         if (NumSignBits > (DestBitSize - SrcBitSize))
8360           return ReplaceInstUsesWith(CI, TryRes);
8361         
8362         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8363           if (TryI->use_empty())
8364             EraseInstFromFunction(*TryI);
8365       }
8366       break;
8367     }
8368     }
8369     
8370     if (DoXForm) {
8371       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8372            << " cast: " << CI;
8373       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8374                                            CI.getOpcode() == Instruction::SExt);
8375       if (JustReplace)
8376         // Just replace this cast with the result.
8377         return ReplaceInstUsesWith(CI, Res);
8378
8379       assert(Res->getType() == DestTy);
8380       switch (CI.getOpcode()) {
8381       default: llvm_unreachable("Unknown cast type!");
8382       case Instruction::Trunc:
8383         // Just replace this cast with the result.
8384         return ReplaceInstUsesWith(CI, Res);
8385       case Instruction::ZExt: {
8386         assert(SrcBitSize < DestBitSize && "Not a zext?");
8387
8388         // If the high bits are already zero, just replace this cast with the
8389         // result.
8390         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8391         if (MaskedValueIsZero(Res, Mask))
8392           return ReplaceInstUsesWith(CI, Res);
8393
8394         // We need to emit an AND to clear the high bits.
8395         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8396                                                             SrcBitSize));
8397         return BinaryOperator::CreateAnd(Res, C);
8398       }
8399       case Instruction::SExt: {
8400         // If the high bits are already filled with sign bit, just replace this
8401         // cast with the result.
8402         unsigned NumSignBits = ComputeNumSignBits(Res);
8403         if (NumSignBits > (DestBitSize - SrcBitSize))
8404           return ReplaceInstUsesWith(CI, Res);
8405
8406         // We need to emit a cast to truncate, then a cast to sext.
8407         return CastInst::Create(Instruction::SExt,
8408             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8409                              CI), DestTy);
8410       }
8411       }
8412     }
8413   }
8414   
8415   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8416   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8417
8418   switch (SrcI->getOpcode()) {
8419   case Instruction::Add:
8420   case Instruction::Mul:
8421   case Instruction::And:
8422   case Instruction::Or:
8423   case Instruction::Xor:
8424     // If we are discarding information, rewrite.
8425     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8426       // Don't insert two casts unless at least one can be eliminated.
8427       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8428           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8429         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8430         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8431         return BinaryOperator::Create(
8432             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8433       }
8434     }
8435
8436     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8437     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8438         SrcI->getOpcode() == Instruction::Xor &&
8439         Op1 == Context->getConstantIntTrue() &&
8440         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8441       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8442       return BinaryOperator::CreateXor(New,
8443                                       Context->getConstantInt(CI.getType(), 1));
8444     }
8445     break;
8446
8447   case Instruction::Shl: {
8448     // Canonicalize trunc inside shl, if we can.
8449     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8450     if (CI && DestBitSize < SrcBitSize &&
8451         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8452       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8453       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8454       return BinaryOperator::CreateShl(Op0c, Op1c);
8455     }
8456     break;
8457   }
8458   }
8459   return 0;
8460 }
8461
8462 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8463   if (Instruction *Result = commonIntCastTransforms(CI))
8464     return Result;
8465   
8466   Value *Src = CI.getOperand(0);
8467   const Type *Ty = CI.getType();
8468   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8469   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8470
8471   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8472   if (DestBitWidth == 1 &&
8473       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8474     Constant *One = Context->getConstantInt(Src->getType(), 1);
8475     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8476     Value *Zero = Context->getNullValue(Src->getType());
8477     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8478   }
8479
8480   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8481   ConstantInt *ShAmtV = 0;
8482   Value *ShiftOp = 0;
8483   if (Src->hasOneUse() &&
8484       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8485     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8486     
8487     // Get a mask for the bits shifting in.
8488     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8489     if (MaskedValueIsZero(ShiftOp, Mask)) {
8490       if (ShAmt >= DestBitWidth)        // All zeros.
8491         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8492       
8493       // Okay, we can shrink this.  Truncate the input, then return a new
8494       // shift.
8495       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8496       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8497       return BinaryOperator::CreateLShr(V1, V2);
8498     }
8499   }
8500   
8501   return 0;
8502 }
8503
8504 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8505 /// in order to eliminate the icmp.
8506 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8507                                              bool DoXform) {
8508   // If we are just checking for a icmp eq of a single bit and zext'ing it
8509   // to an integer, then shift the bit to the appropriate place and then
8510   // cast to integer to avoid the comparison.
8511   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8512     const APInt &Op1CV = Op1C->getValue();
8513       
8514     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8515     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8516     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8517         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8518       if (!DoXform) return ICI;
8519
8520       Value *In = ICI->getOperand(0);
8521       Value *Sh = Context->getConstantInt(In->getType(),
8522                                    In->getType()->getScalarSizeInBits()-1);
8523       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8524                                                         In->getName()+".lobit"),
8525                                CI);
8526       if (In->getType() != CI.getType())
8527         In = CastInst::CreateIntegerCast(In, CI.getType(),
8528                                          false/*ZExt*/, "tmp", &CI);
8529
8530       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8531         Constant *One = Context->getConstantInt(In->getType(), 1);
8532         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8533                                                          In->getName()+".not"),
8534                                  CI);
8535       }
8536
8537       return ReplaceInstUsesWith(CI, In);
8538     }
8539       
8540       
8541       
8542     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8543     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8544     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8545     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8546     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8547     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8548     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8549     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8550     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8551         // This only works for EQ and NE
8552         ICI->isEquality()) {
8553       // If Op1C some other power of two, convert:
8554       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8555       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8556       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8557       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8558         
8559       APInt KnownZeroMask(~KnownZero);
8560       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8561         if (!DoXform) return ICI;
8562
8563         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8564         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8565           // (X&4) == 2 --> false
8566           // (X&4) != 2 --> true
8567           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8568           Res = Context->getConstantExprZExt(Res, CI.getType());
8569           return ReplaceInstUsesWith(CI, Res);
8570         }
8571           
8572         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8573         Value *In = ICI->getOperand(0);
8574         if (ShiftAmt) {
8575           // Perform a logical shr by shiftamt.
8576           // Insert the shift to put the result in the low bit.
8577           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8578                               Context->getConstantInt(In->getType(), ShiftAmt),
8579                                                    In->getName()+".lobit"), CI);
8580         }
8581           
8582         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8583           Constant *One = Context->getConstantInt(In->getType(), 1);
8584           In = BinaryOperator::CreateXor(In, One, "tmp");
8585           InsertNewInstBefore(cast<Instruction>(In), CI);
8586         }
8587           
8588         if (CI.getType() == In->getType())
8589           return ReplaceInstUsesWith(CI, In);
8590         else
8591           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8592       }
8593     }
8594   }
8595
8596   return 0;
8597 }
8598
8599 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8600   // If one of the common conversion will work ..
8601   if (Instruction *Result = commonIntCastTransforms(CI))
8602     return Result;
8603
8604   Value *Src = CI.getOperand(0);
8605
8606   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8607   // types and if the sizes are just right we can convert this into a logical
8608   // 'and' which will be much cheaper than the pair of casts.
8609   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8610     // Get the sizes of the types involved.  We know that the intermediate type
8611     // will be smaller than A or C, but don't know the relation between A and C.
8612     Value *A = CSrc->getOperand(0);
8613     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8614     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8615     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8616     // If we're actually extending zero bits, then if
8617     // SrcSize <  DstSize: zext(a & mask)
8618     // SrcSize == DstSize: a & mask
8619     // SrcSize  > DstSize: trunc(a) & mask
8620     if (SrcSize < DstSize) {
8621       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8622       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8623       Instruction *And =
8624         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8625       InsertNewInstBefore(And, CI);
8626       return new ZExtInst(And, CI.getType());
8627     } else if (SrcSize == DstSize) {
8628       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8629       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8630                                                            AndValue));
8631     } else if (SrcSize > DstSize) {
8632       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8633       InsertNewInstBefore(Trunc, CI);
8634       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8635       return BinaryOperator::CreateAnd(Trunc, 
8636                                        Context->getConstantInt(Trunc->getType(),
8637                                                                AndValue));
8638     }
8639   }
8640
8641   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8642     return transformZExtICmp(ICI, CI);
8643
8644   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8645   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8646     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8647     // of the (zext icmp) will be transformed.
8648     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8649     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8650     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8651         (transformZExtICmp(LHS, CI, false) ||
8652          transformZExtICmp(RHS, CI, false))) {
8653       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8654       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8655       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8656     }
8657   }
8658
8659   // zext(trunc(t) & C) -> (t & zext(C)).
8660   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8661     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8662       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8663         Value *TI0 = TI->getOperand(0);
8664         if (TI0->getType() == CI.getType())
8665           return
8666             BinaryOperator::CreateAnd(TI0,
8667                                 Context->getConstantExprZExt(C, CI.getType()));
8668       }
8669
8670   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8671   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8672     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8673       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8674         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8675             And->getOperand(1) == C)
8676           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8677             Value *TI0 = TI->getOperand(0);
8678             if (TI0->getType() == CI.getType()) {
8679               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8680               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8681               InsertNewInstBefore(NewAnd, *And);
8682               return BinaryOperator::CreateXor(NewAnd, ZC);
8683             }
8684           }
8685
8686   return 0;
8687 }
8688
8689 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8690   if (Instruction *I = commonIntCastTransforms(CI))
8691     return I;
8692   
8693   Value *Src = CI.getOperand(0);
8694   
8695   // Canonicalize sign-extend from i1 to a select.
8696   if (Src->getType() == Type::Int1Ty)
8697     return SelectInst::Create(Src,
8698                               Context->getAllOnesValue(CI.getType()),
8699                               Context->getNullValue(CI.getType()));
8700
8701   // See if the value being truncated is already sign extended.  If so, just
8702   // eliminate the trunc/sext pair.
8703   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8704     Value *Op = cast<User>(Src)->getOperand(0);
8705     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8706     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8707     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8708     unsigned NumSignBits = ComputeNumSignBits(Op);
8709
8710     if (OpBits == DestBits) {
8711       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8712       // bits, it is already ready.
8713       if (NumSignBits > DestBits-MidBits)
8714         return ReplaceInstUsesWith(CI, Op);
8715     } else if (OpBits < DestBits) {
8716       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8717       // bits, just sext from i32.
8718       if (NumSignBits > OpBits-MidBits)
8719         return new SExtInst(Op, CI.getType(), "tmp");
8720     } else {
8721       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8722       // bits, just truncate to i32.
8723       if (NumSignBits > OpBits-MidBits)
8724         return new TruncInst(Op, CI.getType(), "tmp");
8725     }
8726   }
8727
8728   // If the input is a shl/ashr pair of a same constant, then this is a sign
8729   // extension from a smaller value.  If we could trust arbitrary bitwidth
8730   // integers, we could turn this into a truncate to the smaller bit and then
8731   // use a sext for the whole extension.  Since we don't, look deeper and check
8732   // for a truncate.  If the source and dest are the same type, eliminate the
8733   // trunc and extend and just do shifts.  For example, turn:
8734   //   %a = trunc i32 %i to i8
8735   //   %b = shl i8 %a, 6
8736   //   %c = ashr i8 %b, 6
8737   //   %d = sext i8 %c to i32
8738   // into:
8739   //   %a = shl i32 %i, 30
8740   //   %d = ashr i32 %a, 30
8741   Value *A = 0;
8742   ConstantInt *BA = 0, *CA = 0;
8743   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8744                         m_ConstantInt(CA)), *Context) &&
8745       BA == CA && isa<TruncInst>(A)) {
8746     Value *I = cast<TruncInst>(A)->getOperand(0);
8747     if (I->getType() == CI.getType()) {
8748       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8749       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8750       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8751       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8752       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8753                                                         CI.getName()), CI);
8754       return BinaryOperator::CreateAShr(I, ShAmtV);
8755     }
8756   }
8757   
8758   return 0;
8759 }
8760
8761 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8762 /// in the specified FP type without changing its value.
8763 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8764                               LLVMContext *Context) {
8765   bool losesInfo;
8766   APFloat F = CFP->getValueAPF();
8767   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8768   if (!losesInfo)
8769     return Context->getConstantFP(F);
8770   return 0;
8771 }
8772
8773 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8774 /// through it until we get the source value.
8775 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8776   if (Instruction *I = dyn_cast<Instruction>(V))
8777     if (I->getOpcode() == Instruction::FPExt)
8778       return LookThroughFPExtensions(I->getOperand(0), Context);
8779   
8780   // If this value is a constant, return the constant in the smallest FP type
8781   // that can accurately represent it.  This allows us to turn
8782   // (float)((double)X+2.0) into x+2.0f.
8783   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8784     if (CFP->getType() == Type::PPC_FP128Ty)
8785       return V;  // No constant folding of this.
8786     // See if the value can be truncated to float and then reextended.
8787     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8788       return V;
8789     if (CFP->getType() == Type::DoubleTy)
8790       return V;  // Won't shrink.
8791     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8792       return V;
8793     // Don't try to shrink to various long double types.
8794   }
8795   
8796   return V;
8797 }
8798
8799 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8800   if (Instruction *I = commonCastTransforms(CI))
8801     return I;
8802   
8803   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8804   // smaller than the destination type, we can eliminate the truncate by doing
8805   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8806   // many builtins (sqrt, etc).
8807   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8808   if (OpI && OpI->hasOneUse()) {
8809     switch (OpI->getOpcode()) {
8810     default: break;
8811     case Instruction::FAdd:
8812     case Instruction::FSub:
8813     case Instruction::FMul:
8814     case Instruction::FDiv:
8815     case Instruction::FRem:
8816       const Type *SrcTy = OpI->getType();
8817       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8818       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8819       if (LHSTrunc->getType() != SrcTy && 
8820           RHSTrunc->getType() != SrcTy) {
8821         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8822         // If the source types were both smaller than the destination type of
8823         // the cast, do this xform.
8824         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8825             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8826           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8827                                       CI.getType(), CI);
8828           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8829                                       CI.getType(), CI);
8830           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8831         }
8832       }
8833       break;  
8834     }
8835   }
8836   return 0;
8837 }
8838
8839 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8840   return commonCastTransforms(CI);
8841 }
8842
8843 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8844   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8845   if (OpI == 0)
8846     return commonCastTransforms(FI);
8847
8848   // fptoui(uitofp(X)) --> X
8849   // fptoui(sitofp(X)) --> X
8850   // This is safe if the intermediate type has enough bits in its mantissa to
8851   // accurately represent all values of X.  For example, do not do this with
8852   // i64->float->i64.  This is also safe for sitofp case, because any negative
8853   // 'X' value would cause an undefined result for the fptoui. 
8854   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8855       OpI->getOperand(0)->getType() == FI.getType() &&
8856       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8857                     OpI->getType()->getFPMantissaWidth())
8858     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8859
8860   return commonCastTransforms(FI);
8861 }
8862
8863 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8864   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8865   if (OpI == 0)
8866     return commonCastTransforms(FI);
8867   
8868   // fptosi(sitofp(X)) --> X
8869   // fptosi(uitofp(X)) --> X
8870   // This is safe if the intermediate type has enough bits in its mantissa to
8871   // accurately represent all values of X.  For example, do not do this with
8872   // i64->float->i64.  This is also safe for sitofp case, because any negative
8873   // 'X' value would cause an undefined result for the fptoui. 
8874   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8875       OpI->getOperand(0)->getType() == FI.getType() &&
8876       (int)FI.getType()->getScalarSizeInBits() <=
8877                     OpI->getType()->getFPMantissaWidth())
8878     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8879   
8880   return commonCastTransforms(FI);
8881 }
8882
8883 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8884   return commonCastTransforms(CI);
8885 }
8886
8887 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8888   return commonCastTransforms(CI);
8889 }
8890
8891 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8892   // If the destination integer type is smaller than the intptr_t type for
8893   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8894   // trunc to be exposed to other transforms.  Don't do this for extending
8895   // ptrtoint's, because we don't know if the target sign or zero extends its
8896   // pointers.
8897   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8898     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8899                                                     TD->getIntPtrType(),
8900                                                     "tmp"), CI);
8901     return new TruncInst(P, CI.getType());
8902   }
8903   
8904   return commonPointerCastTransforms(CI);
8905 }
8906
8907 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8908   // If the source integer type is larger than the intptr_t type for
8909   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8910   // allows the trunc to be exposed to other transforms.  Don't do this for
8911   // extending inttoptr's, because we don't know if the target sign or zero
8912   // extends to pointers.
8913   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8914       TD->getPointerSizeInBits()) {
8915     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8916                                                  TD->getIntPtrType(),
8917                                                  "tmp"), CI);
8918     return new IntToPtrInst(P, CI.getType());
8919   }
8920   
8921   if (Instruction *I = commonCastTransforms(CI))
8922     return I;
8923   
8924   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8925   if (!DestPointee->isSized()) return 0;
8926
8927   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8928   ConstantInt *Cst;
8929   Value *X;
8930   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8931                                     m_ConstantInt(Cst)), *Context)) {
8932     // If the source and destination operands have the same type, see if this
8933     // is a single-index GEP.
8934     if (X->getType() == CI.getType()) {
8935       // Get the size of the pointee type.
8936       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8937
8938       // Convert the constant to intptr type.
8939       APInt Offset = Cst->getValue();
8940       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8941
8942       // If Offset is evenly divisible by Size, we can do this xform.
8943       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8944         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8945         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8946       }
8947     }
8948     // TODO: Could handle other cases, e.g. where add is indexing into field of
8949     // struct etc.
8950   } else if (CI.getOperand(0)->hasOneUse() &&
8951              match(CI.getOperand(0), m_Add(m_Value(X),
8952                    m_ConstantInt(Cst)), *Context)) {
8953     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8954     // "inttoptr+GEP" instead of "add+intptr".
8955     
8956     // Get the size of the pointee type.
8957     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8958     
8959     // Convert the constant to intptr type.
8960     APInt Offset = Cst->getValue();
8961     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8962     
8963     // If Offset is evenly divisible by Size, we can do this xform.
8964     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8965       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8966       
8967       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8968                                                             "tmp"), CI);
8969       return GetElementPtrInst::Create(P,
8970                                        Context->getConstantInt(Offset), "tmp");
8971     }
8972   }
8973   return 0;
8974 }
8975
8976 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8977   // If the operands are integer typed then apply the integer transforms,
8978   // otherwise just apply the common ones.
8979   Value *Src = CI.getOperand(0);
8980   const Type *SrcTy = Src->getType();
8981   const Type *DestTy = CI.getType();
8982
8983   if (isa<PointerType>(SrcTy)) {
8984     if (Instruction *I = commonPointerCastTransforms(CI))
8985       return I;
8986   } else {
8987     if (Instruction *Result = commonCastTransforms(CI))
8988       return Result;
8989   }
8990
8991
8992   // Get rid of casts from one type to the same type. These are useless and can
8993   // be replaced by the operand.
8994   if (DestTy == Src->getType())
8995     return ReplaceInstUsesWith(CI, Src);
8996
8997   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8998     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8999     const Type *DstElTy = DstPTy->getElementType();
9000     const Type *SrcElTy = SrcPTy->getElementType();
9001     
9002     // If the address spaces don't match, don't eliminate the bitcast, which is
9003     // required for changing types.
9004     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9005       return 0;
9006     
9007     // If we are casting a malloc or alloca to a pointer to a type of the same
9008     // size, rewrite the allocation instruction to allocate the "right" type.
9009     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9010       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9011         return V;
9012     
9013     // If the source and destination are pointers, and this cast is equivalent
9014     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9015     // This can enhance SROA and other transforms that want type-safe pointers.
9016     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9017     unsigned NumZeros = 0;
9018     while (SrcElTy != DstElTy && 
9019            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9020            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9021       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9022       ++NumZeros;
9023     }
9024
9025     // If we found a path from the src to dest, create the getelementptr now.
9026     if (SrcElTy == DstElTy) {
9027       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9028       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9029                                        ((Instruction*) NULL));
9030     }
9031   }
9032
9033   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9034     if (SVI->hasOneUse()) {
9035       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9036       // a bitconvert to a vector with the same # elts.
9037       if (isa<VectorType>(DestTy) && 
9038           cast<VectorType>(DestTy)->getNumElements() ==
9039                 SVI->getType()->getNumElements() &&
9040           SVI->getType()->getNumElements() ==
9041             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9042         CastInst *Tmp;
9043         // If either of the operands is a cast from CI.getType(), then
9044         // evaluating the shuffle in the casted destination's type will allow
9045         // us to eliminate at least one cast.
9046         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9047              Tmp->getOperand(0)->getType() == DestTy) ||
9048             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9049              Tmp->getOperand(0)->getType() == DestTy)) {
9050           Value *LHS = InsertCastBefore(Instruction::BitCast,
9051                                         SVI->getOperand(0), DestTy, CI);
9052           Value *RHS = InsertCastBefore(Instruction::BitCast,
9053                                         SVI->getOperand(1), DestTy, CI);
9054           // Return a new shuffle vector.  Use the same element ID's, as we
9055           // know the vector types match #elts.
9056           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9057         }
9058       }
9059     }
9060   }
9061   return 0;
9062 }
9063
9064 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9065 ///   %C = or %A, %B
9066 ///   %D = select %cond, %C, %A
9067 /// into:
9068 ///   %C = select %cond, %B, 0
9069 ///   %D = or %A, %C
9070 ///
9071 /// Assuming that the specified instruction is an operand to the select, return
9072 /// a bitmask indicating which operands of this instruction are foldable if they
9073 /// equal the other incoming value of the select.
9074 ///
9075 static unsigned GetSelectFoldableOperands(Instruction *I) {
9076   switch (I->getOpcode()) {
9077   case Instruction::Add:
9078   case Instruction::Mul:
9079   case Instruction::And:
9080   case Instruction::Or:
9081   case Instruction::Xor:
9082     return 3;              // Can fold through either operand.
9083   case Instruction::Sub:   // Can only fold on the amount subtracted.
9084   case Instruction::Shl:   // Can only fold on the shift amount.
9085   case Instruction::LShr:
9086   case Instruction::AShr:
9087     return 1;
9088   default:
9089     return 0;              // Cannot fold
9090   }
9091 }
9092
9093 /// GetSelectFoldableConstant - For the same transformation as the previous
9094 /// function, return the identity constant that goes into the select.
9095 static Constant *GetSelectFoldableConstant(Instruction *I,
9096                                            LLVMContext *Context) {
9097   switch (I->getOpcode()) {
9098   default: llvm_unreachable("This cannot happen!");
9099   case Instruction::Add:
9100   case Instruction::Sub:
9101   case Instruction::Or:
9102   case Instruction::Xor:
9103   case Instruction::Shl:
9104   case Instruction::LShr:
9105   case Instruction::AShr:
9106     return Context->getNullValue(I->getType());
9107   case Instruction::And:
9108     return Context->getAllOnesValue(I->getType());
9109   case Instruction::Mul:
9110     return Context->getConstantInt(I->getType(), 1);
9111   }
9112 }
9113
9114 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9115 /// have the same opcode and only one use each.  Try to simplify this.
9116 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9117                                           Instruction *FI) {
9118   if (TI->getNumOperands() == 1) {
9119     // If this is a non-volatile load or a cast from the same type,
9120     // merge.
9121     if (TI->isCast()) {
9122       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9123         return 0;
9124     } else {
9125       return 0;  // unknown unary op.
9126     }
9127
9128     // Fold this by inserting a select from the input values.
9129     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9130                                            FI->getOperand(0), SI.getName()+".v");
9131     InsertNewInstBefore(NewSI, SI);
9132     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9133                             TI->getType());
9134   }
9135
9136   // Only handle binary operators here.
9137   if (!isa<BinaryOperator>(TI))
9138     return 0;
9139
9140   // Figure out if the operations have any operands in common.
9141   Value *MatchOp, *OtherOpT, *OtherOpF;
9142   bool MatchIsOpZero;
9143   if (TI->getOperand(0) == FI->getOperand(0)) {
9144     MatchOp  = TI->getOperand(0);
9145     OtherOpT = TI->getOperand(1);
9146     OtherOpF = FI->getOperand(1);
9147     MatchIsOpZero = true;
9148   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9149     MatchOp  = TI->getOperand(1);
9150     OtherOpT = TI->getOperand(0);
9151     OtherOpF = FI->getOperand(0);
9152     MatchIsOpZero = false;
9153   } else if (!TI->isCommutative()) {
9154     return 0;
9155   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9156     MatchOp  = TI->getOperand(0);
9157     OtherOpT = TI->getOperand(1);
9158     OtherOpF = FI->getOperand(0);
9159     MatchIsOpZero = true;
9160   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9161     MatchOp  = TI->getOperand(1);
9162     OtherOpT = TI->getOperand(0);
9163     OtherOpF = FI->getOperand(1);
9164     MatchIsOpZero = true;
9165   } else {
9166     return 0;
9167   }
9168
9169   // If we reach here, they do have operations in common.
9170   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9171                                          OtherOpF, SI.getName()+".v");
9172   InsertNewInstBefore(NewSI, SI);
9173
9174   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9175     if (MatchIsOpZero)
9176       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9177     else
9178       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9179   }
9180   llvm_unreachable("Shouldn't get here");
9181   return 0;
9182 }
9183
9184 static bool isSelect01(Constant *C1, Constant *C2) {
9185   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9186   if (!C1I)
9187     return false;
9188   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9189   if (!C2I)
9190     return false;
9191   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9192 }
9193
9194 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9195 /// facilitate further optimization.
9196 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9197                                             Value *FalseVal) {
9198   // See the comment above GetSelectFoldableOperands for a description of the
9199   // transformation we are doing here.
9200   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9201     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9202         !isa<Constant>(FalseVal)) {
9203       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9204         unsigned OpToFold = 0;
9205         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9206           OpToFold = 1;
9207         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9208           OpToFold = 2;
9209         }
9210
9211         if (OpToFold) {
9212           Constant *C = GetSelectFoldableConstant(TVI, Context);
9213           Value *OOp = TVI->getOperand(2-OpToFold);
9214           // Avoid creating select between 2 constants unless it's selecting
9215           // between 0 and 1.
9216           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9217             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9218             InsertNewInstBefore(NewSel, SI);
9219             NewSel->takeName(TVI);
9220             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9221               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9222             llvm_unreachable("Unknown instruction!!");
9223           }
9224         }
9225       }
9226     }
9227   }
9228
9229   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9230     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9231         !isa<Constant>(TrueVal)) {
9232       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9233         unsigned OpToFold = 0;
9234         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9235           OpToFold = 1;
9236         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9237           OpToFold = 2;
9238         }
9239
9240         if (OpToFold) {
9241           Constant *C = GetSelectFoldableConstant(FVI, Context);
9242           Value *OOp = FVI->getOperand(2-OpToFold);
9243           // Avoid creating select between 2 constants unless it's selecting
9244           // between 0 and 1.
9245           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9246             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9247             InsertNewInstBefore(NewSel, SI);
9248             NewSel->takeName(FVI);
9249             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9250               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9251             llvm_unreachable("Unknown instruction!!");
9252           }
9253         }
9254       }
9255     }
9256   }
9257
9258   return 0;
9259 }
9260
9261 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9262 /// ICmpInst as its first operand.
9263 ///
9264 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9265                                                    ICmpInst *ICI) {
9266   bool Changed = false;
9267   ICmpInst::Predicate Pred = ICI->getPredicate();
9268   Value *CmpLHS = ICI->getOperand(0);
9269   Value *CmpRHS = ICI->getOperand(1);
9270   Value *TrueVal = SI.getTrueValue();
9271   Value *FalseVal = SI.getFalseValue();
9272
9273   // Check cases where the comparison is with a constant that
9274   // can be adjusted to fit the min/max idiom. We may edit ICI in
9275   // place here, so make sure the select is the only user.
9276   if (ICI->hasOneUse())
9277     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9278       switch (Pred) {
9279       default: break;
9280       case ICmpInst::ICMP_ULT:
9281       case ICmpInst::ICMP_SLT: {
9282         // X < MIN ? T : F  -->  F
9283         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9284           return ReplaceInstUsesWith(SI, FalseVal);
9285         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9286         Constant *AdjustedRHS = SubOne(CI, Context);
9287         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9288             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9289           Pred = ICmpInst::getSwappedPredicate(Pred);
9290           CmpRHS = AdjustedRHS;
9291           std::swap(FalseVal, TrueVal);
9292           ICI->setPredicate(Pred);
9293           ICI->setOperand(1, CmpRHS);
9294           SI.setOperand(1, TrueVal);
9295           SI.setOperand(2, FalseVal);
9296           Changed = true;
9297         }
9298         break;
9299       }
9300       case ICmpInst::ICMP_UGT:
9301       case ICmpInst::ICMP_SGT: {
9302         // X > MAX ? T : F  -->  F
9303         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9304           return ReplaceInstUsesWith(SI, FalseVal);
9305         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9306         Constant *AdjustedRHS = AddOne(CI, Context);
9307         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9308             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9309           Pred = ICmpInst::getSwappedPredicate(Pred);
9310           CmpRHS = AdjustedRHS;
9311           std::swap(FalseVal, TrueVal);
9312           ICI->setPredicate(Pred);
9313           ICI->setOperand(1, CmpRHS);
9314           SI.setOperand(1, TrueVal);
9315           SI.setOperand(2, FalseVal);
9316           Changed = true;
9317         }
9318         break;
9319       }
9320       }
9321
9322       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9323       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9324       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9325       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9326           match(FalseVal, m_ConstantInt<0>(), *Context))
9327         Pred = ICI->getPredicate();
9328       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9329                match(FalseVal, m_ConstantInt<-1>(), *Context))
9330         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9331       
9332       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9333         // If we are just checking for a icmp eq of a single bit and zext'ing it
9334         // to an integer, then shift the bit to the appropriate place and then
9335         // cast to integer to avoid the comparison.
9336         const APInt &Op1CV = CI->getValue();
9337     
9338         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9339         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9340         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9341             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9342           Value *In = ICI->getOperand(0);
9343           Value *Sh = Context->getConstantInt(In->getType(),
9344                                        In->getType()->getScalarSizeInBits()-1);
9345           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9346                                                           In->getName()+".lobit"),
9347                                    *ICI);
9348           if (In->getType() != SI.getType())
9349             In = CastInst::CreateIntegerCast(In, SI.getType(),
9350                                              true/*SExt*/, "tmp", ICI);
9351     
9352           if (Pred == ICmpInst::ICMP_SGT)
9353             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9354                                        In->getName()+".not"), *ICI);
9355     
9356           return ReplaceInstUsesWith(SI, In);
9357         }
9358       }
9359     }
9360
9361   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9362     // Transform (X == Y) ? X : Y  -> Y
9363     if (Pred == ICmpInst::ICMP_EQ)
9364       return ReplaceInstUsesWith(SI, FalseVal);
9365     // Transform (X != Y) ? X : Y  -> X
9366     if (Pred == ICmpInst::ICMP_NE)
9367       return ReplaceInstUsesWith(SI, TrueVal);
9368     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9369
9370   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9371     // Transform (X == Y) ? Y : X  -> X
9372     if (Pred == ICmpInst::ICMP_EQ)
9373       return ReplaceInstUsesWith(SI, FalseVal);
9374     // Transform (X != Y) ? Y : X  -> Y
9375     if (Pred == ICmpInst::ICMP_NE)
9376       return ReplaceInstUsesWith(SI, TrueVal);
9377     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9378   }
9379
9380   /// NOTE: if we wanted to, this is where to detect integer ABS
9381
9382   return Changed ? &SI : 0;
9383 }
9384
9385 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9386   Value *CondVal = SI.getCondition();
9387   Value *TrueVal = SI.getTrueValue();
9388   Value *FalseVal = SI.getFalseValue();
9389
9390   // select true, X, Y  -> X
9391   // select false, X, Y -> Y
9392   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9393     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9394
9395   // select C, X, X -> X
9396   if (TrueVal == FalseVal)
9397     return ReplaceInstUsesWith(SI, TrueVal);
9398
9399   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9400     return ReplaceInstUsesWith(SI, FalseVal);
9401   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9402     return ReplaceInstUsesWith(SI, TrueVal);
9403   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9404     if (isa<Constant>(TrueVal))
9405       return ReplaceInstUsesWith(SI, TrueVal);
9406     else
9407       return ReplaceInstUsesWith(SI, FalseVal);
9408   }
9409
9410   if (SI.getType() == Type::Int1Ty) {
9411     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9412       if (C->getZExtValue()) {
9413         // Change: A = select B, true, C --> A = or B, C
9414         return BinaryOperator::CreateOr(CondVal, FalseVal);
9415       } else {
9416         // Change: A = select B, false, C --> A = and !B, C
9417         Value *NotCond =
9418           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9419                                              "not."+CondVal->getName()), SI);
9420         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9421       }
9422     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9423       if (C->getZExtValue() == false) {
9424         // Change: A = select B, C, false --> A = and B, C
9425         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9426       } else {
9427         // Change: A = select B, C, true --> A = or !B, C
9428         Value *NotCond =
9429           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9430                                              "not."+CondVal->getName()), SI);
9431         return BinaryOperator::CreateOr(NotCond, TrueVal);
9432       }
9433     }
9434     
9435     // select a, b, a  -> a&b
9436     // select a, a, b  -> a|b
9437     if (CondVal == TrueVal)
9438       return BinaryOperator::CreateOr(CondVal, FalseVal);
9439     else if (CondVal == FalseVal)
9440       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9441   }
9442
9443   // Selecting between two integer constants?
9444   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9445     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9446       // select C, 1, 0 -> zext C to int
9447       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9448         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9449       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9450         // select C, 0, 1 -> zext !C to int
9451         Value *NotCond =
9452           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9453                                                "not."+CondVal->getName()), SI);
9454         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9455       }
9456
9457       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9458         // If one of the constants is zero (we know they can't both be) and we
9459         // have an icmp instruction with zero, and we have an 'and' with the
9460         // non-constant value, eliminate this whole mess.  This corresponds to
9461         // cases like this: ((X & 27) ? 27 : 0)
9462         if (TrueValC->isZero() || FalseValC->isZero())
9463           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9464               cast<Constant>(IC->getOperand(1))->isNullValue())
9465             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9466               if (ICA->getOpcode() == Instruction::And &&
9467                   isa<ConstantInt>(ICA->getOperand(1)) &&
9468                   (ICA->getOperand(1) == TrueValC ||
9469                    ICA->getOperand(1) == FalseValC) &&
9470                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9471                 // Okay, now we know that everything is set up, we just don't
9472                 // know whether we have a icmp_ne or icmp_eq and whether the 
9473                 // true or false val is the zero.
9474                 bool ShouldNotVal = !TrueValC->isZero();
9475                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9476                 Value *V = ICA;
9477                 if (ShouldNotVal)
9478                   V = InsertNewInstBefore(BinaryOperator::Create(
9479                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9480                 return ReplaceInstUsesWith(SI, V);
9481               }
9482       }
9483     }
9484
9485   // See if we are selecting two values based on a comparison of the two values.
9486   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9487     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9488       // Transform (X == Y) ? X : Y  -> Y
9489       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9490         // This is not safe in general for floating point:  
9491         // consider X== -0, Y== +0.
9492         // It becomes safe if either operand is a nonzero constant.
9493         ConstantFP *CFPt, *CFPf;
9494         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9495               !CFPt->getValueAPF().isZero()) ||
9496             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9497              !CFPf->getValueAPF().isZero()))
9498         return ReplaceInstUsesWith(SI, FalseVal);
9499       }
9500       // Transform (X != Y) ? X : Y  -> X
9501       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9502         return ReplaceInstUsesWith(SI, TrueVal);
9503       // NOTE: if we wanted to, this is where to detect MIN/MAX
9504
9505     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9506       // Transform (X == Y) ? Y : X  -> X
9507       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9508         // This is not safe in general for floating point:  
9509         // consider X== -0, Y== +0.
9510         // It becomes safe if either operand is a nonzero constant.
9511         ConstantFP *CFPt, *CFPf;
9512         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9513               !CFPt->getValueAPF().isZero()) ||
9514             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9515              !CFPf->getValueAPF().isZero()))
9516           return ReplaceInstUsesWith(SI, FalseVal);
9517       }
9518       // Transform (X != Y) ? Y : X  -> Y
9519       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9520         return ReplaceInstUsesWith(SI, TrueVal);
9521       // NOTE: if we wanted to, this is where to detect MIN/MAX
9522     }
9523     // NOTE: if we wanted to, this is where to detect ABS
9524   }
9525
9526   // See if we are selecting two values based on a comparison of the two values.
9527   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9528     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9529       return Result;
9530
9531   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9532     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9533       if (TI->hasOneUse() && FI->hasOneUse()) {
9534         Instruction *AddOp = 0, *SubOp = 0;
9535
9536         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9537         if (TI->getOpcode() == FI->getOpcode())
9538           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9539             return IV;
9540
9541         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9542         // even legal for FP.
9543         if ((TI->getOpcode() == Instruction::Sub &&
9544              FI->getOpcode() == Instruction::Add) ||
9545             (TI->getOpcode() == Instruction::FSub &&
9546              FI->getOpcode() == Instruction::FAdd)) {
9547           AddOp = FI; SubOp = TI;
9548         } else if ((FI->getOpcode() == Instruction::Sub &&
9549                     TI->getOpcode() == Instruction::Add) ||
9550                    (FI->getOpcode() == Instruction::FSub &&
9551                     TI->getOpcode() == Instruction::FAdd)) {
9552           AddOp = TI; SubOp = FI;
9553         }
9554
9555         if (AddOp) {
9556           Value *OtherAddOp = 0;
9557           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9558             OtherAddOp = AddOp->getOperand(1);
9559           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9560             OtherAddOp = AddOp->getOperand(0);
9561           }
9562
9563           if (OtherAddOp) {
9564             // So at this point we know we have (Y -> OtherAddOp):
9565             //        select C, (add X, Y), (sub X, Z)
9566             Value *NegVal;  // Compute -Z
9567             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9568               NegVal = Context->getConstantExprNeg(C);
9569             } else {
9570               NegVal = InsertNewInstBefore(
9571                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9572                                               "tmp"), SI);
9573             }
9574
9575             Value *NewTrueOp = OtherAddOp;
9576             Value *NewFalseOp = NegVal;
9577             if (AddOp != TI)
9578               std::swap(NewTrueOp, NewFalseOp);
9579             Instruction *NewSel =
9580               SelectInst::Create(CondVal, NewTrueOp,
9581                                  NewFalseOp, SI.getName() + ".p");
9582
9583             NewSel = InsertNewInstBefore(NewSel, SI);
9584             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9585           }
9586         }
9587       }
9588
9589   // See if we can fold the select into one of our operands.
9590   if (SI.getType()->isInteger()) {
9591     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9592     if (FoldI)
9593       return FoldI;
9594   }
9595
9596   if (BinaryOperator::isNot(CondVal)) {
9597     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9598     SI.setOperand(1, FalseVal);
9599     SI.setOperand(2, TrueVal);
9600     return &SI;
9601   }
9602
9603   return 0;
9604 }
9605
9606 /// EnforceKnownAlignment - If the specified pointer points to an object that
9607 /// we control, modify the object's alignment to PrefAlign. This isn't
9608 /// often possible though. If alignment is important, a more reliable approach
9609 /// is to simply align all global variables and allocation instructions to
9610 /// their preferred alignment from the beginning.
9611 ///
9612 static unsigned EnforceKnownAlignment(Value *V,
9613                                       unsigned Align, unsigned PrefAlign) {
9614
9615   User *U = dyn_cast<User>(V);
9616   if (!U) return Align;
9617
9618   switch (Operator::getOpcode(U)) {
9619   default: break;
9620   case Instruction::BitCast:
9621     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9622   case Instruction::GetElementPtr: {
9623     // If all indexes are zero, it is just the alignment of the base pointer.
9624     bool AllZeroOperands = true;
9625     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9626       if (!isa<Constant>(*i) ||
9627           !cast<Constant>(*i)->isNullValue()) {
9628         AllZeroOperands = false;
9629         break;
9630       }
9631
9632     if (AllZeroOperands) {
9633       // Treat this like a bitcast.
9634       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9635     }
9636     break;
9637   }
9638   }
9639
9640   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9641     // If there is a large requested alignment and we can, bump up the alignment
9642     // of the global.
9643     if (!GV->isDeclaration()) {
9644       if (GV->getAlignment() >= PrefAlign)
9645         Align = GV->getAlignment();
9646       else {
9647         GV->setAlignment(PrefAlign);
9648         Align = PrefAlign;
9649       }
9650     }
9651   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9652     // If there is a requested alignment and if this is an alloca, round up.  We
9653     // don't do this for malloc, because some systems can't respect the request.
9654     if (isa<AllocaInst>(AI)) {
9655       if (AI->getAlignment() >= PrefAlign)
9656         Align = AI->getAlignment();
9657       else {
9658         AI->setAlignment(PrefAlign);
9659         Align = PrefAlign;
9660       }
9661     }
9662   }
9663
9664   return Align;
9665 }
9666
9667 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9668 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9669 /// and it is more than the alignment of the ultimate object, see if we can
9670 /// increase the alignment of the ultimate object, making this check succeed.
9671 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9672                                                   unsigned PrefAlign) {
9673   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9674                       sizeof(PrefAlign) * CHAR_BIT;
9675   APInt Mask = APInt::getAllOnesValue(BitWidth);
9676   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9677   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9678   unsigned TrailZ = KnownZero.countTrailingOnes();
9679   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9680
9681   if (PrefAlign > Align)
9682     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9683   
9684     // We don't need to make any adjustment.
9685   return Align;
9686 }
9687
9688 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9689   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9690   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9691   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9692   unsigned CopyAlign = MI->getAlignment();
9693
9694   if (CopyAlign < MinAlign) {
9695     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9696                                              MinAlign, false));
9697     return MI;
9698   }
9699   
9700   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9701   // load/store.
9702   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9703   if (MemOpLength == 0) return 0;
9704   
9705   // Source and destination pointer types are always "i8*" for intrinsic.  See
9706   // if the size is something we can handle with a single primitive load/store.
9707   // A single load+store correctly handles overlapping memory in the memmove
9708   // case.
9709   unsigned Size = MemOpLength->getZExtValue();
9710   if (Size == 0) return MI;  // Delete this mem transfer.
9711   
9712   if (Size > 8 || (Size&(Size-1)))
9713     return 0;  // If not 1/2/4/8 bytes, exit.
9714   
9715   // Use an integer load+store unless we can find something better.
9716   Type *NewPtrTy =
9717                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9718   
9719   // Memcpy forces the use of i8* for the source and destination.  That means
9720   // that if you're using memcpy to move one double around, you'll get a cast
9721   // from double* to i8*.  We'd much rather use a double load+store rather than
9722   // an i64 load+store, here because this improves the odds that the source or
9723   // dest address will be promotable.  See if we can find a better type than the
9724   // integer datatype.
9725   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9726     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9727     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9728       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9729       // down through these levels if so.
9730       while (!SrcETy->isSingleValueType()) {
9731         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9732           if (STy->getNumElements() == 1)
9733             SrcETy = STy->getElementType(0);
9734           else
9735             break;
9736         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9737           if (ATy->getNumElements() == 1)
9738             SrcETy = ATy->getElementType();
9739           else
9740             break;
9741         } else
9742           break;
9743       }
9744       
9745       if (SrcETy->isSingleValueType())
9746         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9747     }
9748   }
9749   
9750   
9751   // If the memcpy/memmove provides better alignment info than we can
9752   // infer, use it.
9753   SrcAlign = std::max(SrcAlign, CopyAlign);
9754   DstAlign = std::max(DstAlign, CopyAlign);
9755   
9756   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9757   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9758   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9759   InsertNewInstBefore(L, *MI);
9760   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9761
9762   // Set the size of the copy to 0, it will be deleted on the next iteration.
9763   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9764   return MI;
9765 }
9766
9767 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9768   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9769   if (MI->getAlignment() < Alignment) {
9770     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9771                                              Alignment, false));
9772     return MI;
9773   }
9774   
9775   // Extract the length and alignment and fill if they are constant.
9776   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9777   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9778   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9779     return 0;
9780   uint64_t Len = LenC->getZExtValue();
9781   Alignment = MI->getAlignment();
9782   
9783   // If the length is zero, this is a no-op
9784   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9785   
9786   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9787   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9788     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9789     
9790     Value *Dest = MI->getDest();
9791     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9792
9793     // Alignment 0 is identity for alignment 1 for memset, but not store.
9794     if (Alignment == 0) Alignment = 1;
9795     
9796     // Extract the fill value and store.
9797     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9798     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9799                                       Dest, false, Alignment), *MI);
9800     
9801     // Set the size of the copy to 0, it will be deleted on the next iteration.
9802     MI->setLength(Context->getNullValue(LenC->getType()));
9803     return MI;
9804   }
9805
9806   return 0;
9807 }
9808
9809
9810 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9811 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9812 /// the heavy lifting.
9813 ///
9814 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9815   // If the caller function is nounwind, mark the call as nounwind, even if the
9816   // callee isn't.
9817   if (CI.getParent()->getParent()->doesNotThrow() &&
9818       !CI.doesNotThrow()) {
9819     CI.setDoesNotThrow();
9820     return &CI;
9821   }
9822   
9823   
9824   
9825   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9826   if (!II) return visitCallSite(&CI);
9827   
9828   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9829   // visitCallSite.
9830   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9831     bool Changed = false;
9832
9833     // memmove/cpy/set of zero bytes is a noop.
9834     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9835       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9836
9837       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9838         if (CI->getZExtValue() == 1) {
9839           // Replace the instruction with just byte operations.  We would
9840           // transform other cases to loads/stores, but we don't know if
9841           // alignment is sufficient.
9842         }
9843     }
9844
9845     // If we have a memmove and the source operation is a constant global,
9846     // then the source and dest pointers can't alias, so we can change this
9847     // into a call to memcpy.
9848     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9849       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9850         if (GVSrc->isConstant()) {
9851           Module *M = CI.getParent()->getParent()->getParent();
9852           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9853           const Type *Tys[1];
9854           Tys[0] = CI.getOperand(3)->getType();
9855           CI.setOperand(0, 
9856                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9857           Changed = true;
9858         }
9859
9860       // memmove(x,x,size) -> noop.
9861       if (MMI->getSource() == MMI->getDest())
9862         return EraseInstFromFunction(CI);
9863     }
9864
9865     // If we can determine a pointer alignment that is bigger than currently
9866     // set, update the alignment.
9867     if (isa<MemTransferInst>(MI)) {
9868       if (Instruction *I = SimplifyMemTransfer(MI))
9869         return I;
9870     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9871       if (Instruction *I = SimplifyMemSet(MSI))
9872         return I;
9873     }
9874           
9875     if (Changed) return II;
9876   }
9877   
9878   switch (II->getIntrinsicID()) {
9879   default: break;
9880   case Intrinsic::bswap:
9881     // bswap(bswap(x)) -> x
9882     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9883       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9884         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9885     break;
9886   case Intrinsic::ppc_altivec_lvx:
9887   case Intrinsic::ppc_altivec_lvxl:
9888   case Intrinsic::x86_sse_loadu_ps:
9889   case Intrinsic::x86_sse2_loadu_pd:
9890   case Intrinsic::x86_sse2_loadu_dq:
9891     // Turn PPC lvx     -> load if the pointer is known aligned.
9892     // Turn X86 loadups -> load if the pointer is known aligned.
9893     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9894       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9895                                    Context->getPointerTypeUnqual(II->getType()),
9896                                        CI);
9897       return new LoadInst(Ptr);
9898     }
9899     break;
9900   case Intrinsic::ppc_altivec_stvx:
9901   case Intrinsic::ppc_altivec_stvxl:
9902     // Turn stvx -> store if the pointer is known aligned.
9903     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9904       const Type *OpPtrTy = 
9905         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9906       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9907       return new StoreInst(II->getOperand(1), Ptr);
9908     }
9909     break;
9910   case Intrinsic::x86_sse_storeu_ps:
9911   case Intrinsic::x86_sse2_storeu_pd:
9912   case Intrinsic::x86_sse2_storeu_dq:
9913     // Turn X86 storeu -> store if the pointer is known aligned.
9914     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9915       const Type *OpPtrTy = 
9916         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9917       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9918       return new StoreInst(II->getOperand(2), Ptr);
9919     }
9920     break;
9921     
9922   case Intrinsic::x86_sse_cvttss2si: {
9923     // These intrinsics only demands the 0th element of its input vector.  If
9924     // we can simplify the input based on that, do so now.
9925     unsigned VWidth =
9926       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9927     APInt DemandedElts(VWidth, 1);
9928     APInt UndefElts(VWidth, 0);
9929     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9930                                               UndefElts)) {
9931       II->setOperand(1, V);
9932       return II;
9933     }
9934     break;
9935   }
9936     
9937   case Intrinsic::ppc_altivec_vperm:
9938     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9939     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9940       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9941       
9942       // Check that all of the elements are integer constants or undefs.
9943       bool AllEltsOk = true;
9944       for (unsigned i = 0; i != 16; ++i) {
9945         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9946             !isa<UndefValue>(Mask->getOperand(i))) {
9947           AllEltsOk = false;
9948           break;
9949         }
9950       }
9951       
9952       if (AllEltsOk) {
9953         // Cast the input vectors to byte vectors.
9954         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9955         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9956         Value *Result = Context->getUndef(Op0->getType());
9957         
9958         // Only extract each element once.
9959         Value *ExtractedElts[32];
9960         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9961         
9962         for (unsigned i = 0; i != 16; ++i) {
9963           if (isa<UndefValue>(Mask->getOperand(i)))
9964             continue;
9965           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9966           Idx &= 31;  // Match the hardware behavior.
9967           
9968           if (ExtractedElts[Idx] == 0) {
9969             Instruction *Elt = 
9970               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9971                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9972             InsertNewInstBefore(Elt, CI);
9973             ExtractedElts[Idx] = Elt;
9974           }
9975         
9976           // Insert this value into the result vector.
9977           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9978                                Context->getConstantInt(Type::Int32Ty, i, false), 
9979                                "tmp");
9980           InsertNewInstBefore(cast<Instruction>(Result), CI);
9981         }
9982         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9983       }
9984     }
9985     break;
9986
9987   case Intrinsic::stackrestore: {
9988     // If the save is right next to the restore, remove the restore.  This can
9989     // happen when variable allocas are DCE'd.
9990     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9991       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9992         BasicBlock::iterator BI = SS;
9993         if (&*++BI == II)
9994           return EraseInstFromFunction(CI);
9995       }
9996     }
9997     
9998     // Scan down this block to see if there is another stack restore in the
9999     // same block without an intervening call/alloca.
10000     BasicBlock::iterator BI = II;
10001     TerminatorInst *TI = II->getParent()->getTerminator();
10002     bool CannotRemove = false;
10003     for (++BI; &*BI != TI; ++BI) {
10004       if (isa<AllocaInst>(BI)) {
10005         CannotRemove = true;
10006         break;
10007       }
10008       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10009         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10010           // If there is a stackrestore below this one, remove this one.
10011           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10012             return EraseInstFromFunction(CI);
10013           // Otherwise, ignore the intrinsic.
10014         } else {
10015           // If we found a non-intrinsic call, we can't remove the stack
10016           // restore.
10017           CannotRemove = true;
10018           break;
10019         }
10020       }
10021     }
10022     
10023     // If the stack restore is in a return/unwind block and if there are no
10024     // allocas or calls between the restore and the return, nuke the restore.
10025     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10026       return EraseInstFromFunction(CI);
10027     break;
10028   }
10029   }
10030
10031   return visitCallSite(II);
10032 }
10033
10034 // InvokeInst simplification
10035 //
10036 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10037   return visitCallSite(&II);
10038 }
10039
10040 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10041 /// passed through the varargs area, we can eliminate the use of the cast.
10042 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10043                                          const CastInst * const CI,
10044                                          const TargetData * const TD,
10045                                          const int ix) {
10046   if (!CI->isLosslessCast())
10047     return false;
10048
10049   // The size of ByVal arguments is derived from the type, so we
10050   // can't change to a type with a different size.  If the size were
10051   // passed explicitly we could avoid this check.
10052   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10053     return true;
10054
10055   const Type* SrcTy = 
10056             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10057   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10058   if (!SrcTy->isSized() || !DstTy->isSized())
10059     return false;
10060   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10061     return false;
10062   return true;
10063 }
10064
10065 // visitCallSite - Improvements for call and invoke instructions.
10066 //
10067 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10068   bool Changed = false;
10069
10070   // If the callee is a constexpr cast of a function, attempt to move the cast
10071   // to the arguments of the call/invoke.
10072   if (transformConstExprCastCall(CS)) return 0;
10073
10074   Value *Callee = CS.getCalledValue();
10075
10076   if (Function *CalleeF = dyn_cast<Function>(Callee))
10077     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10078       Instruction *OldCall = CS.getInstruction();
10079       // If the call and callee calling conventions don't match, this call must
10080       // be unreachable, as the call is undefined.
10081       new StoreInst(Context->getConstantIntTrue(),
10082                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10083                                   OldCall);
10084       if (!OldCall->use_empty())
10085         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10086       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10087         return EraseInstFromFunction(*OldCall);
10088       return 0;
10089     }
10090
10091   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10092     // This instruction is not reachable, just remove it.  We insert a store to
10093     // undef so that we know that this code is not reachable, despite the fact
10094     // that we can't modify the CFG here.
10095     new StoreInst(Context->getConstantIntTrue(),
10096                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10097                   CS.getInstruction());
10098
10099     if (!CS.getInstruction()->use_empty())
10100       CS.getInstruction()->
10101         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10102
10103     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10104       // Don't break the CFG, insert a dummy cond branch.
10105       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10106                          Context->getConstantIntTrue(), II);
10107     }
10108     return EraseInstFromFunction(*CS.getInstruction());
10109   }
10110
10111   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10112     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10113       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10114         return transformCallThroughTrampoline(CS);
10115
10116   const PointerType *PTy = cast<PointerType>(Callee->getType());
10117   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10118   if (FTy->isVarArg()) {
10119     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10120     // See if we can optimize any arguments passed through the varargs area of
10121     // the call.
10122     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10123            E = CS.arg_end(); I != E; ++I, ++ix) {
10124       CastInst *CI = dyn_cast<CastInst>(*I);
10125       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10126         *I = CI->getOperand(0);
10127         Changed = true;
10128       }
10129     }
10130   }
10131
10132   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10133     // Inline asm calls cannot throw - mark them 'nounwind'.
10134     CS.setDoesNotThrow();
10135     Changed = true;
10136   }
10137
10138   return Changed ? CS.getInstruction() : 0;
10139 }
10140
10141 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10142 // attempt to move the cast to the arguments of the call/invoke.
10143 //
10144 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10145   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10146   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10147   if (CE->getOpcode() != Instruction::BitCast || 
10148       !isa<Function>(CE->getOperand(0)))
10149     return false;
10150   Function *Callee = cast<Function>(CE->getOperand(0));
10151   Instruction *Caller = CS.getInstruction();
10152   const AttrListPtr &CallerPAL = CS.getAttributes();
10153
10154   // Okay, this is a cast from a function to a different type.  Unless doing so
10155   // would cause a type conversion of one of our arguments, change this call to
10156   // be a direct call with arguments casted to the appropriate types.
10157   //
10158   const FunctionType *FT = Callee->getFunctionType();
10159   const Type *OldRetTy = Caller->getType();
10160   const Type *NewRetTy = FT->getReturnType();
10161
10162   if (isa<StructType>(NewRetTy))
10163     return false; // TODO: Handle multiple return values.
10164
10165   // Check to see if we are changing the return type...
10166   if (OldRetTy != NewRetTy) {
10167     if (Callee->isDeclaration() &&
10168         // Conversion is ok if changing from one pointer type to another or from
10169         // a pointer to an integer of the same size.
10170         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10171           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10172       return false;   // Cannot transform this return value.
10173
10174     if (!Caller->use_empty() &&
10175         // void -> non-void is handled specially
10176         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10177       return false;   // Cannot transform this return value.
10178
10179     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10180       Attributes RAttrs = CallerPAL.getRetAttributes();
10181       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10182         return false;   // Attribute not compatible with transformed value.
10183     }
10184
10185     // If the callsite is an invoke instruction, and the return value is used by
10186     // a PHI node in a successor, we cannot change the return type of the call
10187     // because there is no place to put the cast instruction (without breaking
10188     // the critical edge).  Bail out in this case.
10189     if (!Caller->use_empty())
10190       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10191         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10192              UI != E; ++UI)
10193           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10194             if (PN->getParent() == II->getNormalDest() ||
10195                 PN->getParent() == II->getUnwindDest())
10196               return false;
10197   }
10198
10199   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10200   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10201
10202   CallSite::arg_iterator AI = CS.arg_begin();
10203   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10204     const Type *ParamTy = FT->getParamType(i);
10205     const Type *ActTy = (*AI)->getType();
10206
10207     if (!CastInst::isCastable(ActTy, ParamTy))
10208       return false;   // Cannot transform this parameter value.
10209
10210     if (CallerPAL.getParamAttributes(i + 1) 
10211         & Attribute::typeIncompatible(ParamTy))
10212       return false;   // Attribute not compatible with transformed value.
10213
10214     // Converting from one pointer type to another or between a pointer and an
10215     // integer of the same size is safe even if we do not have a body.
10216     bool isConvertible = ActTy == ParamTy ||
10217       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10218        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10219     if (Callee->isDeclaration() && !isConvertible) return false;
10220   }
10221
10222   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10223       Callee->isDeclaration())
10224     return false;   // Do not delete arguments unless we have a function body.
10225
10226   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10227       !CallerPAL.isEmpty())
10228     // In this case we have more arguments than the new function type, but we
10229     // won't be dropping them.  Check that these extra arguments have attributes
10230     // that are compatible with being a vararg call argument.
10231     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10232       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10233         break;
10234       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10235       if (PAttrs & Attribute::VarArgsIncompatible)
10236         return false;
10237     }
10238
10239   // Okay, we decided that this is a safe thing to do: go ahead and start
10240   // inserting cast instructions as necessary...
10241   std::vector<Value*> Args;
10242   Args.reserve(NumActualArgs);
10243   SmallVector<AttributeWithIndex, 8> attrVec;
10244   attrVec.reserve(NumCommonArgs);
10245
10246   // Get any return attributes.
10247   Attributes RAttrs = CallerPAL.getRetAttributes();
10248
10249   // If the return value is not being used, the type may not be compatible
10250   // with the existing attributes.  Wipe out any problematic attributes.
10251   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10252
10253   // Add the new return attributes.
10254   if (RAttrs)
10255     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10256
10257   AI = CS.arg_begin();
10258   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10259     const Type *ParamTy = FT->getParamType(i);
10260     if ((*AI)->getType() == ParamTy) {
10261       Args.push_back(*AI);
10262     } else {
10263       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10264           false, ParamTy, false);
10265       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10266       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10267     }
10268
10269     // Add any parameter attributes.
10270     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10271       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10272   }
10273
10274   // If the function takes more arguments than the call was taking, add them
10275   // now...
10276   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10277     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10278
10279   // If we are removing arguments to the function, emit an obnoxious warning...
10280   if (FT->getNumParams() < NumActualArgs) {
10281     if (!FT->isVarArg()) {
10282       cerr << "WARNING: While resolving call to function '"
10283            << Callee->getName() << "' arguments were dropped!\n";
10284     } else {
10285       // Add all of the arguments in their promoted form to the arg list...
10286       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10287         const Type *PTy = getPromotedType((*AI)->getType());
10288         if (PTy != (*AI)->getType()) {
10289           // Must promote to pass through va_arg area!
10290           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10291                                                                 PTy, false);
10292           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10293           InsertNewInstBefore(Cast, *Caller);
10294           Args.push_back(Cast);
10295         } else {
10296           Args.push_back(*AI);
10297         }
10298
10299         // Add any parameter attributes.
10300         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10301           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10302       }
10303     }
10304   }
10305
10306   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10307     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10308
10309   if (NewRetTy == Type::VoidTy)
10310     Caller->setName("");   // Void type should not have a name.
10311
10312   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10313
10314   Instruction *NC;
10315   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10316     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10317                             Args.begin(), Args.end(),
10318                             Caller->getName(), Caller);
10319     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10320     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10321   } else {
10322     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10323                           Caller->getName(), Caller);
10324     CallInst *CI = cast<CallInst>(Caller);
10325     if (CI->isTailCall())
10326       cast<CallInst>(NC)->setTailCall();
10327     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10328     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10329   }
10330
10331   // Insert a cast of the return type as necessary.
10332   Value *NV = NC;
10333   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10334     if (NV->getType() != Type::VoidTy) {
10335       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10336                                                             OldRetTy, false);
10337       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10338
10339       // If this is an invoke instruction, we should insert it after the first
10340       // non-phi, instruction in the normal successor block.
10341       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10342         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10343         InsertNewInstBefore(NC, *I);
10344       } else {
10345         // Otherwise, it's a call, just insert cast right after the call instr
10346         InsertNewInstBefore(NC, *Caller);
10347       }
10348       AddUsersToWorkList(*Caller);
10349     } else {
10350       NV = Context->getUndef(Caller->getType());
10351     }
10352   }
10353
10354   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10355     Caller->replaceAllUsesWith(NV);
10356   Caller->eraseFromParent();
10357   RemoveFromWorkList(Caller);
10358   return true;
10359 }
10360
10361 // transformCallThroughTrampoline - Turn a call to a function created by the
10362 // init_trampoline intrinsic into a direct call to the underlying function.
10363 //
10364 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10365   Value *Callee = CS.getCalledValue();
10366   const PointerType *PTy = cast<PointerType>(Callee->getType());
10367   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10368   const AttrListPtr &Attrs = CS.getAttributes();
10369
10370   // If the call already has the 'nest' attribute somewhere then give up -
10371   // otherwise 'nest' would occur twice after splicing in the chain.
10372   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10373     return 0;
10374
10375   IntrinsicInst *Tramp =
10376     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10377
10378   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10379   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10380   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10381
10382   const AttrListPtr &NestAttrs = NestF->getAttributes();
10383   if (!NestAttrs.isEmpty()) {
10384     unsigned NestIdx = 1;
10385     const Type *NestTy = 0;
10386     Attributes NestAttr = Attribute::None;
10387
10388     // Look for a parameter marked with the 'nest' attribute.
10389     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10390          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10391       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10392         // Record the parameter type and any other attributes.
10393         NestTy = *I;
10394         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10395         break;
10396       }
10397
10398     if (NestTy) {
10399       Instruction *Caller = CS.getInstruction();
10400       std::vector<Value*> NewArgs;
10401       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10402
10403       SmallVector<AttributeWithIndex, 8> NewAttrs;
10404       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10405
10406       // Insert the nest argument into the call argument list, which may
10407       // mean appending it.  Likewise for attributes.
10408
10409       // Add any result attributes.
10410       if (Attributes Attr = Attrs.getRetAttributes())
10411         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10412
10413       {
10414         unsigned Idx = 1;
10415         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10416         do {
10417           if (Idx == NestIdx) {
10418             // Add the chain argument and attributes.
10419             Value *NestVal = Tramp->getOperand(3);
10420             if (NestVal->getType() != NestTy)
10421               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10422             NewArgs.push_back(NestVal);
10423             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10424           }
10425
10426           if (I == E)
10427             break;
10428
10429           // Add the original argument and attributes.
10430           NewArgs.push_back(*I);
10431           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10432             NewAttrs.push_back
10433               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10434
10435           ++Idx, ++I;
10436         } while (1);
10437       }
10438
10439       // Add any function attributes.
10440       if (Attributes Attr = Attrs.getFnAttributes())
10441         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10442
10443       // The trampoline may have been bitcast to a bogus type (FTy).
10444       // Handle this by synthesizing a new function type, equal to FTy
10445       // with the chain parameter inserted.
10446
10447       std::vector<const Type*> NewTypes;
10448       NewTypes.reserve(FTy->getNumParams()+1);
10449
10450       // Insert the chain's type into the list of parameter types, which may
10451       // mean appending it.
10452       {
10453         unsigned Idx = 1;
10454         FunctionType::param_iterator I = FTy->param_begin(),
10455           E = FTy->param_end();
10456
10457         do {
10458           if (Idx == NestIdx)
10459             // Add the chain's type.
10460             NewTypes.push_back(NestTy);
10461
10462           if (I == E)
10463             break;
10464
10465           // Add the original type.
10466           NewTypes.push_back(*I);
10467
10468           ++Idx, ++I;
10469         } while (1);
10470       }
10471
10472       // Replace the trampoline call with a direct call.  Let the generic
10473       // code sort out any function type mismatches.
10474       FunctionType *NewFTy =
10475                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10476                                                 FTy->isVarArg());
10477       Constant *NewCallee =
10478         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10479         NestF : Context->getConstantExprBitCast(NestF, 
10480                                          Context->getPointerTypeUnqual(NewFTy));
10481       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10482
10483       Instruction *NewCaller;
10484       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10485         NewCaller = InvokeInst::Create(NewCallee,
10486                                        II->getNormalDest(), II->getUnwindDest(),
10487                                        NewArgs.begin(), NewArgs.end(),
10488                                        Caller->getName(), Caller);
10489         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10490         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10491       } else {
10492         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10493                                      Caller->getName(), Caller);
10494         if (cast<CallInst>(Caller)->isTailCall())
10495           cast<CallInst>(NewCaller)->setTailCall();
10496         cast<CallInst>(NewCaller)->
10497           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10498         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10499       }
10500       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10501         Caller->replaceAllUsesWith(NewCaller);
10502       Caller->eraseFromParent();
10503       RemoveFromWorkList(Caller);
10504       return 0;
10505     }
10506   }
10507
10508   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10509   // parameter, there is no need to adjust the argument list.  Let the generic
10510   // code sort out any function type mismatches.
10511   Constant *NewCallee =
10512     NestF->getType() == PTy ? NestF : 
10513                               Context->getConstantExprBitCast(NestF, PTy);
10514   CS.setCalledFunction(NewCallee);
10515   return CS.getInstruction();
10516 }
10517
10518 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10519 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10520 /// and a single binop.
10521 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10522   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10523   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10524   unsigned Opc = FirstInst->getOpcode();
10525   Value *LHSVal = FirstInst->getOperand(0);
10526   Value *RHSVal = FirstInst->getOperand(1);
10527     
10528   const Type *LHSType = LHSVal->getType();
10529   const Type *RHSType = RHSVal->getType();
10530   
10531   // Scan to see if all operands are the same opcode, all have one use, and all
10532   // kill their operands (i.e. the operands have one use).
10533   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10534     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10535     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10536         // Verify type of the LHS matches so we don't fold cmp's of different
10537         // types or GEP's with different index types.
10538         I->getOperand(0)->getType() != LHSType ||
10539         I->getOperand(1)->getType() != RHSType)
10540       return 0;
10541
10542     // If they are CmpInst instructions, check their predicates
10543     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10544       if (cast<CmpInst>(I)->getPredicate() !=
10545           cast<CmpInst>(FirstInst)->getPredicate())
10546         return 0;
10547     
10548     // Keep track of which operand needs a phi node.
10549     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10550     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10551   }
10552   
10553   // Otherwise, this is safe to transform!
10554   
10555   Value *InLHS = FirstInst->getOperand(0);
10556   Value *InRHS = FirstInst->getOperand(1);
10557   PHINode *NewLHS = 0, *NewRHS = 0;
10558   if (LHSVal == 0) {
10559     NewLHS = PHINode::Create(LHSType,
10560                              FirstInst->getOperand(0)->getName() + ".pn");
10561     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10562     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10563     InsertNewInstBefore(NewLHS, PN);
10564     LHSVal = NewLHS;
10565   }
10566   
10567   if (RHSVal == 0) {
10568     NewRHS = PHINode::Create(RHSType,
10569                              FirstInst->getOperand(1)->getName() + ".pn");
10570     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10571     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10572     InsertNewInstBefore(NewRHS, PN);
10573     RHSVal = NewRHS;
10574   }
10575   
10576   // Add all operands to the new PHIs.
10577   if (NewLHS || NewRHS) {
10578     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10579       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10580       if (NewLHS) {
10581         Value *NewInLHS = InInst->getOperand(0);
10582         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10583       }
10584       if (NewRHS) {
10585         Value *NewInRHS = InInst->getOperand(1);
10586         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10587       }
10588     }
10589   }
10590     
10591   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10592     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10593   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10594   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10595                          LHSVal, RHSVal);
10596 }
10597
10598 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10599   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10600   
10601   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10602                                         FirstInst->op_end());
10603   // This is true if all GEP bases are allocas and if all indices into them are
10604   // constants.
10605   bool AllBasePointersAreAllocas = true;
10606   
10607   // Scan to see if all operands are the same opcode, all have one use, and all
10608   // kill their operands (i.e. the operands have one use).
10609   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10610     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10611     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10612       GEP->getNumOperands() != FirstInst->getNumOperands())
10613       return 0;
10614
10615     // Keep track of whether or not all GEPs are of alloca pointers.
10616     if (AllBasePointersAreAllocas &&
10617         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10618          !GEP->hasAllConstantIndices()))
10619       AllBasePointersAreAllocas = false;
10620     
10621     // Compare the operand lists.
10622     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10623       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10624         continue;
10625       
10626       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10627       // if one of the PHIs has a constant for the index.  The index may be
10628       // substantially cheaper to compute for the constants, so making it a
10629       // variable index could pessimize the path.  This also handles the case
10630       // for struct indices, which must always be constant.
10631       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10632           isa<ConstantInt>(GEP->getOperand(op)))
10633         return 0;
10634       
10635       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10636         return 0;
10637       FixedOperands[op] = 0;  // Needs a PHI.
10638     }
10639   }
10640   
10641   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10642   // bother doing this transformation.  At best, this will just save a bit of
10643   // offset calculation, but all the predecessors will have to materialize the
10644   // stack address into a register anyway.  We'd actually rather *clone* the
10645   // load up into the predecessors so that we have a load of a gep of an alloca,
10646   // which can usually all be folded into the load.
10647   if (AllBasePointersAreAllocas)
10648     return 0;
10649   
10650   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10651   // that is variable.
10652   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10653   
10654   bool HasAnyPHIs = false;
10655   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10656     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10657     Value *FirstOp = FirstInst->getOperand(i);
10658     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10659                                      FirstOp->getName()+".pn");
10660     InsertNewInstBefore(NewPN, PN);
10661     
10662     NewPN->reserveOperandSpace(e);
10663     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10664     OperandPhis[i] = NewPN;
10665     FixedOperands[i] = NewPN;
10666     HasAnyPHIs = true;
10667   }
10668
10669   
10670   // Add all operands to the new PHIs.
10671   if (HasAnyPHIs) {
10672     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10673       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10674       BasicBlock *InBB = PN.getIncomingBlock(i);
10675       
10676       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10677         if (PHINode *OpPhi = OperandPhis[op])
10678           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10679     }
10680   }
10681   
10682   Value *Base = FixedOperands[0];
10683   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10684                                    FixedOperands.end());
10685 }
10686
10687
10688 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10689 /// sink the load out of the block that defines it.  This means that it must be
10690 /// obvious the value of the load is not changed from the point of the load to
10691 /// the end of the block it is in.
10692 ///
10693 /// Finally, it is safe, but not profitable, to sink a load targetting a
10694 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10695 /// to a register.
10696 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10697   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10698   
10699   for (++BBI; BBI != E; ++BBI)
10700     if (BBI->mayWriteToMemory())
10701       return false;
10702   
10703   // Check for non-address taken alloca.  If not address-taken already, it isn't
10704   // profitable to do this xform.
10705   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10706     bool isAddressTaken = false;
10707     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10708          UI != E; ++UI) {
10709       if (isa<LoadInst>(UI)) continue;
10710       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10711         // If storing TO the alloca, then the address isn't taken.
10712         if (SI->getOperand(1) == AI) continue;
10713       }
10714       isAddressTaken = true;
10715       break;
10716     }
10717     
10718     if (!isAddressTaken && AI->isStaticAlloca())
10719       return false;
10720   }
10721   
10722   // If this load is a load from a GEP with a constant offset from an alloca,
10723   // then we don't want to sink it.  In its present form, it will be
10724   // load [constant stack offset].  Sinking it will cause us to have to
10725   // materialize the stack addresses in each predecessor in a register only to
10726   // do a shared load from register in the successor.
10727   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10728     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10729       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10730         return false;
10731   
10732   return true;
10733 }
10734
10735
10736 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10737 // operator and they all are only used by the PHI, PHI together their
10738 // inputs, and do the operation once, to the result of the PHI.
10739 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10740   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10741
10742   // Scan the instruction, looking for input operations that can be folded away.
10743   // If all input operands to the phi are the same instruction (e.g. a cast from
10744   // the same type or "+42") we can pull the operation through the PHI, reducing
10745   // code size and simplifying code.
10746   Constant *ConstantOp = 0;
10747   const Type *CastSrcTy = 0;
10748   bool isVolatile = false;
10749   if (isa<CastInst>(FirstInst)) {
10750     CastSrcTy = FirstInst->getOperand(0)->getType();
10751   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10752     // Can fold binop, compare or shift here if the RHS is a constant, 
10753     // otherwise call FoldPHIArgBinOpIntoPHI.
10754     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10755     if (ConstantOp == 0)
10756       return FoldPHIArgBinOpIntoPHI(PN);
10757   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10758     isVolatile = LI->isVolatile();
10759     // We can't sink the load if the loaded value could be modified between the
10760     // load and the PHI.
10761     if (LI->getParent() != PN.getIncomingBlock(0) ||
10762         !isSafeAndProfitableToSinkLoad(LI))
10763       return 0;
10764     
10765     // If the PHI is of volatile loads and the load block has multiple
10766     // successors, sinking it would remove a load of the volatile value from
10767     // the path through the other successor.
10768     if (isVolatile &&
10769         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10770       return 0;
10771     
10772   } else if (isa<GetElementPtrInst>(FirstInst)) {
10773     return FoldPHIArgGEPIntoPHI(PN);
10774   } else {
10775     return 0;  // Cannot fold this operation.
10776   }
10777
10778   // Check to see if all arguments are the same operation.
10779   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10780     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10781     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10782     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10783       return 0;
10784     if (CastSrcTy) {
10785       if (I->getOperand(0)->getType() != CastSrcTy)
10786         return 0;  // Cast operation must match.
10787     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10788       // We can't sink the load if the loaded value could be modified between 
10789       // the load and the PHI.
10790       if (LI->isVolatile() != isVolatile ||
10791           LI->getParent() != PN.getIncomingBlock(i) ||
10792           !isSafeAndProfitableToSinkLoad(LI))
10793         return 0;
10794       
10795       // If the PHI is of volatile loads and the load block has multiple
10796       // successors, sinking it would remove a load of the volatile value from
10797       // the path through the other successor.
10798       if (isVolatile &&
10799           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10800         return 0;
10801       
10802     } else if (I->getOperand(1) != ConstantOp) {
10803       return 0;
10804     }
10805   }
10806
10807   // Okay, they are all the same operation.  Create a new PHI node of the
10808   // correct type, and PHI together all of the LHS's of the instructions.
10809   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10810                                    PN.getName()+".in");
10811   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10812
10813   Value *InVal = FirstInst->getOperand(0);
10814   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10815
10816   // Add all operands to the new PHI.
10817   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10818     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10819     if (NewInVal != InVal)
10820       InVal = 0;
10821     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10822   }
10823
10824   Value *PhiVal;
10825   if (InVal) {
10826     // The new PHI unions all of the same values together.  This is really
10827     // common, so we handle it intelligently here for compile-time speed.
10828     PhiVal = InVal;
10829     delete NewPN;
10830   } else {
10831     InsertNewInstBefore(NewPN, PN);
10832     PhiVal = NewPN;
10833   }
10834
10835   // Insert and return the new operation.
10836   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10837     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10838   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10839     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10840   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10841     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10842                            PhiVal, ConstantOp);
10843   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10844   
10845   // If this was a volatile load that we are merging, make sure to loop through
10846   // and mark all the input loads as non-volatile.  If we don't do this, we will
10847   // insert a new volatile load and the old ones will not be deletable.
10848   if (isVolatile)
10849     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10850       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10851   
10852   return new LoadInst(PhiVal, "", isVolatile);
10853 }
10854
10855 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10856 /// that is dead.
10857 static bool DeadPHICycle(PHINode *PN,
10858                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10859   if (PN->use_empty()) return true;
10860   if (!PN->hasOneUse()) return false;
10861
10862   // Remember this node, and if we find the cycle, return.
10863   if (!PotentiallyDeadPHIs.insert(PN))
10864     return true;
10865   
10866   // Don't scan crazily complex things.
10867   if (PotentiallyDeadPHIs.size() == 16)
10868     return false;
10869
10870   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10871     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10872
10873   return false;
10874 }
10875
10876 /// PHIsEqualValue - Return true if this phi node is always equal to
10877 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10878 ///   z = some value; x = phi (y, z); y = phi (x, z)
10879 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10880                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10881   // See if we already saw this PHI node.
10882   if (!ValueEqualPHIs.insert(PN))
10883     return true;
10884   
10885   // Don't scan crazily complex things.
10886   if (ValueEqualPHIs.size() == 16)
10887     return false;
10888  
10889   // Scan the operands to see if they are either phi nodes or are equal to
10890   // the value.
10891   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10892     Value *Op = PN->getIncomingValue(i);
10893     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10894       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10895         return false;
10896     } else if (Op != NonPhiInVal)
10897       return false;
10898   }
10899   
10900   return true;
10901 }
10902
10903
10904 // PHINode simplification
10905 //
10906 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10907   // If LCSSA is around, don't mess with Phi nodes
10908   if (MustPreserveLCSSA) return 0;
10909   
10910   if (Value *V = PN.hasConstantValue())
10911     return ReplaceInstUsesWith(PN, V);
10912
10913   // If all PHI operands are the same operation, pull them through the PHI,
10914   // reducing code size.
10915   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10916       isa<Instruction>(PN.getIncomingValue(1)) &&
10917       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10918       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10919       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10920       // than themselves more than once.
10921       PN.getIncomingValue(0)->hasOneUse())
10922     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10923       return Result;
10924
10925   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10926   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10927   // PHI)... break the cycle.
10928   if (PN.hasOneUse()) {
10929     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10930     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10931       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10932       PotentiallyDeadPHIs.insert(&PN);
10933       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10934         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10935     }
10936    
10937     // If this phi has a single use, and if that use just computes a value for
10938     // the next iteration of a loop, delete the phi.  This occurs with unused
10939     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10940     // common case here is good because the only other things that catch this
10941     // are induction variable analysis (sometimes) and ADCE, which is only run
10942     // late.
10943     if (PHIUser->hasOneUse() &&
10944         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10945         PHIUser->use_back() == &PN) {
10946       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10947     }
10948   }
10949
10950   // We sometimes end up with phi cycles that non-obviously end up being the
10951   // same value, for example:
10952   //   z = some value; x = phi (y, z); y = phi (x, z)
10953   // where the phi nodes don't necessarily need to be in the same block.  Do a
10954   // quick check to see if the PHI node only contains a single non-phi value, if
10955   // so, scan to see if the phi cycle is actually equal to that value.
10956   {
10957     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10958     // Scan for the first non-phi operand.
10959     while (InValNo != NumOperandVals && 
10960            isa<PHINode>(PN.getIncomingValue(InValNo)))
10961       ++InValNo;
10962
10963     if (InValNo != NumOperandVals) {
10964       Value *NonPhiInVal = PN.getOperand(InValNo);
10965       
10966       // Scan the rest of the operands to see if there are any conflicts, if so
10967       // there is no need to recursively scan other phis.
10968       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10969         Value *OpVal = PN.getIncomingValue(InValNo);
10970         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10971           break;
10972       }
10973       
10974       // If we scanned over all operands, then we have one unique value plus
10975       // phi values.  Scan PHI nodes to see if they all merge in each other or
10976       // the value.
10977       if (InValNo == NumOperandVals) {
10978         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10979         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10980           return ReplaceInstUsesWith(PN, NonPhiInVal);
10981       }
10982     }
10983   }
10984   return 0;
10985 }
10986
10987 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10988                                    Instruction *InsertPoint,
10989                                    InstCombiner *IC) {
10990   unsigned PtrSize = DTy->getScalarSizeInBits();
10991   unsigned VTySize = V->getType()->getScalarSizeInBits();
10992   // We must cast correctly to the pointer type. Ensure that we
10993   // sign extend the integer value if it is smaller as this is
10994   // used for address computation.
10995   Instruction::CastOps opcode = 
10996      (VTySize < PtrSize ? Instruction::SExt :
10997       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10998   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10999 }
11000
11001
11002 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11003   Value *PtrOp = GEP.getOperand(0);
11004   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11005   // If so, eliminate the noop.
11006   if (GEP.getNumOperands() == 1)
11007     return ReplaceInstUsesWith(GEP, PtrOp);
11008
11009   if (isa<UndefValue>(GEP.getOperand(0)))
11010     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11011
11012   bool HasZeroPointerIndex = false;
11013   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11014     HasZeroPointerIndex = C->isNullValue();
11015
11016   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11017     return ReplaceInstUsesWith(GEP, PtrOp);
11018
11019   // Eliminate unneeded casts for indices.
11020   bool MadeChange = false;
11021   
11022   gep_type_iterator GTI = gep_type_begin(GEP);
11023   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11024        i != e; ++i, ++GTI) {
11025     if (isa<SequentialType>(*GTI)) {
11026       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11027         if (CI->getOpcode() == Instruction::ZExt ||
11028             CI->getOpcode() == Instruction::SExt) {
11029           const Type *SrcTy = CI->getOperand(0)->getType();
11030           // We can eliminate a cast from i32 to i64 iff the target 
11031           // is a 32-bit pointer target.
11032           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11033             MadeChange = true;
11034             *i = CI->getOperand(0);
11035           }
11036         }
11037       }
11038       // If we are using a wider index than needed for this platform, shrink it
11039       // to what we need.  If narrower, sign-extend it to what we need.
11040       // If the incoming value needs a cast instruction,
11041       // insert it.  This explicit cast can make subsequent optimizations more
11042       // obvious.
11043       Value *Op = *i;
11044       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11045         if (Constant *C = dyn_cast<Constant>(Op)) {
11046           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11047           MadeChange = true;
11048         } else {
11049           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11050                                 GEP);
11051           *i = Op;
11052           MadeChange = true;
11053         }
11054       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11055         if (Constant *C = dyn_cast<Constant>(Op)) {
11056           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11057           MadeChange = true;
11058         } else {
11059           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11060                                 GEP);
11061           *i = Op;
11062           MadeChange = true;
11063         }
11064       }
11065     }
11066   }
11067   if (MadeChange) return &GEP;
11068
11069   // Combine Indices - If the source pointer to this getelementptr instruction
11070   // is a getelementptr instruction, combine the indices of the two
11071   // getelementptr instructions into a single instruction.
11072   //
11073   SmallVector<Value*, 8> SrcGEPOperands;
11074   if (User *Src = dyn_castGetElementPtr(PtrOp))
11075     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11076
11077   if (!SrcGEPOperands.empty()) {
11078     // Note that if our source is a gep chain itself that we wait for that
11079     // chain to be resolved before we perform this transformation.  This
11080     // avoids us creating a TON of code in some cases.
11081     //
11082     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11083         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11084       return 0;   // Wait until our source is folded to completion.
11085
11086     SmallVector<Value*, 8> Indices;
11087
11088     // Find out whether the last index in the source GEP is a sequential idx.
11089     bool EndsWithSequential = false;
11090     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11091            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11092       EndsWithSequential = !isa<StructType>(*I);
11093
11094     // Can we combine the two pointer arithmetics offsets?
11095     if (EndsWithSequential) {
11096       // Replace: gep (gep %P, long B), long A, ...
11097       // With:    T = long A+B; gep %P, T, ...
11098       //
11099       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11100       if (SO1 == Context->getNullValue(SO1->getType())) {
11101         Sum = GO1;
11102       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11103         Sum = SO1;
11104       } else {
11105         // If they aren't the same type, convert both to an integer of the
11106         // target's pointer size.
11107         if (SO1->getType() != GO1->getType()) {
11108           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11109             SO1 =
11110                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11111           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11112             GO1 =
11113                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11114           } else {
11115             unsigned PS = TD->getPointerSizeInBits();
11116             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11117               // Convert GO1 to SO1's type.
11118               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11119
11120             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11121               // Convert SO1 to GO1's type.
11122               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11123             } else {
11124               const Type *PT = TD->getIntPtrType();
11125               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11126               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11127             }
11128           }
11129         }
11130         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11131           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11132                                             cast<Constant>(GO1));
11133         else {
11134           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11135           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11136         }
11137       }
11138
11139       // Recycle the GEP we already have if possible.
11140       if (SrcGEPOperands.size() == 2) {
11141         GEP.setOperand(0, SrcGEPOperands[0]);
11142         GEP.setOperand(1, Sum);
11143         return &GEP;
11144       } else {
11145         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11146                        SrcGEPOperands.end()-1);
11147         Indices.push_back(Sum);
11148         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11149       }
11150     } else if (isa<Constant>(*GEP.idx_begin()) &&
11151                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11152                SrcGEPOperands.size() != 1) {
11153       // Otherwise we can do the fold if the first index of the GEP is a zero
11154       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11155                      SrcGEPOperands.end());
11156       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11157     }
11158
11159     if (!Indices.empty())
11160       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11161                                        Indices.end(), GEP.getName());
11162
11163   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11164     // GEP of global variable.  If all of the indices for this GEP are
11165     // constants, we can promote this to a constexpr instead of an instruction.
11166
11167     // Scan for nonconstants...
11168     SmallVector<Constant*, 8> Indices;
11169     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11170     for (; I != E && isa<Constant>(*I); ++I)
11171       Indices.push_back(cast<Constant>(*I));
11172
11173     if (I == E) {  // If they are all constants...
11174       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11175                                                     &Indices[0],Indices.size());
11176
11177       // Replace all uses of the GEP with the new constexpr...
11178       return ReplaceInstUsesWith(GEP, CE);
11179     }
11180   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11181     if (!isa<PointerType>(X->getType())) {
11182       // Not interesting.  Source pointer must be a cast from pointer.
11183     } else if (HasZeroPointerIndex) {
11184       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11185       // into     : GEP [10 x i8]* X, i32 0, ...
11186       //
11187       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11188       //           into     : GEP i8* X, ...
11189       // 
11190       // This occurs when the program declares an array extern like "int X[];"
11191       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11192       const PointerType *XTy = cast<PointerType>(X->getType());
11193       if (const ArrayType *CATy =
11194           dyn_cast<ArrayType>(CPTy->getElementType())) {
11195         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11196         if (CATy->getElementType() == XTy->getElementType()) {
11197           // -> GEP i8* X, ...
11198           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11199           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11200                                            GEP.getName());
11201         } else if (const ArrayType *XATy =
11202                  dyn_cast<ArrayType>(XTy->getElementType())) {
11203           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11204           if (CATy->getElementType() == XATy->getElementType()) {
11205             // -> GEP [10 x i8]* X, i32 0, ...
11206             // At this point, we know that the cast source type is a pointer
11207             // to an array of the same type as the destination pointer
11208             // array.  Because the array type is never stepped over (there
11209             // is a leading zero) we can fold the cast into this GEP.
11210             GEP.setOperand(0, X);
11211             return &GEP;
11212           }
11213         }
11214       }
11215     } else if (GEP.getNumOperands() == 2) {
11216       // Transform things like:
11217       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11218       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11219       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11220       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11221       if (isa<ArrayType>(SrcElTy) &&
11222           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11223           TD->getTypeAllocSize(ResElTy)) {
11224         Value *Idx[2];
11225         Idx[0] = Context->getNullValue(Type::Int32Ty);
11226         Idx[1] = GEP.getOperand(1);
11227         Value *V = InsertNewInstBefore(
11228                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11229         // V and GEP are both pointer types --> BitCast
11230         return new BitCastInst(V, GEP.getType());
11231       }
11232       
11233       // Transform things like:
11234       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11235       //   (where tmp = 8*tmp2) into:
11236       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11237       
11238       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11239         uint64_t ArrayEltSize =
11240             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11241         
11242         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11243         // allow either a mul, shift, or constant here.
11244         Value *NewIdx = 0;
11245         ConstantInt *Scale = 0;
11246         if (ArrayEltSize == 1) {
11247           NewIdx = GEP.getOperand(1);
11248           Scale = 
11249                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11250         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11251           NewIdx = Context->getConstantInt(CI->getType(), 1);
11252           Scale = CI;
11253         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11254           if (Inst->getOpcode() == Instruction::Shl &&
11255               isa<ConstantInt>(Inst->getOperand(1))) {
11256             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11257             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11258             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11259                                      1ULL << ShAmtVal);
11260             NewIdx = Inst->getOperand(0);
11261           } else if (Inst->getOpcode() == Instruction::Mul &&
11262                      isa<ConstantInt>(Inst->getOperand(1))) {
11263             Scale = cast<ConstantInt>(Inst->getOperand(1));
11264             NewIdx = Inst->getOperand(0);
11265           }
11266         }
11267         
11268         // If the index will be to exactly the right offset with the scale taken
11269         // out, perform the transformation. Note, we don't know whether Scale is
11270         // signed or not. We'll use unsigned version of division/modulo
11271         // operation after making sure Scale doesn't have the sign bit set.
11272         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11273             Scale->getZExtValue() % ArrayEltSize == 0) {
11274           Scale = Context->getConstantInt(Scale->getType(),
11275                                    Scale->getZExtValue() / ArrayEltSize);
11276           if (Scale->getZExtValue() != 1) {
11277             Constant *C =
11278                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11279                                                        false /*ZExt*/);
11280             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11281             NewIdx = InsertNewInstBefore(Sc, GEP);
11282           }
11283
11284           // Insert the new GEP instruction.
11285           Value *Idx[2];
11286           Idx[0] = Context->getNullValue(Type::Int32Ty);
11287           Idx[1] = NewIdx;
11288           Instruction *NewGEP =
11289             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11290           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11291           // The NewGEP must be pointer typed, so must the old one -> BitCast
11292           return new BitCastInst(NewGEP, GEP.getType());
11293         }
11294       }
11295     }
11296   }
11297   
11298   /// See if we can simplify:
11299   ///   X = bitcast A to B*
11300   ///   Y = gep X, <...constant indices...>
11301   /// into a gep of the original struct.  This is important for SROA and alias
11302   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11303   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11304     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11305       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11306       // a constant back from EmitGEPOffset.
11307       ConstantInt *OffsetV =
11308                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11309       int64_t Offset = OffsetV->getSExtValue();
11310       
11311       // If this GEP instruction doesn't move the pointer, just replace the GEP
11312       // with a bitcast of the real input to the dest type.
11313       if (Offset == 0) {
11314         // If the bitcast is of an allocation, and the allocation will be
11315         // converted to match the type of the cast, don't touch this.
11316         if (isa<AllocationInst>(BCI->getOperand(0))) {
11317           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11318           if (Instruction *I = visitBitCast(*BCI)) {
11319             if (I != BCI) {
11320               I->takeName(BCI);
11321               BCI->getParent()->getInstList().insert(BCI, I);
11322               ReplaceInstUsesWith(*BCI, I);
11323             }
11324             return &GEP;
11325           }
11326         }
11327         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11328       }
11329       
11330       // Otherwise, if the offset is non-zero, we need to find out if there is a
11331       // field at Offset in 'A's type.  If so, we can pull the cast through the
11332       // GEP.
11333       SmallVector<Value*, 8> NewIndices;
11334       const Type *InTy =
11335         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11336       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11337         Instruction *NGEP =
11338            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11339                                      NewIndices.end());
11340         if (NGEP->getType() == GEP.getType()) return NGEP;
11341         InsertNewInstBefore(NGEP, GEP);
11342         NGEP->takeName(&GEP);
11343         return new BitCastInst(NGEP, GEP.getType());
11344       }
11345     }
11346   }    
11347     
11348   return 0;
11349 }
11350
11351 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11352   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11353   if (AI.isArrayAllocation()) {  // Check C != 1
11354     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11355       const Type *NewTy = 
11356         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11357       AllocationInst *New = 0;
11358
11359       // Create and insert the replacement instruction...
11360       if (isa<MallocInst>(AI))
11361         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11362       else {
11363         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11364         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11365       }
11366
11367       InsertNewInstBefore(New, AI);
11368
11369       // Scan to the end of the allocation instructions, to skip over a block of
11370       // allocas if possible...also skip interleaved debug info
11371       //
11372       BasicBlock::iterator It = New;
11373       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11374
11375       // Now that I is pointing to the first non-allocation-inst in the block,
11376       // insert our getelementptr instruction...
11377       //
11378       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11379       Value *Idx[2];
11380       Idx[0] = NullIdx;
11381       Idx[1] = NullIdx;
11382       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11383                                            New->getName()+".sub", It);
11384
11385       // Now make everything use the getelementptr instead of the original
11386       // allocation.
11387       return ReplaceInstUsesWith(AI, V);
11388     } else if (isa<UndefValue>(AI.getArraySize())) {
11389       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11390     }
11391   }
11392
11393   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11394     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11395     // Note that we only do this for alloca's, because malloc should allocate
11396     // and return a unique pointer, even for a zero byte allocation.
11397     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11398       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11399
11400     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11401     if (AI.getAlignment() == 0)
11402       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11403   }
11404
11405   return 0;
11406 }
11407
11408 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11409   Value *Op = FI.getOperand(0);
11410
11411   // free undef -> unreachable.
11412   if (isa<UndefValue>(Op)) {
11413     // Insert a new store to null because we cannot modify the CFG here.
11414     new StoreInst(Context->getConstantIntTrue(),
11415            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11416     return EraseInstFromFunction(FI);
11417   }
11418   
11419   // If we have 'free null' delete the instruction.  This can happen in stl code
11420   // when lots of inlining happens.
11421   if (isa<ConstantPointerNull>(Op))
11422     return EraseInstFromFunction(FI);
11423   
11424   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11425   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11426     FI.setOperand(0, CI->getOperand(0));
11427     return &FI;
11428   }
11429   
11430   // Change free (gep X, 0,0,0,0) into free(X)
11431   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11432     if (GEPI->hasAllZeroIndices()) {
11433       AddToWorkList(GEPI);
11434       FI.setOperand(0, GEPI->getOperand(0));
11435       return &FI;
11436     }
11437   }
11438   
11439   // Change free(malloc) into nothing, if the malloc has a single use.
11440   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11441     if (MI->hasOneUse()) {
11442       EraseInstFromFunction(FI);
11443       return EraseInstFromFunction(*MI);
11444     }
11445
11446   return 0;
11447 }
11448
11449
11450 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11451 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11452                                         const TargetData *TD) {
11453   User *CI = cast<User>(LI.getOperand(0));
11454   Value *CastOp = CI->getOperand(0);
11455   LLVMContext *Context = IC.getContext();
11456
11457   if (TD) {
11458     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11459       // Instead of loading constant c string, use corresponding integer value
11460       // directly if string length is small enough.
11461       std::string Str;
11462       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11463         unsigned len = Str.length();
11464         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11465         unsigned numBits = Ty->getPrimitiveSizeInBits();
11466         // Replace LI with immediate integer store.
11467         if ((numBits >> 3) == len + 1) {
11468           APInt StrVal(numBits, 0);
11469           APInt SingleChar(numBits, 0);
11470           if (TD->isLittleEndian()) {
11471             for (signed i = len-1; i >= 0; i--) {
11472               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11473               StrVal = (StrVal << 8) | SingleChar;
11474             }
11475           } else {
11476             for (unsigned i = 0; i < len; i++) {
11477               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11478               StrVal = (StrVal << 8) | SingleChar;
11479             }
11480             // Append NULL at the end.
11481             SingleChar = 0;
11482             StrVal = (StrVal << 8) | SingleChar;
11483           }
11484           Value *NL = Context->getConstantInt(StrVal);
11485           return IC.ReplaceInstUsesWith(LI, NL);
11486         }
11487       }
11488     }
11489   }
11490
11491   const PointerType *DestTy = cast<PointerType>(CI->getType());
11492   const Type *DestPTy = DestTy->getElementType();
11493   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11494
11495     // If the address spaces don't match, don't eliminate the cast.
11496     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11497       return 0;
11498
11499     const Type *SrcPTy = SrcTy->getElementType();
11500
11501     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11502          isa<VectorType>(DestPTy)) {
11503       // If the source is an array, the code below will not succeed.  Check to
11504       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11505       // constants.
11506       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11507         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11508           if (ASrcTy->getNumElements() != 0) {
11509             Value *Idxs[2];
11510             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11511             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11512             SrcTy = cast<PointerType>(CastOp->getType());
11513             SrcPTy = SrcTy->getElementType();
11514           }
11515
11516       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11517             isa<VectorType>(SrcPTy)) &&
11518           // Do not allow turning this into a load of an integer, which is then
11519           // casted to a pointer, this pessimizes pointer analysis a lot.
11520           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11521           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11522                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11523
11524         // Okay, we are casting from one integer or pointer type to another of
11525         // the same size.  Instead of casting the pointer before the load, cast
11526         // the result of the loaded value.
11527         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11528                                                              CI->getName(),
11529                                                          LI.isVolatile()),LI);
11530         // Now cast the result of the load.
11531         return new BitCastInst(NewLoad, LI.getType());
11532       }
11533     }
11534   }
11535   return 0;
11536 }
11537
11538 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11539   Value *Op = LI.getOperand(0);
11540
11541   // Attempt to improve the alignment.
11542   unsigned KnownAlign =
11543     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11544   if (KnownAlign >
11545       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11546                                 LI.getAlignment()))
11547     LI.setAlignment(KnownAlign);
11548
11549   // load (cast X) --> cast (load X) iff safe
11550   if (isa<CastInst>(Op))
11551     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11552       return Res;
11553
11554   // None of the following transforms are legal for volatile loads.
11555   if (LI.isVolatile()) return 0;
11556   
11557   // Do really simple store-to-load forwarding and load CSE, to catch cases
11558   // where there are several consequtive memory accesses to the same location,
11559   // separated by a few arithmetic operations.
11560   BasicBlock::iterator BBI = &LI;
11561   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11562     return ReplaceInstUsesWith(LI, AvailableVal);
11563
11564   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11565     const Value *GEPI0 = GEPI->getOperand(0);
11566     // TODO: Consider a target hook for valid address spaces for this xform.
11567     if (isa<ConstantPointerNull>(GEPI0) &&
11568         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11569       // Insert a new store to null instruction before the load to indicate
11570       // that this code is not reachable.  We do this instead of inserting
11571       // an unreachable instruction directly because we cannot modify the
11572       // CFG.
11573       new StoreInst(Context->getUndef(LI.getType()),
11574                     Context->getNullValue(Op->getType()), &LI);
11575       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11576     }
11577   } 
11578
11579   if (Constant *C = dyn_cast<Constant>(Op)) {
11580     // load null/undef -> undef
11581     // TODO: Consider a target hook for valid address spaces for this xform.
11582     if (isa<UndefValue>(C) || (C->isNullValue() && 
11583         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11584       // Insert a new store to null instruction before the load to indicate that
11585       // this code is not reachable.  We do this instead of inserting an
11586       // unreachable instruction directly because we cannot modify the CFG.
11587       new StoreInst(Context->getUndef(LI.getType()),
11588                     Context->getNullValue(Op->getType()), &LI);
11589       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11590     }
11591
11592     // Instcombine load (constant global) into the value loaded.
11593     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11594       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11595         return ReplaceInstUsesWith(LI, GV->getInitializer());
11596
11597     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11598     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11599       if (CE->getOpcode() == Instruction::GetElementPtr) {
11600         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11601           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11602             if (Constant *V = 
11603                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11604                                                       Context))
11605               return ReplaceInstUsesWith(LI, V);
11606         if (CE->getOperand(0)->isNullValue()) {
11607           // Insert a new store to null instruction before the load to indicate
11608           // that this code is not reachable.  We do this instead of inserting
11609           // an unreachable instruction directly because we cannot modify the
11610           // CFG.
11611           new StoreInst(Context->getUndef(LI.getType()),
11612                         Context->getNullValue(Op->getType()), &LI);
11613           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11614         }
11615
11616       } else if (CE->isCast()) {
11617         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11618           return Res;
11619       }
11620     }
11621   }
11622     
11623   // If this load comes from anywhere in a constant global, and if the global
11624   // is all undef or zero, we know what it loads.
11625   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11626     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11627       if (GV->getInitializer()->isNullValue())
11628         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11629       else if (isa<UndefValue>(GV->getInitializer()))
11630         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11631     }
11632   }
11633
11634   if (Op->hasOneUse()) {
11635     // Change select and PHI nodes to select values instead of addresses: this
11636     // helps alias analysis out a lot, allows many others simplifications, and
11637     // exposes redundancy in the code.
11638     //
11639     // Note that we cannot do the transformation unless we know that the
11640     // introduced loads cannot trap!  Something like this is valid as long as
11641     // the condition is always false: load (select bool %C, int* null, int* %G),
11642     // but it would not be valid if we transformed it to load from null
11643     // unconditionally.
11644     //
11645     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11646       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11647       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11648           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11649         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11650                                      SI->getOperand(1)->getName()+".val"), LI);
11651         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11652                                      SI->getOperand(2)->getName()+".val"), LI);
11653         return SelectInst::Create(SI->getCondition(), V1, V2);
11654       }
11655
11656       // load (select (cond, null, P)) -> load P
11657       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11658         if (C->isNullValue()) {
11659           LI.setOperand(0, SI->getOperand(2));
11660           return &LI;
11661         }
11662
11663       // load (select (cond, P, null)) -> load P
11664       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11665         if (C->isNullValue()) {
11666           LI.setOperand(0, SI->getOperand(1));
11667           return &LI;
11668         }
11669     }
11670   }
11671   return 0;
11672 }
11673
11674 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11675 /// when possible.  This makes it generally easy to do alias analysis and/or
11676 /// SROA/mem2reg of the memory object.
11677 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11678   User *CI = cast<User>(SI.getOperand(1));
11679   Value *CastOp = CI->getOperand(0);
11680   LLVMContext *Context = IC.getContext();
11681
11682   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11683   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11684   if (SrcTy == 0) return 0;
11685   
11686   const Type *SrcPTy = SrcTy->getElementType();
11687
11688   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11689     return 0;
11690   
11691   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11692   /// to its first element.  This allows us to handle things like:
11693   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11694   /// on 32-bit hosts.
11695   SmallVector<Value*, 4> NewGEPIndices;
11696   
11697   // If the source is an array, the code below will not succeed.  Check to
11698   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11699   // constants.
11700   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11701     // Index through pointer.
11702     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11703     NewGEPIndices.push_back(Zero);
11704     
11705     while (1) {
11706       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11707         if (!STy->getNumElements()) /* Struct can be empty {} */
11708           break;
11709         NewGEPIndices.push_back(Zero);
11710         SrcPTy = STy->getElementType(0);
11711       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11712         NewGEPIndices.push_back(Zero);
11713         SrcPTy = ATy->getElementType();
11714       } else {
11715         break;
11716       }
11717     }
11718     
11719     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11720   }
11721
11722   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11723     return 0;
11724   
11725   // If the pointers point into different address spaces or if they point to
11726   // values with different sizes, we can't do the transformation.
11727   if (SrcTy->getAddressSpace() != 
11728         cast<PointerType>(CI->getType())->getAddressSpace() ||
11729       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11730       IC.getTargetData().getTypeSizeInBits(DestPTy))
11731     return 0;
11732
11733   // Okay, we are casting from one integer or pointer type to another of
11734   // the same size.  Instead of casting the pointer before 
11735   // the store, cast the value to be stored.
11736   Value *NewCast;
11737   Value *SIOp0 = SI.getOperand(0);
11738   Instruction::CastOps opcode = Instruction::BitCast;
11739   const Type* CastSrcTy = SIOp0->getType();
11740   const Type* CastDstTy = SrcPTy;
11741   if (isa<PointerType>(CastDstTy)) {
11742     if (CastSrcTy->isInteger())
11743       opcode = Instruction::IntToPtr;
11744   } else if (isa<IntegerType>(CastDstTy)) {
11745     if (isa<PointerType>(SIOp0->getType()))
11746       opcode = Instruction::PtrToInt;
11747   }
11748   
11749   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11750   // emit a GEP to index into its first field.
11751   if (!NewGEPIndices.empty()) {
11752     if (Constant *C = dyn_cast<Constant>(CastOp))
11753       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11754                                               NewGEPIndices.size());
11755     else
11756       CastOp = IC.InsertNewInstBefore(
11757               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11758                                         NewGEPIndices.end()), SI);
11759   }
11760   
11761   if (Constant *C = dyn_cast<Constant>(SIOp0))
11762     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11763   else
11764     NewCast = IC.InsertNewInstBefore(
11765       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11766       SI);
11767   return new StoreInst(NewCast, CastOp);
11768 }
11769
11770 /// equivalentAddressValues - Test if A and B will obviously have the same
11771 /// value. This includes recognizing that %t0 and %t1 will have the same
11772 /// value in code like this:
11773 ///   %t0 = getelementptr \@a, 0, 3
11774 ///   store i32 0, i32* %t0
11775 ///   %t1 = getelementptr \@a, 0, 3
11776 ///   %t2 = load i32* %t1
11777 ///
11778 static bool equivalentAddressValues(Value *A, Value *B) {
11779   // Test if the values are trivially equivalent.
11780   if (A == B) return true;
11781   
11782   // Test if the values come form identical arithmetic instructions.
11783   if (isa<BinaryOperator>(A) ||
11784       isa<CastInst>(A) ||
11785       isa<PHINode>(A) ||
11786       isa<GetElementPtrInst>(A))
11787     if (Instruction *BI = dyn_cast<Instruction>(B))
11788       if (cast<Instruction>(A)->isIdenticalTo(BI))
11789         return true;
11790   
11791   // Otherwise they may not be equivalent.
11792   return false;
11793 }
11794
11795 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11796 // return the llvm.dbg.declare.
11797 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11798   if (!V->hasNUses(2))
11799     return 0;
11800   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11801        UI != E; ++UI) {
11802     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11803       return DI;
11804     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11805       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11806         return DI;
11807       }
11808   }
11809   return 0;
11810 }
11811
11812 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11813   Value *Val = SI.getOperand(0);
11814   Value *Ptr = SI.getOperand(1);
11815
11816   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11817     EraseInstFromFunction(SI);
11818     ++NumCombined;
11819     return 0;
11820   }
11821   
11822   // If the RHS is an alloca with a single use, zapify the store, making the
11823   // alloca dead.
11824   // If the RHS is an alloca with a two uses, the other one being a 
11825   // llvm.dbg.declare, zapify the store and the declare, making the
11826   // alloca dead.  We must do this to prevent declare's from affecting
11827   // codegen.
11828   if (!SI.isVolatile()) {
11829     if (Ptr->hasOneUse()) {
11830       if (isa<AllocaInst>(Ptr)) {
11831         EraseInstFromFunction(SI);
11832         ++NumCombined;
11833         return 0;
11834       }
11835       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11836         if (isa<AllocaInst>(GEP->getOperand(0))) {
11837           if (GEP->getOperand(0)->hasOneUse()) {
11838             EraseInstFromFunction(SI);
11839             ++NumCombined;
11840             return 0;
11841           }
11842           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11843             EraseInstFromFunction(*DI);
11844             EraseInstFromFunction(SI);
11845             ++NumCombined;
11846             return 0;
11847           }
11848         }
11849       }
11850     }
11851     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11852       EraseInstFromFunction(*DI);
11853       EraseInstFromFunction(SI);
11854       ++NumCombined;
11855       return 0;
11856     }
11857   }
11858
11859   // Attempt to improve the alignment.
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   // Do really simple DSE, to catch cases where there are several consecutive
11868   // stores to the same location, separated by a few arithmetic operations. This
11869   // situation often occurs with bitfield accesses.
11870   BasicBlock::iterator BBI = &SI;
11871   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11872        --ScanInsts) {
11873     --BBI;
11874     // Don't count debug info directives, lest they affect codegen,
11875     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11876     // It is necessary for correctness to skip those that feed into a
11877     // llvm.dbg.declare, as these are not present when debugging is off.
11878     if (isa<DbgInfoIntrinsic>(BBI) ||
11879         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11880       ScanInsts++;
11881       continue;
11882     }    
11883     
11884     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11885       // Prev store isn't volatile, and stores to the same location?
11886       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11887                                                           SI.getOperand(1))) {
11888         ++NumDeadStore;
11889         ++BBI;
11890         EraseInstFromFunction(*PrevSI);
11891         continue;
11892       }
11893       break;
11894     }
11895     
11896     // If this is a load, we have to stop.  However, if the loaded value is from
11897     // the pointer we're loading and is producing the pointer we're storing,
11898     // then *this* store is dead (X = load P; store X -> P).
11899     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11900       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11901           !SI.isVolatile()) {
11902         EraseInstFromFunction(SI);
11903         ++NumCombined;
11904         return 0;
11905       }
11906       // Otherwise, this is a load from some other location.  Stores before it
11907       // may not be dead.
11908       break;
11909     }
11910     
11911     // Don't skip over loads or things that can modify memory.
11912     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11913       break;
11914   }
11915   
11916   
11917   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11918
11919   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11920   if (isa<ConstantPointerNull>(Ptr) &&
11921       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11922     if (!isa<UndefValue>(Val)) {
11923       SI.setOperand(0, Context->getUndef(Val->getType()));
11924       if (Instruction *U = dyn_cast<Instruction>(Val))
11925         AddToWorkList(U);  // Dropped a use.
11926       ++NumCombined;
11927     }
11928     return 0;  // Do not modify these!
11929   }
11930
11931   // store undef, Ptr -> noop
11932   if (isa<UndefValue>(Val)) {
11933     EraseInstFromFunction(SI);
11934     ++NumCombined;
11935     return 0;
11936   }
11937
11938   // If the pointer destination is a cast, see if we can fold the cast into the
11939   // source instead.
11940   if (isa<CastInst>(Ptr))
11941     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11942       return Res;
11943   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11944     if (CE->isCast())
11945       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11946         return Res;
11947
11948   
11949   // If this store is the last instruction in the basic block (possibly
11950   // excepting debug info instructions and the pointer bitcasts that feed
11951   // into them), and if the block ends with an unconditional branch, try
11952   // to move it to the successor block.
11953   BBI = &SI; 
11954   do {
11955     ++BBI;
11956   } while (isa<DbgInfoIntrinsic>(BBI) ||
11957            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11958   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11959     if (BI->isUnconditional())
11960       if (SimplifyStoreAtEndOfBlock(SI))
11961         return 0;  // xform done!
11962   
11963   return 0;
11964 }
11965
11966 /// SimplifyStoreAtEndOfBlock - Turn things like:
11967 ///   if () { *P = v1; } else { *P = v2 }
11968 /// into a phi node with a store in the successor.
11969 ///
11970 /// Simplify things like:
11971 ///   *P = v1; if () { *P = v2; }
11972 /// into a phi node with a store in the successor.
11973 ///
11974 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11975   BasicBlock *StoreBB = SI.getParent();
11976   
11977   // Check to see if the successor block has exactly two incoming edges.  If
11978   // so, see if the other predecessor contains a store to the same location.
11979   // if so, insert a PHI node (if needed) and move the stores down.
11980   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11981   
11982   // Determine whether Dest has exactly two predecessors and, if so, compute
11983   // the other predecessor.
11984   pred_iterator PI = pred_begin(DestBB);
11985   BasicBlock *OtherBB = 0;
11986   if (*PI != StoreBB)
11987     OtherBB = *PI;
11988   ++PI;
11989   if (PI == pred_end(DestBB))
11990     return false;
11991   
11992   if (*PI != StoreBB) {
11993     if (OtherBB)
11994       return false;
11995     OtherBB = *PI;
11996   }
11997   if (++PI != pred_end(DestBB))
11998     return false;
11999
12000   // Bail out if all the relevant blocks aren't distinct (this can happen,
12001   // for example, if SI is in an infinite loop)
12002   if (StoreBB == DestBB || OtherBB == DestBB)
12003     return false;
12004
12005   // Verify that the other block ends in a branch and is not otherwise empty.
12006   BasicBlock::iterator BBI = OtherBB->getTerminator();
12007   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12008   if (!OtherBr || BBI == OtherBB->begin())
12009     return false;
12010   
12011   // If the other block ends in an unconditional branch, check for the 'if then
12012   // else' case.  there is an instruction before the branch.
12013   StoreInst *OtherStore = 0;
12014   if (OtherBr->isUnconditional()) {
12015     --BBI;
12016     // Skip over debugging info.
12017     while (isa<DbgInfoIntrinsic>(BBI) ||
12018            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12019       if (BBI==OtherBB->begin())
12020         return false;
12021       --BBI;
12022     }
12023     // If this isn't a store, or isn't a store to the same location, bail out.
12024     OtherStore = dyn_cast<StoreInst>(BBI);
12025     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12026       return false;
12027   } else {
12028     // Otherwise, the other block ended with a conditional branch. If one of the
12029     // destinations is StoreBB, then we have the if/then case.
12030     if (OtherBr->getSuccessor(0) != StoreBB && 
12031         OtherBr->getSuccessor(1) != StoreBB)
12032       return false;
12033     
12034     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12035     // if/then triangle.  See if there is a store to the same ptr as SI that
12036     // lives in OtherBB.
12037     for (;; --BBI) {
12038       // Check to see if we find the matching store.
12039       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12040         if (OtherStore->getOperand(1) != SI.getOperand(1))
12041           return false;
12042         break;
12043       }
12044       // If we find something that may be using or overwriting the stored
12045       // value, or if we run out of instructions, we can't do the xform.
12046       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12047           BBI == OtherBB->begin())
12048         return false;
12049     }
12050     
12051     // In order to eliminate the store in OtherBr, we have to
12052     // make sure nothing reads or overwrites the stored value in
12053     // StoreBB.
12054     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12055       // FIXME: This should really be AA driven.
12056       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12057         return false;
12058     }
12059   }
12060   
12061   // Insert a PHI node now if we need it.
12062   Value *MergedVal = OtherStore->getOperand(0);
12063   if (MergedVal != SI.getOperand(0)) {
12064     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12065     PN->reserveOperandSpace(2);
12066     PN->addIncoming(SI.getOperand(0), SI.getParent());
12067     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12068     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12069   }
12070   
12071   // Advance to a place where it is safe to insert the new store and
12072   // insert it.
12073   BBI = DestBB->getFirstNonPHI();
12074   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12075                                     OtherStore->isVolatile()), *BBI);
12076   
12077   // Nuke the old stores.
12078   EraseInstFromFunction(SI);
12079   EraseInstFromFunction(*OtherStore);
12080   ++NumCombined;
12081   return true;
12082 }
12083
12084
12085 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12086   // Change br (not X), label True, label False to: br X, label False, True
12087   Value *X = 0;
12088   BasicBlock *TrueDest;
12089   BasicBlock *FalseDest;
12090   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12091       !isa<Constant>(X)) {
12092     // Swap Destinations and condition...
12093     BI.setCondition(X);
12094     BI.setSuccessor(0, FalseDest);
12095     BI.setSuccessor(1, TrueDest);
12096     return &BI;
12097   }
12098
12099   // Cannonicalize fcmp_one -> fcmp_oeq
12100   FCmpInst::Predicate FPred; Value *Y;
12101   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12102                              TrueDest, FalseDest), *Context))
12103     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12104          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12105       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12106       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12107       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12108       NewSCC->takeName(I);
12109       // Swap Destinations and condition...
12110       BI.setCondition(NewSCC);
12111       BI.setSuccessor(0, FalseDest);
12112       BI.setSuccessor(1, TrueDest);
12113       RemoveFromWorkList(I);
12114       I->eraseFromParent();
12115       AddToWorkList(NewSCC);
12116       return &BI;
12117     }
12118
12119   // Cannonicalize icmp_ne -> icmp_eq
12120   ICmpInst::Predicate IPred;
12121   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12122                       TrueDest, FalseDest), *Context))
12123     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12124          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12125          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12126       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12127       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12128       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12129       NewSCC->takeName(I);
12130       // Swap Destinations and condition...
12131       BI.setCondition(NewSCC);
12132       BI.setSuccessor(0, FalseDest);
12133       BI.setSuccessor(1, TrueDest);
12134       RemoveFromWorkList(I);
12135       I->eraseFromParent();;
12136       AddToWorkList(NewSCC);
12137       return &BI;
12138     }
12139
12140   return 0;
12141 }
12142
12143 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12144   Value *Cond = SI.getCondition();
12145   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12146     if (I->getOpcode() == Instruction::Add)
12147       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12148         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12149         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12150           SI.setOperand(i,
12151                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12152                                                 AddRHS));
12153         SI.setOperand(0, I->getOperand(0));
12154         AddToWorkList(I);
12155         return &SI;
12156       }
12157   }
12158   return 0;
12159 }
12160
12161 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12162   Value *Agg = EV.getAggregateOperand();
12163
12164   if (!EV.hasIndices())
12165     return ReplaceInstUsesWith(EV, Agg);
12166
12167   if (Constant *C = dyn_cast<Constant>(Agg)) {
12168     if (isa<UndefValue>(C))
12169       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12170       
12171     if (isa<ConstantAggregateZero>(C))
12172       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12173
12174     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12175       // Extract the element indexed by the first index out of the constant
12176       Value *V = C->getOperand(*EV.idx_begin());
12177       if (EV.getNumIndices() > 1)
12178         // Extract the remaining indices out of the constant indexed by the
12179         // first index
12180         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12181       else
12182         return ReplaceInstUsesWith(EV, V);
12183     }
12184     return 0; // Can't handle other constants
12185   } 
12186   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12187     // We're extracting from an insertvalue instruction, compare the indices
12188     const unsigned *exti, *exte, *insi, *inse;
12189     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12190          exte = EV.idx_end(), inse = IV->idx_end();
12191          exti != exte && insi != inse;
12192          ++exti, ++insi) {
12193       if (*insi != *exti)
12194         // The insert and extract both reference distinctly different elements.
12195         // This means the extract is not influenced by the insert, and we can
12196         // replace the aggregate operand of the extract with the aggregate
12197         // operand of the insert. i.e., replace
12198         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12199         // %E = extractvalue { i32, { i32 } } %I, 0
12200         // with
12201         // %E = extractvalue { i32, { i32 } } %A, 0
12202         return ExtractValueInst::Create(IV->getAggregateOperand(),
12203                                         EV.idx_begin(), EV.idx_end());
12204     }
12205     if (exti == exte && insi == inse)
12206       // Both iterators are at the end: Index lists are identical. Replace
12207       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12208       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12209       // with "i32 42"
12210       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12211     if (exti == exte) {
12212       // The extract list is a prefix of the insert list. i.e. replace
12213       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12214       // %E = extractvalue { i32, { i32 } } %I, 1
12215       // with
12216       // %X = extractvalue { i32, { i32 } } %A, 1
12217       // %E = insertvalue { i32 } %X, i32 42, 0
12218       // by switching the order of the insert and extract (though the
12219       // insertvalue should be left in, since it may have other uses).
12220       Value *NewEV = InsertNewInstBefore(
12221         ExtractValueInst::Create(IV->getAggregateOperand(),
12222                                  EV.idx_begin(), EV.idx_end()),
12223         EV);
12224       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12225                                      insi, inse);
12226     }
12227     if (insi == inse)
12228       // The insert list is a prefix of the extract list
12229       // We can simply remove the common indices from the extract and make it
12230       // operate on the inserted value instead of the insertvalue result.
12231       // i.e., replace
12232       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12233       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12234       // with
12235       // %E extractvalue { i32 } { i32 42 }, 0
12236       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12237                                       exti, exte);
12238   }
12239   // Can't simplify extracts from other values. Note that nested extracts are
12240   // already simplified implicitely by the above (extract ( extract (insert) )
12241   // will be translated into extract ( insert ( extract ) ) first and then just
12242   // the value inserted, if appropriate).
12243   return 0;
12244 }
12245
12246 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12247 /// is to leave as a vector operation.
12248 static bool CheapToScalarize(Value *V, bool isConstant) {
12249   if (isa<ConstantAggregateZero>(V)) 
12250     return true;
12251   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12252     if (isConstant) return true;
12253     // If all elts are the same, we can extract.
12254     Constant *Op0 = C->getOperand(0);
12255     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12256       if (C->getOperand(i) != Op0)
12257         return false;
12258     return true;
12259   }
12260   Instruction *I = dyn_cast<Instruction>(V);
12261   if (!I) return false;
12262   
12263   // Insert element gets simplified to the inserted element or is deleted if
12264   // this is constant idx extract element and its a constant idx insertelt.
12265   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12266       isa<ConstantInt>(I->getOperand(2)))
12267     return true;
12268   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12269     return true;
12270   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12271     if (BO->hasOneUse() &&
12272         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12273          CheapToScalarize(BO->getOperand(1), isConstant)))
12274       return true;
12275   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12276     if (CI->hasOneUse() &&
12277         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12278          CheapToScalarize(CI->getOperand(1), isConstant)))
12279       return true;
12280   
12281   return false;
12282 }
12283
12284 /// Read and decode a shufflevector mask.
12285 ///
12286 /// It turns undef elements into values that are larger than the number of
12287 /// elements in the input.
12288 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12289   unsigned NElts = SVI->getType()->getNumElements();
12290   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12291     return std::vector<unsigned>(NElts, 0);
12292   if (isa<UndefValue>(SVI->getOperand(2)))
12293     return std::vector<unsigned>(NElts, 2*NElts);
12294
12295   std::vector<unsigned> Result;
12296   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12297   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12298     if (isa<UndefValue>(*i))
12299       Result.push_back(NElts*2);  // undef -> 8
12300     else
12301       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12302   return Result;
12303 }
12304
12305 /// FindScalarElement - Given a vector and an element number, see if the scalar
12306 /// value is already around as a register, for example if it were inserted then
12307 /// extracted from the vector.
12308 static Value *FindScalarElement(Value *V, unsigned EltNo,
12309                                 LLVMContext *Context) {
12310   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12311   const VectorType *PTy = cast<VectorType>(V->getType());
12312   unsigned Width = PTy->getNumElements();
12313   if (EltNo >= Width)  // Out of range access.
12314     return Context->getUndef(PTy->getElementType());
12315   
12316   if (isa<UndefValue>(V))
12317     return Context->getUndef(PTy->getElementType());
12318   else if (isa<ConstantAggregateZero>(V))
12319     return Context->getNullValue(PTy->getElementType());
12320   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12321     return CP->getOperand(EltNo);
12322   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12323     // If this is an insert to a variable element, we don't know what it is.
12324     if (!isa<ConstantInt>(III->getOperand(2))) 
12325       return 0;
12326     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12327     
12328     // If this is an insert to the element we are looking for, return the
12329     // inserted value.
12330     if (EltNo == IIElt) 
12331       return III->getOperand(1);
12332     
12333     // Otherwise, the insertelement doesn't modify the value, recurse on its
12334     // vector input.
12335     return FindScalarElement(III->getOperand(0), EltNo, Context);
12336   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12337     unsigned LHSWidth =
12338       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12339     unsigned InEl = getShuffleMask(SVI)[EltNo];
12340     if (InEl < LHSWidth)
12341       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12342     else if (InEl < LHSWidth*2)
12343       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12344     else
12345       return Context->getUndef(PTy->getElementType());
12346   }
12347   
12348   // Otherwise, we don't know.
12349   return 0;
12350 }
12351
12352 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12353   // If vector val is undef, replace extract with scalar undef.
12354   if (isa<UndefValue>(EI.getOperand(0)))
12355     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12356
12357   // If vector val is constant 0, replace extract with scalar 0.
12358   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12359     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12360   
12361   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12362     // If vector val is constant with all elements the same, replace EI with
12363     // that element. When the elements are not identical, we cannot replace yet
12364     // (we do that below, but only when the index is constant).
12365     Constant *op0 = C->getOperand(0);
12366     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12367       if (C->getOperand(i) != op0) {
12368         op0 = 0; 
12369         break;
12370       }
12371     if (op0)
12372       return ReplaceInstUsesWith(EI, op0);
12373   }
12374   
12375   // If extracting a specified index from the vector, see if we can recursively
12376   // find a previously computed scalar that was inserted into the vector.
12377   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12378     unsigned IndexVal = IdxC->getZExtValue();
12379     unsigned VectorWidth = 
12380       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12381       
12382     // If this is extracting an invalid index, turn this into undef, to avoid
12383     // crashing the code below.
12384     if (IndexVal >= VectorWidth)
12385       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12386     
12387     // This instruction only demands the single element from the input vector.
12388     // If the input vector has a single use, simplify it based on this use
12389     // property.
12390     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12391       APInt UndefElts(VectorWidth, 0);
12392       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12393       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12394                                                 DemandedMask, UndefElts)) {
12395         EI.setOperand(0, V);
12396         return &EI;
12397       }
12398     }
12399     
12400     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12401       return ReplaceInstUsesWith(EI, Elt);
12402     
12403     // If the this extractelement is directly using a bitcast from a vector of
12404     // the same number of elements, see if we can find the source element from
12405     // it.  In this case, we will end up needing to bitcast the scalars.
12406     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12407       if (const VectorType *VT = 
12408               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12409         if (VT->getNumElements() == VectorWidth)
12410           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12411                                              IndexVal, Context))
12412             return new BitCastInst(Elt, EI.getType());
12413     }
12414   }
12415   
12416   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12417     if (I->hasOneUse()) {
12418       // Push extractelement into predecessor operation if legal and
12419       // profitable to do so
12420       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12421         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12422         if (CheapToScalarize(BO, isConstantElt)) {
12423           ExtractElementInst *newEI0 = 
12424             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12425                                    EI.getName()+".lhs");
12426           ExtractElementInst *newEI1 =
12427             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12428                                    EI.getName()+".rhs");
12429           InsertNewInstBefore(newEI0, EI);
12430           InsertNewInstBefore(newEI1, EI);
12431           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12432         }
12433       } else if (isa<LoadInst>(I)) {
12434         unsigned AS = 
12435           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12436         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12437                                   Context->getPointerType(EI.getType(), AS),EI);
12438         GetElementPtrInst *GEP =
12439           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12440         InsertNewInstBefore(GEP, EI);
12441         return new LoadInst(GEP);
12442       }
12443     }
12444     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12445       // Extracting the inserted element?
12446       if (IE->getOperand(2) == EI.getOperand(1))
12447         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12448       // If the inserted and extracted elements are constants, they must not
12449       // be the same value, extract from the pre-inserted value instead.
12450       if (isa<Constant>(IE->getOperand(2)) &&
12451           isa<Constant>(EI.getOperand(1))) {
12452         AddUsesToWorkList(EI);
12453         EI.setOperand(0, IE->getOperand(0));
12454         return &EI;
12455       }
12456     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12457       // If this is extracting an element from a shufflevector, figure out where
12458       // it came from and extract from the appropriate input element instead.
12459       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12460         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12461         Value *Src;
12462         unsigned LHSWidth =
12463           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12464
12465         if (SrcIdx < LHSWidth)
12466           Src = SVI->getOperand(0);
12467         else if (SrcIdx < LHSWidth*2) {
12468           SrcIdx -= LHSWidth;
12469           Src = SVI->getOperand(1);
12470         } else {
12471           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12472         }
12473         return new ExtractElementInst(Src,
12474                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12475       }
12476     }
12477   }
12478   return 0;
12479 }
12480
12481 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12482 /// elements from either LHS or RHS, return the shuffle mask and true. 
12483 /// Otherwise, return false.
12484 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12485                                          std::vector<Constant*> &Mask,
12486                                          LLVMContext *Context) {
12487   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12488          "Invalid CollectSingleShuffleElements");
12489   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12490
12491   if (isa<UndefValue>(V)) {
12492     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12493     return true;
12494   } else if (V == LHS) {
12495     for (unsigned i = 0; i != NumElts; ++i)
12496       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12497     return true;
12498   } else if (V == RHS) {
12499     for (unsigned i = 0; i != NumElts; ++i)
12500       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12501     return true;
12502   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12503     // If this is an insert of an extract from some other vector, include it.
12504     Value *VecOp    = IEI->getOperand(0);
12505     Value *ScalarOp = IEI->getOperand(1);
12506     Value *IdxOp    = IEI->getOperand(2);
12507     
12508     if (!isa<ConstantInt>(IdxOp))
12509       return false;
12510     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12511     
12512     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12513       // Okay, we can handle this if the vector we are insertinting into is
12514       // transitively ok.
12515       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12516         // If so, update the mask to reflect the inserted undef.
12517         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12518         return true;
12519       }      
12520     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12521       if (isa<ConstantInt>(EI->getOperand(1)) &&
12522           EI->getOperand(0)->getType() == V->getType()) {
12523         unsigned ExtractedIdx =
12524           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12525         
12526         // This must be extracting from either LHS or RHS.
12527         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12528           // Okay, we can handle this if the vector we are insertinting into is
12529           // transitively ok.
12530           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12531             // If so, update the mask to reflect the inserted value.
12532             if (EI->getOperand(0) == LHS) {
12533               Mask[InsertedIdx % NumElts] = 
12534                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12535             } else {
12536               assert(EI->getOperand(0) == RHS);
12537               Mask[InsertedIdx % NumElts] = 
12538                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12539               
12540             }
12541             return true;
12542           }
12543         }
12544       }
12545     }
12546   }
12547   // TODO: Handle shufflevector here!
12548   
12549   return false;
12550 }
12551
12552 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12553 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12554 /// that computes V and the LHS value of the shuffle.
12555 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12556                                      Value *&RHS, LLVMContext *Context) {
12557   assert(isa<VectorType>(V->getType()) && 
12558          (RHS == 0 || V->getType() == RHS->getType()) &&
12559          "Invalid shuffle!");
12560   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12561
12562   if (isa<UndefValue>(V)) {
12563     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12564     return V;
12565   } else if (isa<ConstantAggregateZero>(V)) {
12566     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12567     return V;
12568   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12569     // If this is an insert of an extract from some other vector, include it.
12570     Value *VecOp    = IEI->getOperand(0);
12571     Value *ScalarOp = IEI->getOperand(1);
12572     Value *IdxOp    = IEI->getOperand(2);
12573     
12574     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12575       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12576           EI->getOperand(0)->getType() == V->getType()) {
12577         unsigned ExtractedIdx =
12578           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12579         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12580         
12581         // Either the extracted from or inserted into vector must be RHSVec,
12582         // otherwise we'd end up with a shuffle of three inputs.
12583         if (EI->getOperand(0) == RHS || RHS == 0) {
12584           RHS = EI->getOperand(0);
12585           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12586           Mask[InsertedIdx % NumElts] = 
12587             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12588           return V;
12589         }
12590         
12591         if (VecOp == RHS) {
12592           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12593                                             RHS, Context);
12594           // Everything but the extracted element is replaced with the RHS.
12595           for (unsigned i = 0; i != NumElts; ++i) {
12596             if (i != InsertedIdx)
12597               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12598           }
12599           return V;
12600         }
12601         
12602         // If this insertelement is a chain that comes from exactly these two
12603         // vectors, return the vector and the effective shuffle.
12604         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12605                                          Context))
12606           return EI->getOperand(0);
12607         
12608       }
12609     }
12610   }
12611   // TODO: Handle shufflevector here!
12612   
12613   // Otherwise, can't do anything fancy.  Return an identity vector.
12614   for (unsigned i = 0; i != NumElts; ++i)
12615     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12616   return V;
12617 }
12618
12619 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12620   Value *VecOp    = IE.getOperand(0);
12621   Value *ScalarOp = IE.getOperand(1);
12622   Value *IdxOp    = IE.getOperand(2);
12623   
12624   // Inserting an undef or into an undefined place, remove this.
12625   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12626     ReplaceInstUsesWith(IE, VecOp);
12627   
12628   // If the inserted element was extracted from some other vector, and if the 
12629   // indexes are constant, try to turn this into a shufflevector operation.
12630   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12631     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12632         EI->getOperand(0)->getType() == IE.getType()) {
12633       unsigned NumVectorElts = IE.getType()->getNumElements();
12634       unsigned ExtractedIdx =
12635         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12636       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12637       
12638       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12639         return ReplaceInstUsesWith(IE, VecOp);
12640       
12641       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12642         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12643       
12644       // If we are extracting a value from a vector, then inserting it right
12645       // back into the same place, just use the input vector.
12646       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12647         return ReplaceInstUsesWith(IE, VecOp);      
12648       
12649       // We could theoretically do this for ANY input.  However, doing so could
12650       // turn chains of insertelement instructions into a chain of shufflevector
12651       // instructions, and right now we do not merge shufflevectors.  As such,
12652       // only do this in a situation where it is clear that there is benefit.
12653       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12654         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12655         // the values of VecOp, except then one read from EIOp0.
12656         // Build a new shuffle mask.
12657         std::vector<Constant*> Mask;
12658         if (isa<UndefValue>(VecOp))
12659           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12660         else {
12661           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12662           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12663                                                        NumVectorElts));
12664         } 
12665         Mask[InsertedIdx] = 
12666                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12667         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12668                                      Context->getConstantVector(Mask));
12669       }
12670       
12671       // If this insertelement isn't used by some other insertelement, turn it
12672       // (and any insertelements it points to), into one big shuffle.
12673       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12674         std::vector<Constant*> Mask;
12675         Value *RHS = 0;
12676         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12677         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12678         // We now have a shuffle of LHS, RHS, Mask.
12679         return new ShuffleVectorInst(LHS, RHS,
12680                                      Context->getConstantVector(Mask));
12681       }
12682     }
12683   }
12684
12685   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12686   APInt UndefElts(VWidth, 0);
12687   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12688   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12689     return &IE;
12690
12691   return 0;
12692 }
12693
12694
12695 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12696   Value *LHS = SVI.getOperand(0);
12697   Value *RHS = SVI.getOperand(1);
12698   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12699
12700   bool MadeChange = false;
12701
12702   // Undefined shuffle mask -> undefined value.
12703   if (isa<UndefValue>(SVI.getOperand(2)))
12704     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12705
12706   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12707
12708   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12709     return 0;
12710
12711   APInt UndefElts(VWidth, 0);
12712   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12713   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12714     LHS = SVI.getOperand(0);
12715     RHS = SVI.getOperand(1);
12716     MadeChange = true;
12717   }
12718   
12719   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12720   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12721   if (LHS == RHS || isa<UndefValue>(LHS)) {
12722     if (isa<UndefValue>(LHS) && LHS == RHS) {
12723       // shuffle(undef,undef,mask) -> undef.
12724       return ReplaceInstUsesWith(SVI, LHS);
12725     }
12726     
12727     // Remap any references to RHS to use LHS.
12728     std::vector<Constant*> Elts;
12729     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12730       if (Mask[i] >= 2*e)
12731         Elts.push_back(Context->getUndef(Type::Int32Ty));
12732       else {
12733         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12734             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12735           Mask[i] = 2*e;     // Turn into undef.
12736           Elts.push_back(Context->getUndef(Type::Int32Ty));
12737         } else {
12738           Mask[i] = Mask[i] % e;  // Force to LHS.
12739           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12740         }
12741       }
12742     }
12743     SVI.setOperand(0, SVI.getOperand(1));
12744     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12745     SVI.setOperand(2, Context->getConstantVector(Elts));
12746     LHS = SVI.getOperand(0);
12747     RHS = SVI.getOperand(1);
12748     MadeChange = true;
12749   }
12750   
12751   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12752   bool isLHSID = true, isRHSID = true;
12753     
12754   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12755     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12756     // Is this an identity shuffle of the LHS value?
12757     isLHSID &= (Mask[i] == i);
12758       
12759     // Is this an identity shuffle of the RHS value?
12760     isRHSID &= (Mask[i]-e == i);
12761   }
12762
12763   // Eliminate identity shuffles.
12764   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12765   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12766   
12767   // If the LHS is a shufflevector itself, see if we can combine it with this
12768   // one without producing an unusual shuffle.  Here we are really conservative:
12769   // we are absolutely afraid of producing a shuffle mask not in the input
12770   // program, because the code gen may not be smart enough to turn a merged
12771   // shuffle into two specific shuffles: it may produce worse code.  As such,
12772   // we only merge two shuffles if the result is one of the two input shuffle
12773   // masks.  In this case, merging the shuffles just removes one instruction,
12774   // which we know is safe.  This is good for things like turning:
12775   // (splat(splat)) -> splat.
12776   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12777     if (isa<UndefValue>(RHS)) {
12778       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12779
12780       std::vector<unsigned> NewMask;
12781       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12782         if (Mask[i] >= 2*e)
12783           NewMask.push_back(2*e);
12784         else
12785           NewMask.push_back(LHSMask[Mask[i]]);
12786       
12787       // If the result mask is equal to the src shuffle or this shuffle mask, do
12788       // the replacement.
12789       if (NewMask == LHSMask || NewMask == Mask) {
12790         unsigned LHSInNElts =
12791           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12792         std::vector<Constant*> Elts;
12793         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12794           if (NewMask[i] >= LHSInNElts*2) {
12795             Elts.push_back(Context->getUndef(Type::Int32Ty));
12796           } else {
12797             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12798           }
12799         }
12800         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12801                                      LHSSVI->getOperand(1),
12802                                      Context->getConstantVector(Elts));
12803       }
12804     }
12805   }
12806
12807   return MadeChange ? &SVI : 0;
12808 }
12809
12810
12811
12812
12813 /// TryToSinkInstruction - Try to move the specified instruction from its
12814 /// current block into the beginning of DestBlock, which can only happen if it's
12815 /// safe to move the instruction past all of the instructions between it and the
12816 /// end of its block.
12817 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12818   assert(I->hasOneUse() && "Invariants didn't hold!");
12819
12820   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12821   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12822     return false;
12823
12824   // Do not sink alloca instructions out of the entry block.
12825   if (isa<AllocaInst>(I) && I->getParent() ==
12826         &DestBlock->getParent()->getEntryBlock())
12827     return false;
12828
12829   // We can only sink load instructions if there is nothing between the load and
12830   // the end of block that could change the value.
12831   if (I->mayReadFromMemory()) {
12832     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12833          Scan != E; ++Scan)
12834       if (Scan->mayWriteToMemory())
12835         return false;
12836   }
12837
12838   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12839
12840   CopyPrecedingStopPoint(I, InsertPos);
12841   I->moveBefore(InsertPos);
12842   ++NumSunkInst;
12843   return true;
12844 }
12845
12846
12847 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12848 /// all reachable code to the worklist.
12849 ///
12850 /// This has a couple of tricks to make the code faster and more powerful.  In
12851 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12852 /// them to the worklist (this significantly speeds up instcombine on code where
12853 /// many instructions are dead or constant).  Additionally, if we find a branch
12854 /// whose condition is a known constant, we only visit the reachable successors.
12855 ///
12856 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12857                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12858                                        InstCombiner &IC,
12859                                        const TargetData *TD) {
12860   SmallVector<BasicBlock*, 256> Worklist;
12861   Worklist.push_back(BB);
12862
12863   while (!Worklist.empty()) {
12864     BB = Worklist.back();
12865     Worklist.pop_back();
12866     
12867     // We have now visited this block!  If we've already been here, ignore it.
12868     if (!Visited.insert(BB)) continue;
12869
12870     DbgInfoIntrinsic *DBI_Prev = NULL;
12871     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12872       Instruction *Inst = BBI++;
12873       
12874       // DCE instruction if trivially dead.
12875       if (isInstructionTriviallyDead(Inst)) {
12876         ++NumDeadInst;
12877         DOUT << "IC: DCE: " << *Inst;
12878         Inst->eraseFromParent();
12879         continue;
12880       }
12881       
12882       // ConstantProp instruction if trivially constant.
12883       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12884         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12885         Inst->replaceAllUsesWith(C);
12886         ++NumConstProp;
12887         Inst->eraseFromParent();
12888         continue;
12889       }
12890      
12891       // If there are two consecutive llvm.dbg.stoppoint calls then
12892       // it is likely that the optimizer deleted code in between these
12893       // two intrinsics. 
12894       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12895       if (DBI_Next) {
12896         if (DBI_Prev
12897             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12898             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12899           IC.RemoveFromWorkList(DBI_Prev);
12900           DBI_Prev->eraseFromParent();
12901         }
12902         DBI_Prev = DBI_Next;
12903       } else {
12904         DBI_Prev = 0;
12905       }
12906
12907       IC.AddToWorkList(Inst);
12908     }
12909
12910     // Recursively visit successors.  If this is a branch or switch on a
12911     // constant, only visit the reachable successor.
12912     TerminatorInst *TI = BB->getTerminator();
12913     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12914       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12915         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12916         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12917         Worklist.push_back(ReachableBB);
12918         continue;
12919       }
12920     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12921       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12922         // See if this is an explicit destination.
12923         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12924           if (SI->getCaseValue(i) == Cond) {
12925             BasicBlock *ReachableBB = SI->getSuccessor(i);
12926             Worklist.push_back(ReachableBB);
12927             continue;
12928           }
12929         
12930         // Otherwise it is the default destination.
12931         Worklist.push_back(SI->getSuccessor(0));
12932         continue;
12933       }
12934     }
12935     
12936     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12937       Worklist.push_back(TI->getSuccessor(i));
12938   }
12939 }
12940
12941 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12942   bool Changed = false;
12943   TD = &getAnalysis<TargetData>();
12944   
12945   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12946              << F.getNameStr() << "\n");
12947
12948   {
12949     // Do a depth-first traversal of the function, populate the worklist with
12950     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12951     // track of which blocks we visit.
12952     SmallPtrSet<BasicBlock*, 64> Visited;
12953     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12954
12955     // Do a quick scan over the function.  If we find any blocks that are
12956     // unreachable, remove any instructions inside of them.  This prevents
12957     // the instcombine code from having to deal with some bad special cases.
12958     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12959       if (!Visited.count(BB)) {
12960         Instruction *Term = BB->getTerminator();
12961         while (Term != BB->begin()) {   // Remove instrs bottom-up
12962           BasicBlock::iterator I = Term; --I;
12963
12964           DOUT << "IC: DCE: " << *I;
12965           // A debug intrinsic shouldn't force another iteration if we weren't
12966           // going to do one without it.
12967           if (!isa<DbgInfoIntrinsic>(I)) {
12968             ++NumDeadInst;
12969             Changed = true;
12970           }
12971           if (!I->use_empty())
12972             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12973           I->eraseFromParent();
12974         }
12975       }
12976   }
12977
12978   while (!Worklist.empty()) {
12979     Instruction *I = RemoveOneFromWorkList();
12980     if (I == 0) continue;  // skip null values.
12981
12982     // Check to see if we can DCE the instruction.
12983     if (isInstructionTriviallyDead(I)) {
12984       // Add operands to the worklist.
12985       if (I->getNumOperands() < 4)
12986         AddUsesToWorkList(*I);
12987       ++NumDeadInst;
12988
12989       DOUT << "IC: DCE: " << *I;
12990
12991       I->eraseFromParent();
12992       RemoveFromWorkList(I);
12993       Changed = true;
12994       continue;
12995     }
12996
12997     // Instruction isn't dead, see if we can constant propagate it.
12998     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12999       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13000
13001       // Add operands to the worklist.
13002       AddUsesToWorkList(*I);
13003       ReplaceInstUsesWith(*I, C);
13004
13005       ++NumConstProp;
13006       I->eraseFromParent();
13007       RemoveFromWorkList(I);
13008       Changed = true;
13009       continue;
13010     }
13011
13012     if (TD) {
13013       // See if we can constant fold its operands.
13014       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13015         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13016           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13017                                   F.getContext(), TD))
13018             if (NewC != CE) {
13019               i->set(NewC);
13020               Changed = true;
13021             }
13022     }
13023
13024     // See if we can trivially sink this instruction to a successor basic block.
13025     if (I->hasOneUse()) {
13026       BasicBlock *BB = I->getParent();
13027       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13028       if (UserParent != BB) {
13029         bool UserIsSuccessor = false;
13030         // See if the user is one of our successors.
13031         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13032           if (*SI == UserParent) {
13033             UserIsSuccessor = true;
13034             break;
13035           }
13036
13037         // If the user is one of our immediate successors, and if that successor
13038         // only has us as a predecessors (we'd have to split the critical edge
13039         // otherwise), we can keep going.
13040         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13041             next(pred_begin(UserParent)) == pred_end(UserParent))
13042           // Okay, the CFG is simple enough, try to sink this instruction.
13043           Changed |= TryToSinkInstruction(I, UserParent);
13044       }
13045     }
13046
13047     // Now that we have an instruction, try combining it to simplify it...
13048 #ifndef NDEBUG
13049     std::string OrigI;
13050 #endif
13051     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13052     if (Instruction *Result = visit(*I)) {
13053       ++NumCombined;
13054       // Should we replace the old instruction with a new one?
13055       if (Result != I) {
13056         DOUT << "IC: Old = " << *I
13057              << "    New = " << *Result;
13058
13059         // Everything uses the new instruction now.
13060         I->replaceAllUsesWith(Result);
13061
13062         // Push the new instruction and any users onto the worklist.
13063         AddToWorkList(Result);
13064         AddUsersToWorkList(*Result);
13065
13066         // Move the name to the new instruction first.
13067         Result->takeName(I);
13068
13069         // Insert the new instruction into the basic block...
13070         BasicBlock *InstParent = I->getParent();
13071         BasicBlock::iterator InsertPos = I;
13072
13073         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13074           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13075             ++InsertPos;
13076
13077         InstParent->getInstList().insert(InsertPos, Result);
13078
13079         // Make sure that we reprocess all operands now that we reduced their
13080         // use counts.
13081         AddUsesToWorkList(*I);
13082
13083         // Instructions can end up on the worklist more than once.  Make sure
13084         // we do not process an instruction that has been deleted.
13085         RemoveFromWorkList(I);
13086
13087         // Erase the old instruction.
13088         InstParent->getInstList().erase(I);
13089       } else {
13090 #ifndef NDEBUG
13091         DOUT << "IC: Mod = " << OrigI
13092              << "    New = " << *I;
13093 #endif
13094
13095         // If the instruction was modified, it's possible that it is now dead.
13096         // if so, remove it.
13097         if (isInstructionTriviallyDead(I)) {
13098           // Make sure we process all operands now that we are reducing their
13099           // use counts.
13100           AddUsesToWorkList(*I);
13101
13102           // Instructions may end up in the worklist more than once.  Erase all
13103           // occurrences of this instruction.
13104           RemoveFromWorkList(I);
13105           I->eraseFromParent();
13106         } else {
13107           AddToWorkList(I);
13108           AddUsersToWorkList(*I);
13109         }
13110       }
13111       Changed = true;
13112     }
13113   }
13114
13115   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13116     
13117   // Do an explicit clear, this shrinks the map if needed.
13118   WorklistMap.clear();
13119   return Changed;
13120 }
13121
13122
13123 bool InstCombiner::runOnFunction(Function &F) {
13124   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13125   
13126   bool EverMadeChange = false;
13127
13128   // Iterate while there is work to do.
13129   unsigned Iteration = 0;
13130   while (DoOneIteration(F, Iteration++))
13131     EverMadeChange = true;
13132   return EverMadeChange;
13133 }
13134
13135 FunctionPass *llvm::createInstructionCombiningPass() {
13136   return new InstCombiner();
13137 }