Remove dead check.
[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 (Operator *O = dyn_cast<Operator>(V)) {
445     if (O->getOpcode() == Instruction::BitCast)
446       return O->getOperand(0);
447     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
448       if (GEP->hasAllZeroIndices())
449         return GEP->getPointerOperand();
450   }
451   return 0;
452 }
453
454 /// This function is a wrapper around CastInst::isEliminableCastPair. It
455 /// simply extracts arguments and returns what that function returns.
456 static Instruction::CastOps 
457 isEliminableCastPair(
458   const CastInst *CI, ///< The first cast instruction
459   unsigned opcode,       ///< The opcode of the second cast instruction
460   const Type *DstTy,     ///< The target type for the second cast instruction
461   TargetData *TD         ///< The target data for pointer size
462 ) {
463   
464   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
465   const Type *MidTy = CI->getType();                  // B from above
466
467   // Get the opcodes of the two Cast instructions
468   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
469   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
470
471   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
472                                                 DstTy, TD->getIntPtrType());
473   
474   // We don't want to form an inttoptr or ptrtoint that converts to an integer
475   // type that differs from the pointer size.
476   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
477       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
478     Res = 0;
479   
480   return Instruction::CastOps(Res);
481 }
482
483 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
484 /// in any code being generated.  It does not require codegen if V is simple
485 /// enough or if the cast can be folded into other casts.
486 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
487                               const Type *Ty, TargetData *TD) {
488   if (V->getType() == Ty || isa<Constant>(V)) return false;
489   
490   // If this is another cast that can be eliminated, it isn't codegen either.
491   if (const CastInst *CI = dyn_cast<CastInst>(V))
492     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
493       return false;
494   return true;
495 }
496
497 // SimplifyCommutative - This performs a few simplifications for commutative
498 // operators:
499 //
500 //  1. Order operands such that they are listed from right (least complex) to
501 //     left (most complex).  This puts constants before unary operators before
502 //     binary operators.
503 //
504 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
505 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
506 //
507 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
508   bool Changed = false;
509   if (getComplexity(Context, I.getOperand(0)) < 
510       getComplexity(Context, I.getOperand(1)))
511     Changed = !I.swapOperands();
512
513   if (!I.isAssociative()) return Changed;
514   Instruction::BinaryOps Opcode = I.getOpcode();
515   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517       if (isa<Constant>(I.getOperand(1))) {
518         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
519                                              cast<Constant>(I.getOperand(1)),
520                                              cast<Constant>(Op->getOperand(1)));
521         I.setOperand(0, Op->getOperand(0));
522         I.setOperand(1, Folded);
523         return true;
524       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526             isOnlyUse(Op) && isOnlyUse(Op1)) {
527           Constant *C1 = cast<Constant>(Op->getOperand(1));
528           Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
532           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
533                                                     Op1->getOperand(0),
534                                                     Op1->getName(), &I);
535           AddToWorkList(New);
536           I.setOperand(0, New);
537           I.setOperand(1, Folded);
538           return true;
539         }
540     }
541   return Changed;
542 }
543
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548   if (getComplexity(Context, I.getOperand(0)) >=
549       getComplexity(Context, I.getOperand(1)))
550     return false;
551   I.swapOperands();
552   // Compare instructions are not associative so there's nothing else we can do.
553   return true;
554 }
555
556 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557 // if the LHS is a constant zero (which is the 'negate' form).
558 //
559 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
560   if (BinaryOperator::isNeg(V))
561     return BinaryOperator::getNegArgument(V);
562
563   // Constants can be considered to be negated values if they can be folded.
564   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565     return Context->getConstantExprNeg(C);
566
567   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568     if (C->getType()->getElementType()->isInteger())
569       return Context->getConstantExprNeg(C);
570
571   return 0;
572 }
573
574 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
575 // instruction if the LHS is a constant negative zero (which is the 'negate'
576 // form).
577 //
578 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
579   if (BinaryOperator::isFNeg(V))
580     return BinaryOperator::getFNegArgument(V);
581
582   // Constants can be considered to be negated values if they can be folded.
583   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
584     return Context->getConstantExprFNeg(C);
585
586   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587     if (C->getType()->getElementType()->isFloatingPoint())
588       return Context->getConstantExprFNeg(C);
589
590   return 0;
591 }
592
593 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
594   if (BinaryOperator::isNot(V))
595     return BinaryOperator::getNotArgument(V);
596
597   // Constants can be considered to be not'ed values...
598   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
599     return Context->getConstantInt(~C->getValue());
600   return 0;
601 }
602
603 // dyn_castFoldableMul - If this value is a multiply that can be folded into
604 // other computations (because it has a constant operand), return the
605 // non-constant operand of the multiply, and set CST to point to the multiplier.
606 // Otherwise, return null.
607 //
608 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
609                                          LLVMContext *Context) {
610   if (V->hasOneUse() && V->getType()->isInteger())
611     if (Instruction *I = dyn_cast<Instruction>(V)) {
612       if (I->getOpcode() == Instruction::Mul)
613         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
614           return I->getOperand(0);
615       if (I->getOpcode() == Instruction::Shl)
616         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
617           // The multiplier is really 1 << CST.
618           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
619           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
620           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
621           return I->getOperand(0);
622         }
623     }
624   return 0;
625 }
626
627 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
628 /// expression, return it.
629 static User *dyn_castGetElementPtr(Value *V) {
630   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
631   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
632     if (CE->getOpcode() == Instruction::GetElementPtr)
633       return cast<User>(V);
634   return false;
635 }
636
637 /// AddOne - Add one to a ConstantInt
638 static Constant *AddOne(Constant *C, LLVMContext *Context) {
639   return Context->getConstantExprAdd(C, 
640     Context->getConstantInt(C->getType(), 1));
641 }
642 /// SubOne - Subtract one from a ConstantInt
643 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
644   return Context->getConstantExprSub(C, 
645     Context->getConstantInt(C->getType(), 1));
646 }
647 /// MultiplyOverflows - True if the multiply can not be expressed in an int
648 /// this size.
649 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
650                               LLVMContext *Context) {
651   uint32_t W = C1->getBitWidth();
652   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
653   if (sign) {
654     LHSExt.sext(W * 2);
655     RHSExt.sext(W * 2);
656   } else {
657     LHSExt.zext(W * 2);
658     RHSExt.zext(W * 2);
659   }
660
661   APInt MulExt = LHSExt * RHSExt;
662
663   if (sign) {
664     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
665     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
666     return MulExt.slt(Min) || MulExt.sgt(Max);
667   } else 
668     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
669 }
670
671
672 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
673 /// specified instruction is a constant integer.  If so, check to see if there
674 /// are any bits set in the constant that are not demanded.  If so, shrink the
675 /// constant and return true.
676 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
677                                    APInt Demanded, LLVMContext *Context) {
678   assert(I && "No instruction?");
679   assert(OpNo < I->getNumOperands() && "Operand index too large");
680
681   // If the operand is not a constant integer, nothing to do.
682   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
683   if (!OpC) return false;
684
685   // If there are no bits set that aren't demanded, nothing to do.
686   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
687   if ((~Demanded & OpC->getValue()) == 0)
688     return false;
689
690   // This instruction is producing bits that are not demanded. Shrink the RHS.
691   Demanded &= OpC->getValue();
692   I->setOperand(OpNo, Context->getConstantInt(Demanded));
693   return true;
694 }
695
696 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
697 // set of known zero and one bits, compute the maximum and minimum values that
698 // could have the specified known zero and known one bits, returning them in
699 // min/max.
700 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
701                                                    const APInt& KnownOne,
702                                                    APInt& Min, APInt& Max) {
703   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
704          KnownZero.getBitWidth() == Min.getBitWidth() &&
705          KnownZero.getBitWidth() == Max.getBitWidth() &&
706          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
707   APInt UnknownBits = ~(KnownZero|KnownOne);
708
709   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
710   // bit if it is unknown.
711   Min = KnownOne;
712   Max = KnownOne|UnknownBits;
713   
714   if (UnknownBits.isNegative()) { // Sign bit is unknown
715     Min.set(Min.getBitWidth()-1);
716     Max.clear(Max.getBitWidth()-1);
717   }
718 }
719
720 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
721 // a set of known zero and one bits, compute the maximum and minimum values that
722 // could have the specified known zero and known one bits, returning them in
723 // min/max.
724 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
725                                                      const APInt &KnownOne,
726                                                      APInt &Min, APInt &Max) {
727   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728          KnownZero.getBitWidth() == Min.getBitWidth() &&
729          KnownZero.getBitWidth() == Max.getBitWidth() &&
730          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
731   APInt UnknownBits = ~(KnownZero|KnownOne);
732   
733   // The minimum value is when the unknown bits are all zeros.
734   Min = KnownOne;
735   // The maximum value is when the unknown bits are all ones.
736   Max = KnownOne|UnknownBits;
737 }
738
739 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
740 /// SimplifyDemandedBits knows about.  See if the instruction has any
741 /// properties that allow us to simplify its operands.
742 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
743   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
744   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
745   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
746   
747   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
748                                      KnownZero, KnownOne, 0);
749   if (V == 0) return false;
750   if (V == &Inst) return true;
751   ReplaceInstUsesWith(Inst, V);
752   return true;
753 }
754
755 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
756 /// specified instruction operand if possible, updating it in place.  It returns
757 /// true if it made any change and false otherwise.
758 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
759                                         APInt &KnownZero, APInt &KnownOne,
760                                         unsigned Depth) {
761   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
762                                           KnownZero, KnownOne, Depth);
763   if (NewVal == 0) return false;
764   U.set(NewVal);
765   return true;
766 }
767
768
769 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
770 /// value based on the demanded bits.  When this function is called, it is known
771 /// that only the bits set in DemandedMask of the result of V are ever used
772 /// downstream. Consequently, depending on the mask and V, it may be possible
773 /// to replace V with a constant or one of its operands. In such cases, this
774 /// function does the replacement and returns true. In all other cases, it
775 /// returns false after analyzing the expression and setting KnownOne and known
776 /// to be one in the expression.  KnownZero contains all the bits that are known
777 /// to be zero in the expression. These are provided to potentially allow the
778 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
779 /// the expression. KnownOne and KnownZero always follow the invariant that 
780 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
781 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
782 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
783 /// and KnownOne must all be the same.
784 ///
785 /// This returns null if it did not change anything and it permits no
786 /// simplification.  This returns V itself if it did some simplification of V's
787 /// operands based on the information about what bits are demanded. This returns
788 /// some other non-null value if it found out that V is equal to another value
789 /// in the context where the specified bits are demanded, but not for all users.
790 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
791                                              APInt &KnownZero, APInt &KnownOne,
792                                              unsigned Depth) {
793   assert(V != 0 && "Null pointer of Value???");
794   assert(Depth <= 6 && "Limit Search Depth");
795   uint32_t BitWidth = DemandedMask.getBitWidth();
796   const Type *VTy = V->getType();
797   assert((TD || !isa<PointerType>(VTy)) &&
798          "SimplifyDemandedBits needs to know bit widths!");
799   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
800          (!VTy->isIntOrIntVector() ||
801           VTy->getScalarSizeInBits() == BitWidth) &&
802          KnownZero.getBitWidth() == BitWidth &&
803          KnownOne.getBitWidth() == BitWidth &&
804          "Value *V, DemandedMask, KnownZero and KnownOne "
805          "must have same BitWidth");
806   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
807     // We know all of the bits for a constant!
808     KnownOne = CI->getValue() & DemandedMask;
809     KnownZero = ~KnownOne & DemandedMask;
810     return 0;
811   }
812   if (isa<ConstantPointerNull>(V)) {
813     // We know all of the bits for a constant!
814     KnownOne.clear();
815     KnownZero = DemandedMask;
816     return 0;
817   }
818
819   KnownZero.clear();
820   KnownOne.clear();
821   if (DemandedMask == 0) {   // Not demanding any bits from V.
822     if (isa<UndefValue>(V))
823       return 0;
824     return Context->getUndef(VTy);
825   }
826   
827   if (Depth == 6)        // Limit search depth.
828     return 0;
829   
830   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
831   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
832
833   Instruction *I = dyn_cast<Instruction>(V);
834   if (!I) {
835     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
836     return 0;        // Only analyze instructions.
837   }
838
839   // If there are multiple uses of this value and we aren't at the root, then
840   // we can't do any simplifications of the operands, because DemandedMask
841   // only reflects the bits demanded by *one* of the users.
842   if (Depth != 0 && !I->hasOneUse()) {
843     // Despite the fact that we can't simplify this instruction in all User's
844     // context, we can at least compute the knownzero/knownone bits, and we can
845     // do simplifications that apply to *just* the one user if we know that
846     // this instruction has a simpler value in that context.
847     if (I->getOpcode() == Instruction::And) {
848       // If either the LHS or the RHS are Zero, the result is zero.
849       ComputeMaskedBits(I->getOperand(1), DemandedMask,
850                         RHSKnownZero, RHSKnownOne, Depth+1);
851       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
852                         LHSKnownZero, LHSKnownOne, Depth+1);
853       
854       // If all of the demanded bits are known 1 on one side, return the other.
855       // These bits cannot contribute to the result of the 'and' in this
856       // context.
857       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
858           (DemandedMask & ~LHSKnownZero))
859         return I->getOperand(0);
860       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
861           (DemandedMask & ~RHSKnownZero))
862         return I->getOperand(1);
863       
864       // If all of the demanded bits in the inputs are known zeros, return zero.
865       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
866         return Context->getNullValue(VTy);
867       
868     } else if (I->getOpcode() == Instruction::Or) {
869       // We can simplify (X|Y) -> X or Y in the user's context if we know that
870       // only bits from X or Y are demanded.
871       
872       // If either the LHS or the RHS are One, the result is One.
873       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
874                         RHSKnownZero, RHSKnownOne, Depth+1);
875       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
876                         LHSKnownZero, LHSKnownOne, Depth+1);
877       
878       // If all of the demanded bits are known zero on one side, return the
879       // other.  These bits cannot contribute to the result of the 'or' in this
880       // context.
881       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
882           (DemandedMask & ~LHSKnownOne))
883         return I->getOperand(0);
884       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
885           (DemandedMask & ~RHSKnownOne))
886         return I->getOperand(1);
887       
888       // If all of the potentially set bits on one side are known to be set on
889       // the other side, just use the 'other' side.
890       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
891           (DemandedMask & (~RHSKnownZero)))
892         return I->getOperand(0);
893       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
894           (DemandedMask & (~LHSKnownZero)))
895         return I->getOperand(1);
896     }
897     
898     // Compute the KnownZero/KnownOne bits to simplify things downstream.
899     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
900     return 0;
901   }
902   
903   // If this is the root being simplified, allow it to have multiple uses,
904   // just set the DemandedMask to all bits so that we can try to simplify the
905   // operands.  This allows visitTruncInst (for example) to simplify the
906   // operand of a trunc without duplicating all the logic below.
907   if (Depth == 0 && !V->hasOneUse())
908     DemandedMask = APInt::getAllOnesValue(BitWidth);
909   
910   switch (I->getOpcode()) {
911   default:
912     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
913     break;
914   case Instruction::And:
915     // If either the LHS or the RHS are Zero, the result is zero.
916     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
917                              RHSKnownZero, RHSKnownOne, Depth+1) ||
918         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
919                              LHSKnownZero, LHSKnownOne, Depth+1))
920       return I;
921     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
922     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
923
924     // If all of the demanded bits are known 1 on one side, return the other.
925     // These bits cannot contribute to the result of the 'and'.
926     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
927         (DemandedMask & ~LHSKnownZero))
928       return I->getOperand(0);
929     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
930         (DemandedMask & ~RHSKnownZero))
931       return I->getOperand(1);
932     
933     // If all of the demanded bits in the inputs are known zeros, return zero.
934     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
935       return Context->getNullValue(VTy);
936       
937     // If the RHS is a constant, see if we can simplify it.
938     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
939       return I;
940       
941     // Output known-1 bits are only known if set in both the LHS & RHS.
942     RHSKnownOne &= LHSKnownOne;
943     // Output known-0 are known to be clear if zero in either the LHS | RHS.
944     RHSKnownZero |= LHSKnownZero;
945     break;
946   case Instruction::Or:
947     // If either the LHS or the RHS are One, the result is One.
948     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
949                              RHSKnownZero, RHSKnownOne, Depth+1) ||
950         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
951                              LHSKnownZero, LHSKnownOne, Depth+1))
952       return I;
953     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
954     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
955     
956     // If all of the demanded bits are known zero on one side, return the other.
957     // These bits cannot contribute to the result of the 'or'.
958     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
959         (DemandedMask & ~LHSKnownOne))
960       return I->getOperand(0);
961     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
962         (DemandedMask & ~RHSKnownOne))
963       return I->getOperand(1);
964
965     // If all of the potentially set bits on one side are known to be set on
966     // the other side, just use the 'other' side.
967     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
968         (DemandedMask & (~RHSKnownZero)))
969       return I->getOperand(0);
970     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
971         (DemandedMask & (~LHSKnownZero)))
972       return I->getOperand(1);
973         
974     // If the RHS is a constant, see if we can simplify it.
975     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
976       return I;
977           
978     // Output known-0 bits are only known if clear in both the LHS & RHS.
979     RHSKnownZero &= LHSKnownZero;
980     // Output known-1 are known to be set if set in either the LHS | RHS.
981     RHSKnownOne |= LHSKnownOne;
982     break;
983   case Instruction::Xor: {
984     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
985                              RHSKnownZero, RHSKnownOne, Depth+1) ||
986         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
987                              LHSKnownZero, LHSKnownOne, Depth+1))
988       return I;
989     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
990     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
991     
992     // If all of the demanded bits are known zero on one side, return the other.
993     // These bits cannot contribute to the result of the 'xor'.
994     if ((DemandedMask & RHSKnownZero) == DemandedMask)
995       return I->getOperand(0);
996     if ((DemandedMask & LHSKnownZero) == DemandedMask)
997       return I->getOperand(1);
998     
999     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1000     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1001                          (RHSKnownOne & LHSKnownOne);
1002     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1003     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1004                         (RHSKnownOne & LHSKnownZero);
1005     
1006     // If all of the demanded bits are known to be zero on one side or the
1007     // other, turn this into an *inclusive* or.
1008     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1009     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1010       Instruction *Or =
1011         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1012                                  I->getName());
1013       return InsertNewInstBefore(Or, *I);
1014     }
1015     
1016     // If all of the demanded bits on one side are known, and all of the set
1017     // bits on that side are also known to be set on the other side, turn this
1018     // into an AND, as we know the bits will be cleared.
1019     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1021       // all known
1022       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1023         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1024         Instruction *And = 
1025           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1026         return InsertNewInstBefore(And, *I);
1027       }
1028     }
1029     
1030     // If the RHS is a constant, see if we can simplify it.
1031     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1032     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1033       return I;
1034     
1035     RHSKnownZero = KnownZeroOut;
1036     RHSKnownOne  = KnownOneOut;
1037     break;
1038   }
1039   case Instruction::Select:
1040     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1041                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1042         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1043                              LHSKnownZero, LHSKnownOne, Depth+1))
1044       return I;
1045     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1046     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1047     
1048     // If the operands are constants, see if we can simplify them.
1049     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1050         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1051       return I;
1052     
1053     // Only known if known in both the LHS and RHS.
1054     RHSKnownOne &= LHSKnownOne;
1055     RHSKnownZero &= LHSKnownZero;
1056     break;
1057   case Instruction::Trunc: {
1058     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1059     DemandedMask.zext(truncBf);
1060     RHSKnownZero.zext(truncBf);
1061     RHSKnownOne.zext(truncBf);
1062     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1063                              RHSKnownZero, RHSKnownOne, Depth+1))
1064       return I;
1065     DemandedMask.trunc(BitWidth);
1066     RHSKnownZero.trunc(BitWidth);
1067     RHSKnownOne.trunc(BitWidth);
1068     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1069     break;
1070   }
1071   case Instruction::BitCast:
1072     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1073       return false;  // vector->int or fp->int?
1074
1075     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1076       if (const VectorType *SrcVTy =
1077             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1078         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1079           // Don't touch a bitcast between vectors of different element counts.
1080           return false;
1081       } else
1082         // Don't touch a scalar-to-vector bitcast.
1083         return false;
1084     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1085       // Don't touch a vector-to-scalar bitcast.
1086       return false;
1087
1088     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1089                              RHSKnownZero, RHSKnownOne, Depth+1))
1090       return I;
1091     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1092     break;
1093   case Instruction::ZExt: {
1094     // Compute the bits in the result that are not present in the input.
1095     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1096     
1097     DemandedMask.trunc(SrcBitWidth);
1098     RHSKnownZero.trunc(SrcBitWidth);
1099     RHSKnownOne.trunc(SrcBitWidth);
1100     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1101                              RHSKnownZero, RHSKnownOne, Depth+1))
1102       return I;
1103     DemandedMask.zext(BitWidth);
1104     RHSKnownZero.zext(BitWidth);
1105     RHSKnownOne.zext(BitWidth);
1106     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1107     // The top bits are known to be zero.
1108     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1109     break;
1110   }
1111   case Instruction::SExt: {
1112     // Compute the bits in the result that are not present in the input.
1113     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1114     
1115     APInt InputDemandedBits = DemandedMask & 
1116                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1117
1118     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1119     // If any of the sign extended bits are demanded, we know that the sign
1120     // bit is demanded.
1121     if ((NewBits & DemandedMask) != 0)
1122       InputDemandedBits.set(SrcBitWidth-1);
1123       
1124     InputDemandedBits.trunc(SrcBitWidth);
1125     RHSKnownZero.trunc(SrcBitWidth);
1126     RHSKnownOne.trunc(SrcBitWidth);
1127     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return I;
1130     InputDemandedBits.zext(BitWidth);
1131     RHSKnownZero.zext(BitWidth);
1132     RHSKnownOne.zext(BitWidth);
1133     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1134       
1135     // If the sign bit of the input is known set or clear, then we know the
1136     // top bits of the result.
1137
1138     // If the input sign bit is known zero, or if the NewBits are not demanded
1139     // convert this into a zero extension.
1140     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1141       // Convert to ZExt cast
1142       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1143       return InsertNewInstBefore(NewCast, *I);
1144     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1145       RHSKnownOne |= NewBits;
1146     }
1147     break;
1148   }
1149   case Instruction::Add: {
1150     // Figure out what the input bits are.  If the top bits of the and result
1151     // are not demanded, then the add doesn't demand them from its input
1152     // either.
1153     unsigned NLZ = DemandedMask.countLeadingZeros();
1154       
1155     // If there is a constant on the RHS, there are a variety of xformations
1156     // we can do.
1157     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1158       // If null, this should be simplified elsewhere.  Some of the xforms here
1159       // won't work if the RHS is zero.
1160       if (RHS->isZero())
1161         break;
1162       
1163       // If the top bit of the output is demanded, demand everything from the
1164       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1165       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1166
1167       // Find information about known zero/one bits in the input.
1168       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1169                                LHSKnownZero, LHSKnownOne, Depth+1))
1170         return I;
1171
1172       // If the RHS of the add has bits set that can't affect the input, reduce
1173       // the constant.
1174       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1175         return I;
1176       
1177       // Avoid excess work.
1178       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1179         break;
1180       
1181       // Turn it into OR if input bits are zero.
1182       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1183         Instruction *Or =
1184           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1185                                    I->getName());
1186         return InsertNewInstBefore(Or, *I);
1187       }
1188       
1189       // We can say something about the output known-zero and known-one bits,
1190       // depending on potential carries from the input constant and the
1191       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1192       // bits set and the RHS constant is 0x01001, then we know we have a known
1193       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1194       
1195       // To compute this, we first compute the potential carry bits.  These are
1196       // the bits which may be modified.  I'm not aware of a better way to do
1197       // this scan.
1198       const APInt &RHSVal = RHS->getValue();
1199       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1200       
1201       // Now that we know which bits have carries, compute the known-1/0 sets.
1202       
1203       // Bits are known one if they are known zero in one operand and one in the
1204       // other, and there is no input carry.
1205       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1206                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1207       
1208       // Bits are known zero if they are known zero in both operands and there
1209       // is no input carry.
1210       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1211     } else {
1212       // If the high-bits of this ADD are not demanded, then it does not demand
1213       // the high bits of its LHS or RHS.
1214       if (DemandedMask[BitWidth-1] == 0) {
1215         // Right fill the mask of bits for this ADD to demand the most
1216         // significant bit and all those below it.
1217         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1218         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1219                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1220             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1221                                  LHSKnownZero, LHSKnownOne, Depth+1))
1222           return I;
1223       }
1224     }
1225     break;
1226   }
1227   case Instruction::Sub:
1228     // If the high-bits of this SUB are not demanded, then it does not demand
1229     // the high bits of its LHS or RHS.
1230     if (DemandedMask[BitWidth-1] == 0) {
1231       // Right fill the mask of bits for this SUB to demand the most
1232       // significant bit and all those below it.
1233       uint32_t NLZ = DemandedMask.countLeadingZeros();
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     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1242     // the known zeros and ones.
1243     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1244     break;
1245   case Instruction::Shl:
1246     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1247       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1248       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1249       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1250                                RHSKnownZero, RHSKnownOne, Depth+1))
1251         return I;
1252       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1253       RHSKnownZero <<= ShiftAmt;
1254       RHSKnownOne  <<= ShiftAmt;
1255       // low bits known zero.
1256       if (ShiftAmt)
1257         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1258     }
1259     break;
1260   case Instruction::LShr:
1261     // For a logical shift right
1262     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1263       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1264       
1265       // Unsigned shift right.
1266       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1267       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1268                                RHSKnownZero, RHSKnownOne, Depth+1))
1269         return I;
1270       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1271       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1272       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1273       if (ShiftAmt) {
1274         // Compute the new bits that are at the top now.
1275         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1276         RHSKnownZero |= HighBits;  // high bits known zero.
1277       }
1278     }
1279     break;
1280   case Instruction::AShr:
1281     // If this is an arithmetic shift right and only the low-bit is set, we can
1282     // always convert this into a logical shr, even if the shift amount is
1283     // variable.  The low bit of the shift cannot be an input sign bit unless
1284     // the shift amount is >= the size of the datatype, which is undefined.
1285     if (DemandedMask == 1) {
1286       // Perform the logical shift right.
1287       Instruction *NewVal = BinaryOperator::CreateLShr(
1288                         I->getOperand(0), I->getOperand(1), I->getName());
1289       return InsertNewInstBefore(NewVal, *I);
1290     }    
1291
1292     // If the sign bit is the only bit demanded by this ashr, then there is no
1293     // need to do it, the shift doesn't change the high bit.
1294     if (DemandedMask.isSignBit())
1295       return I->getOperand(0);
1296     
1297     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1298       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1299       
1300       // Signed shift right.
1301       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1302       // If any of the "high bits" are demanded, we should set the sign bit as
1303       // demanded.
1304       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1305         DemandedMaskIn.set(BitWidth-1);
1306       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1307                                RHSKnownZero, RHSKnownOne, Depth+1))
1308         return I;
1309       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1310       // Compute the new bits that are at the top now.
1311       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1312       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1313       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1314         
1315       // Handle the sign bits.
1316       APInt SignBit(APInt::getSignBit(BitWidth));
1317       // Adjust to where it is now in the mask.
1318       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1319         
1320       // If the input sign bit is known to be zero, or if none of the top bits
1321       // are demanded, turn this into an unsigned shift right.
1322       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1323           (HighBits & ~DemandedMask) == HighBits) {
1324         // Perform the logical shift right.
1325         Instruction *NewVal = BinaryOperator::CreateLShr(
1326                           I->getOperand(0), SA, I->getName());
1327         return InsertNewInstBefore(NewVal, *I);
1328       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1329         RHSKnownOne |= HighBits;
1330       }
1331     }
1332     break;
1333   case Instruction::SRem:
1334     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1335       APInt RA = Rem->getValue().abs();
1336       if (RA.isPowerOf2()) {
1337         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1338           return I->getOperand(0);
1339
1340         APInt LowBits = RA - 1;
1341         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1342         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1343                                  LHSKnownZero, LHSKnownOne, Depth+1))
1344           return I;
1345
1346         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1347           LHSKnownZero |= ~LowBits;
1348
1349         KnownZero |= LHSKnownZero & DemandedMask;
1350
1351         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1352       }
1353     }
1354     break;
1355   case Instruction::URem: {
1356     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1357     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1358     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1359                              KnownZero2, KnownOne2, Depth+1) ||
1360         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1361                              KnownZero2, KnownOne2, Depth+1))
1362       return I;
1363
1364     unsigned Leaders = KnownZero2.countLeadingOnes();
1365     Leaders = std::max(Leaders,
1366                        KnownZero2.countLeadingOnes());
1367     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1368     break;
1369   }
1370   case Instruction::Call:
1371     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1372       switch (II->getIntrinsicID()) {
1373       default: break;
1374       case Intrinsic::bswap: {
1375         // If the only bits demanded come from one byte of the bswap result,
1376         // just shift the input byte into position to eliminate the bswap.
1377         unsigned NLZ = DemandedMask.countLeadingZeros();
1378         unsigned NTZ = DemandedMask.countTrailingZeros();
1379           
1380         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1381         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1382         // have 14 leading zeros, round to 8.
1383         NLZ &= ~7;
1384         NTZ &= ~7;
1385         // If we need exactly one byte, we can do this transformation.
1386         if (BitWidth-NLZ-NTZ == 8) {
1387           unsigned ResultBit = NTZ;
1388           unsigned InputBit = BitWidth-NTZ-8;
1389           
1390           // Replace this with either a left or right shift to get the byte into
1391           // the right place.
1392           Instruction *NewVal;
1393           if (InputBit > ResultBit)
1394             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1395                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1396           else
1397             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1398                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1399           NewVal->takeName(I);
1400           return InsertNewInstBefore(NewVal, *I);
1401         }
1402           
1403         // TODO: Could compute known zero/one bits based on the input.
1404         break;
1405       }
1406       }
1407     }
1408     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1409     break;
1410   }
1411   
1412   // If the client is only demanding bits that we know, return the known
1413   // constant.
1414   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1415     Constant *C = Context->getConstantInt(RHSKnownOne);
1416     if (isa<PointerType>(V->getType()))
1417       C = Context->getConstantExprIntToPtr(C, V->getType());
1418     return C;
1419   }
1420   return false;
1421 }
1422
1423
1424 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1425 /// any number of elements. DemandedElts contains the set of elements that are
1426 /// actually used by the caller.  This method analyzes which elements of the
1427 /// operand are undef and returns that information in UndefElts.
1428 ///
1429 /// If the information about demanded elements can be used to simplify the
1430 /// operation, the operation is simplified, then the resultant value is
1431 /// returned.  This returns null if no change was made.
1432 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1433                                                 APInt& UndefElts,
1434                                                 unsigned Depth) {
1435   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1436   APInt EltMask(APInt::getAllOnesValue(VWidth));
1437   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1438
1439   if (isa<UndefValue>(V)) {
1440     // If the entire vector is undefined, just return this info.
1441     UndefElts = EltMask;
1442     return 0;
1443   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1444     UndefElts = EltMask;
1445     return Context->getUndef(V->getType());
1446   }
1447
1448   UndefElts = 0;
1449   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1450     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1451     Constant *Undef = Context->getUndef(EltTy);
1452
1453     std::vector<Constant*> Elts;
1454     for (unsigned i = 0; i != VWidth; ++i)
1455       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1456         Elts.push_back(Undef);
1457         UndefElts.set(i);
1458       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1459         Elts.push_back(Undef);
1460         UndefElts.set(i);
1461       } else {                               // Otherwise, defined.
1462         Elts.push_back(CP->getOperand(i));
1463       }
1464
1465     // If we changed the constant, return it.
1466     Constant *NewCP = Context->getConstantVector(Elts);
1467     return NewCP != CP ? NewCP : 0;
1468   } else if (isa<ConstantAggregateZero>(V)) {
1469     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1470     // set to undef.
1471     
1472     // Check if this is identity. If so, return 0 since we are not simplifying
1473     // anything.
1474     if (DemandedElts == ((1ULL << VWidth) -1))
1475       return 0;
1476     
1477     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1478     Constant *Zero = Context->getNullValue(EltTy);
1479     Constant *Undef = Context->getUndef(EltTy);
1480     std::vector<Constant*> Elts;
1481     for (unsigned i = 0; i != VWidth; ++i) {
1482       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1483       Elts.push_back(Elt);
1484     }
1485     UndefElts = DemandedElts ^ EltMask;
1486     return Context->getConstantVector(Elts);
1487   }
1488   
1489   // Limit search depth.
1490   if (Depth == 10)
1491     return 0;
1492
1493   // If multiple users are using the root value, procede with
1494   // simplification conservatively assuming that all elements
1495   // are needed.
1496   if (!V->hasOneUse()) {
1497     // Quit if we find multiple users of a non-root value though.
1498     // They'll be handled when it's their turn to be visited by
1499     // the main instcombine process.
1500     if (Depth != 0)
1501       // TODO: Just compute the UndefElts information recursively.
1502       return 0;
1503
1504     // Conservatively assume that all elements are needed.
1505     DemandedElts = EltMask;
1506   }
1507   
1508   Instruction *I = dyn_cast<Instruction>(V);
1509   if (!I) return 0;        // Only analyze instructions.
1510   
1511   bool MadeChange = false;
1512   APInt UndefElts2(VWidth, 0);
1513   Value *TmpV;
1514   switch (I->getOpcode()) {
1515   default: break;
1516     
1517   case Instruction::InsertElement: {
1518     // If this is a variable index, we don't know which element it overwrites.
1519     // demand exactly the same input as we produce.
1520     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1521     if (Idx == 0) {
1522       // Note that we can't propagate undef elt info, because we don't know
1523       // which elt is getting updated.
1524       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1525                                         UndefElts2, Depth+1);
1526       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1527       break;
1528     }
1529     
1530     // If this is inserting an element that isn't demanded, remove this
1531     // insertelement.
1532     unsigned IdxNo = Idx->getZExtValue();
1533     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1534       return AddSoonDeadInstToWorklist(*I, 0);
1535     
1536     // Otherwise, the element inserted overwrites whatever was there, so the
1537     // input demanded set is simpler than the output set.
1538     APInt DemandedElts2 = DemandedElts;
1539     DemandedElts2.clear(IdxNo);
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543
1544     // The inserted element is defined.
1545     UndefElts.clear(IdxNo);
1546     break;
1547   }
1548   case Instruction::ShuffleVector: {
1549     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1550     uint64_t LHSVWidth =
1551       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1552     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1553     for (unsigned i = 0; i < VWidth; i++) {
1554       if (DemandedElts[i]) {
1555         unsigned MaskVal = Shuffle->getMaskValue(i);
1556         if (MaskVal != -1u) {
1557           assert(MaskVal < LHSVWidth * 2 &&
1558                  "shufflevector mask index out of range!");
1559           if (MaskVal < LHSVWidth)
1560             LeftDemanded.set(MaskVal);
1561           else
1562             RightDemanded.set(MaskVal - LHSVWidth);
1563         }
1564       }
1565     }
1566
1567     APInt UndefElts4(LHSVWidth, 0);
1568     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1569                                       UndefElts4, Depth+1);
1570     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571
1572     APInt UndefElts3(LHSVWidth, 0);
1573     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1574                                       UndefElts3, Depth+1);
1575     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1576
1577     bool NewUndefElts = false;
1578     for (unsigned i = 0; i < VWidth; i++) {
1579       unsigned MaskVal = Shuffle->getMaskValue(i);
1580       if (MaskVal == -1u) {
1581         UndefElts.set(i);
1582       } else if (MaskVal < LHSVWidth) {
1583         if (UndefElts4[MaskVal]) {
1584           NewUndefElts = true;
1585           UndefElts.set(i);
1586         }
1587       } else {
1588         if (UndefElts3[MaskVal - LHSVWidth]) {
1589           NewUndefElts = true;
1590           UndefElts.set(i);
1591         }
1592       }
1593     }
1594
1595     if (NewUndefElts) {
1596       // Add additional discovered undefs.
1597       std::vector<Constant*> Elts;
1598       for (unsigned i = 0; i < VWidth; ++i) {
1599         if (UndefElts[i])
1600           Elts.push_back(Context->getUndef(Type::Int32Ty));
1601         else
1602           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1603                                           Shuffle->getMaskValue(i)));
1604       }
1605       I->setOperand(2, Context->getConstantVector(Elts));
1606       MadeChange = true;
1607     }
1608     break;
1609   }
1610   case Instruction::BitCast: {
1611     // Vector->vector casts only.
1612     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1613     if (!VTy) break;
1614     unsigned InVWidth = VTy->getNumElements();
1615     APInt InputDemandedElts(InVWidth, 0);
1616     unsigned Ratio;
1617
1618     if (VWidth == InVWidth) {
1619       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1620       // elements as are demanded of us.
1621       Ratio = 1;
1622       InputDemandedElts = DemandedElts;
1623     } else if (VWidth > InVWidth) {
1624       // Untested so far.
1625       break;
1626       
1627       // If there are more elements in the result than there are in the source,
1628       // then an input element is live if any of the corresponding output
1629       // elements are live.
1630       Ratio = VWidth/InVWidth;
1631       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1632         if (DemandedElts[OutIdx])
1633           InputDemandedElts.set(OutIdx/Ratio);
1634       }
1635     } else {
1636       // Untested so far.
1637       break;
1638       
1639       // If there are more elements in the source than there are in the result,
1640       // then an input element is live if the corresponding output element is
1641       // live.
1642       Ratio = InVWidth/VWidth;
1643       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1644         if (DemandedElts[InIdx/Ratio])
1645           InputDemandedElts.set(InIdx);
1646     }
1647     
1648     // div/rem demand all inputs, because they don't want divide by zero.
1649     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1650                                       UndefElts2, Depth+1);
1651     if (TmpV) {
1652       I->setOperand(0, TmpV);
1653       MadeChange = true;
1654     }
1655     
1656     UndefElts = UndefElts2;
1657     if (VWidth > InVWidth) {
1658       llvm_unreachable("Unimp");
1659       // If there are more elements in the result than there are in the source,
1660       // then an output element is undef if the corresponding input element is
1661       // undef.
1662       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1663         if (UndefElts2[OutIdx/Ratio])
1664           UndefElts.set(OutIdx);
1665     } else if (VWidth < InVWidth) {
1666       llvm_unreachable("Unimp");
1667       // If there are more elements in the source than there are in the result,
1668       // then a result element is undef if all of the corresponding input
1669       // elements are undef.
1670       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1671       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1672         if (!UndefElts2[InIdx])            // Not undef?
1673           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1674     }
1675     break;
1676   }
1677   case Instruction::And:
1678   case Instruction::Or:
1679   case Instruction::Xor:
1680   case Instruction::Add:
1681   case Instruction::Sub:
1682   case Instruction::Mul:
1683     // div/rem demand all inputs, because they don't want divide by zero.
1684     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685                                       UndefElts, Depth+1);
1686     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1688                                       UndefElts2, Depth+1);
1689     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1690       
1691     // Output elements are undefined if both are undefined.  Consider things
1692     // like undef&0.  The result is known zero, not undef.
1693     UndefElts &= UndefElts2;
1694     break;
1695     
1696   case Instruction::Call: {
1697     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1698     if (!II) break;
1699     switch (II->getIntrinsicID()) {
1700     default: break;
1701       
1702     // Binary vector operations that work column-wise.  A dest element is a
1703     // function of the corresponding input elements from the two inputs.
1704     case Intrinsic::x86_sse_sub_ss:
1705     case Intrinsic::x86_sse_mul_ss:
1706     case Intrinsic::x86_sse_min_ss:
1707     case Intrinsic::x86_sse_max_ss:
1708     case Intrinsic::x86_sse2_sub_sd:
1709     case Intrinsic::x86_sse2_mul_sd:
1710     case Intrinsic::x86_sse2_min_sd:
1711     case Intrinsic::x86_sse2_max_sd:
1712       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1713                                         UndefElts, Depth+1);
1714       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1715       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1716                                         UndefElts2, Depth+1);
1717       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1718
1719       // If only the low elt is demanded and this is a scalarizable intrinsic,
1720       // scalarize it now.
1721       if (DemandedElts == 1) {
1722         switch (II->getIntrinsicID()) {
1723         default: break;
1724         case Intrinsic::x86_sse_sub_ss:
1725         case Intrinsic::x86_sse_mul_ss:
1726         case Intrinsic::x86_sse2_sub_sd:
1727         case Intrinsic::x86_sse2_mul_sd:
1728           // TODO: Lower MIN/MAX/ABS/etc
1729           Value *LHS = II->getOperand(1);
1730           Value *RHS = II->getOperand(2);
1731           // Extract the element as scalars.
1732           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 
1733             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1734           RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1735             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1736           
1737           switch (II->getIntrinsicID()) {
1738           default: llvm_unreachable("Case stmts out of sync!");
1739           case Intrinsic::x86_sse_sub_ss:
1740           case Intrinsic::x86_sse2_sub_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1742                                                         II->getName()), *II);
1743             break;
1744           case Intrinsic::x86_sse_mul_ss:
1745           case Intrinsic::x86_sse2_mul_sd:
1746             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1747                                                          II->getName()), *II);
1748             break;
1749           }
1750           
1751           Instruction *New =
1752             InsertElementInst::Create(
1753               Context->getUndef(II->getType()), TmpV,
1754               Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1755           InsertNewInstBefore(New, *II);
1756           AddSoonDeadInstToWorklist(*II, 0);
1757           return New;
1758         }            
1759       }
1760         
1761       // Output elements are undefined if both are undefined.  Consider things
1762       // like undef&0.  The result is known zero, not undef.
1763       UndefElts &= UndefElts2;
1764       break;
1765     }
1766     break;
1767   }
1768   }
1769   return MadeChange ? I : 0;
1770 }
1771
1772
1773 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1774 /// function is designed to check a chain of associative operators for a
1775 /// potential to apply a certain optimization.  Since the optimization may be
1776 /// applicable if the expression was reassociated, this checks the chain, then
1777 /// reassociates the expression as necessary to expose the optimization
1778 /// opportunity.  This makes use of a special Functor, which must define
1779 /// 'shouldApply' and 'apply' methods.
1780 ///
1781 template<typename Functor>
1782 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1783                                    LLVMContext *Context) {
1784   unsigned Opcode = Root.getOpcode();
1785   Value *LHS = Root.getOperand(0);
1786
1787   // Quick check, see if the immediate LHS matches...
1788   if (F.shouldApply(LHS))
1789     return F.apply(Root);
1790
1791   // Otherwise, if the LHS is not of the same opcode as the root, return.
1792   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1793   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1794     // Should we apply this transform to the RHS?
1795     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1796
1797     // If not to the RHS, check to see if we should apply to the LHS...
1798     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1799       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1800       ShouldApply = true;
1801     }
1802
1803     // If the functor wants to apply the optimization to the RHS of LHSI,
1804     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1805     if (ShouldApply) {
1806       // Now all of the instructions are in the current basic block, go ahead
1807       // and perform the reassociation.
1808       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1809
1810       // First move the selected RHS to the LHS of the root...
1811       Root.setOperand(0, LHSI->getOperand(1));
1812
1813       // Make what used to be the LHS of the root be the user of the root...
1814       Value *ExtraOperand = TmpLHSI->getOperand(1);
1815       if (&Root == TmpLHSI) {
1816         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1817         return 0;
1818       }
1819       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1820       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1821       BasicBlock::iterator ARI = &Root; ++ARI;
1822       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1823       ARI = Root;
1824
1825       // Now propagate the ExtraOperand down the chain of instructions until we
1826       // get to LHSI.
1827       while (TmpLHSI != LHSI) {
1828         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1829         // Move the instruction to immediately before the chain we are
1830         // constructing to avoid breaking dominance properties.
1831         NextLHSI->moveBefore(ARI);
1832         ARI = NextLHSI;
1833
1834         Value *NextOp = NextLHSI->getOperand(1);
1835         NextLHSI->setOperand(1, ExtraOperand);
1836         TmpLHSI = NextLHSI;
1837         ExtraOperand = NextOp;
1838       }
1839
1840       // Now that the instructions are reassociated, have the functor perform
1841       // the transformation...
1842       return F.apply(Root);
1843     }
1844
1845     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1846   }
1847   return 0;
1848 }
1849
1850 namespace {
1851
1852 // AddRHS - Implements: X + X --> X << 1
1853 struct AddRHS {
1854   Value *RHS;
1855   LLVMContext *Context;
1856   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1857   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858   Instruction *apply(BinaryOperator &Add) const {
1859     return BinaryOperator::CreateShl(Add.getOperand(0),
1860                                      Context->getConstantInt(Add.getType(), 1));
1861   }
1862 };
1863
1864 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1865 //                 iff C1&C2 == 0
1866 struct AddMaskingAnd {
1867   Constant *C2;
1868   LLVMContext *Context;
1869   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1870   bool shouldApply(Value *LHS) const {
1871     ConstantInt *C1;
1872     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1873            Context->getConstantExprAnd(C1, C2)->isNullValue();
1874   }
1875   Instruction *apply(BinaryOperator &Add) const {
1876     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1877   }
1878 };
1879
1880 }
1881
1882 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1883                                              InstCombiner *IC) {
1884   LLVMContext *Context = IC->getContext();
1885   
1886   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1887     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1888   }
1889
1890   // Figure out if the constant is the left or the right argument.
1891   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1893
1894   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1895     if (ConstIsRHS)
1896       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1897     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1898   }
1899
1900   Value *Op0 = SO, *Op1 = ConstOperand;
1901   if (!ConstIsRHS)
1902     std::swap(Op0, Op1);
1903   Instruction *New;
1904   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1905     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1906   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1907     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1908                           Op0, Op1, SO->getName()+".cmp");
1909   else {
1910     llvm_unreachable("Unknown binary instruction type!");
1911   }
1912   return IC->InsertNewInstBefore(New, I);
1913 }
1914
1915 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1916 // constant as the other operand, try to fold the binary operator into the
1917 // select arguments.  This also works for Cast instructions, which obviously do
1918 // not have a second operand.
1919 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1920                                      InstCombiner *IC) {
1921   // Don't modify shared select instructions
1922   if (!SI->hasOneUse()) return 0;
1923   Value *TV = SI->getOperand(1);
1924   Value *FV = SI->getOperand(2);
1925
1926   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1927     // Bool selects with constant operands can be folded to logical ops.
1928     if (SI->getType() == Type::Int1Ty) return 0;
1929
1930     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1931     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1932
1933     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1934                               SelectFalseVal);
1935   }
1936   return 0;
1937 }
1938
1939
1940 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1941 /// node as operand #0, see if we can fold the instruction into the PHI (which
1942 /// is only possible if all operands to the PHI are constants).
1943 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1944   PHINode *PN = cast<PHINode>(I.getOperand(0));
1945   unsigned NumPHIValues = PN->getNumIncomingValues();
1946   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1947
1948   // Check to see if all of the operands of the PHI are constants.  If there is
1949   // one non-constant value, remember the BB it is.  If there is more than one
1950   // or if *it* is a PHI, bail out.
1951   BasicBlock *NonConstBB = 0;
1952   for (unsigned i = 0; i != NumPHIValues; ++i)
1953     if (!isa<Constant>(PN->getIncomingValue(i))) {
1954       if (NonConstBB) return 0;  // More than one non-const value.
1955       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1956       NonConstBB = PN->getIncomingBlock(i);
1957       
1958       // If the incoming non-constant value is in I's block, we have an infinite
1959       // loop.
1960       if (NonConstBB == I.getParent())
1961         return 0;
1962     }
1963   
1964   // If there is exactly one non-constant value, we can insert a copy of the
1965   // operation in that block.  However, if this is a critical edge, we would be
1966   // inserting the computation one some other paths (e.g. inside a loop).  Only
1967   // do this if the pred block is unconditionally branching into the phi block.
1968   if (NonConstBB) {
1969     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1970     if (!BI || !BI->isUnconditional()) return 0;
1971   }
1972
1973   // Okay, we can do the transformation: create the new PHI node.
1974   PHINode *NewPN = PHINode::Create(I.getType(), "");
1975   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1976   InsertNewInstBefore(NewPN, *PN);
1977   NewPN->takeName(PN);
1978
1979   // Next, add all of the operands to the PHI.
1980   if (I.getNumOperands() == 2) {
1981     Constant *C = cast<Constant>(I.getOperand(1));
1982     for (unsigned i = 0; i != NumPHIValues; ++i) {
1983       Value *InV = 0;
1984       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1985         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1986           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
1987         else
1988           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
1989       } else {
1990         assert(PN->getIncomingBlock(i) == NonConstBB);
1991         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1992           InV = BinaryOperator::Create(BO->getOpcode(),
1993                                        PN->getIncomingValue(i), C, "phitmp",
1994                                        NonConstBB->getTerminator());
1995         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1996           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1997                                 CI->getPredicate(),
1998                                 PN->getIncomingValue(i), C, "phitmp",
1999                                 NonConstBB->getTerminator());
2000         else
2001           llvm_unreachable("Unknown binop!");
2002         
2003         AddToWorkList(cast<Instruction>(InV));
2004       }
2005       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2006     }
2007   } else { 
2008     CastInst *CI = cast<CastInst>(&I);
2009     const Type *RetTy = CI->getType();
2010     for (unsigned i = 0; i != NumPHIValues; ++i) {
2011       Value *InV;
2012       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2013         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2014       } else {
2015         assert(PN->getIncomingBlock(i) == NonConstBB);
2016         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2017                                I.getType(), "phitmp", 
2018                                NonConstBB->getTerminator());
2019         AddToWorkList(cast<Instruction>(InV));
2020       }
2021       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2022     }
2023   }
2024   return ReplaceInstUsesWith(I, NewPN);
2025 }
2026
2027
2028 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2029 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2030 /// This basically requires proving that the add in the original type would not
2031 /// overflow to change the sign bit or have a carry out.
2032 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2033   // There are different heuristics we can use for this.  Here are some simple
2034   // ones.
2035   
2036   // Add has the property that adding any two 2's complement numbers can only 
2037   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2038   // have at least two sign bits, we know that the addition of the two values will
2039   // sign extend fine.
2040   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2041     return true;
2042   
2043   
2044   // If one of the operands only has one non-zero bit, and if the other operand
2045   // has a known-zero bit in a more significant place than it (not including the
2046   // sign bit) the ripple may go up to and fill the zero, but won't change the
2047   // sign.  For example, (X & ~4) + 1.
2048   
2049   // TODO: Implement.
2050   
2051   return false;
2052 }
2053
2054
2055 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2056   bool Changed = SimplifyCommutative(I);
2057   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2058
2059   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2060     // X + undef -> undef
2061     if (isa<UndefValue>(RHS))
2062       return ReplaceInstUsesWith(I, RHS);
2063
2064     // X + 0 --> X
2065     if (RHSC->isNullValue())
2066       return ReplaceInstUsesWith(I, LHS);
2067
2068     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2069       // X + (signbit) --> X ^ signbit
2070       const APInt& Val = CI->getValue();
2071       uint32_t BitWidth = Val.getBitWidth();
2072       if (Val == APInt::getSignBit(BitWidth))
2073         return BinaryOperator::CreateXor(LHS, RHS);
2074       
2075       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2076       // (X & 254)+1 -> (X&254)|1
2077       if (SimplifyDemandedInstructionBits(I))
2078         return &I;
2079
2080       // zext(bool) + C -> bool ? C + 1 : C
2081       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2082         if (ZI->getSrcTy() == Type::Int1Ty)
2083           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2084     }
2085
2086     if (isa<PHINode>(LHS))
2087       if (Instruction *NV = FoldOpIntoPhi(I))
2088         return NV;
2089     
2090     ConstantInt *XorRHS = 0;
2091     Value *XorLHS = 0;
2092     if (isa<ConstantInt>(RHSC) &&
2093         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2094       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2095       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2096       
2097       uint32_t Size = TySizeBits / 2;
2098       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2099       APInt CFF80Val(-C0080Val);
2100       do {
2101         if (TySizeBits > Size) {
2102           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2103           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2104           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2105               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2106             // This is a sign extend if the top bits are known zero.
2107             if (!MaskedValueIsZero(XorLHS, 
2108                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2109               Size = 0;  // Not a sign ext, but can't be any others either.
2110             break;
2111           }
2112         }
2113         Size >>= 1;
2114         C0080Val = APIntOps::lshr(C0080Val, Size);
2115         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2116       } while (Size >= 1);
2117       
2118       // FIXME: This shouldn't be necessary. When the backends can handle types
2119       // with funny bit widths then this switch statement should be removed. It
2120       // is just here to get the size of the "middle" type back up to something
2121       // that the back ends can handle.
2122       const Type *MiddleType = 0;
2123       switch (Size) {
2124         default: break;
2125         case 32: MiddleType = Type::Int32Ty; break;
2126         case 16: MiddleType = Type::Int16Ty; break;
2127         case  8: MiddleType = Type::Int8Ty; break;
2128       }
2129       if (MiddleType) {
2130         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2131         InsertNewInstBefore(NewTrunc, I);
2132         return new SExtInst(NewTrunc, I.getType(), I.getName());
2133       }
2134     }
2135   }
2136
2137   if (I.getType() == Type::Int1Ty)
2138     return BinaryOperator::CreateXor(LHS, RHS);
2139
2140   // X + X --> X << 1
2141   if (I.getType()->isInteger()) {
2142     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2143       return Result;
2144
2145     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146       if (RHSI->getOpcode() == Instruction::Sub)
2147         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2148           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2149     }
2150     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151       if (LHSI->getOpcode() == Instruction::Sub)
2152         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2153           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154     }
2155   }
2156
2157   // -A + B  -->  B - A
2158   // -A + -B  -->  -(A + B)
2159   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2160     if (LHS->getType()->isIntOrIntVector()) {
2161       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2162         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2163         InsertNewInstBefore(NewAdd, I);
2164         return BinaryOperator::CreateNeg(*Context, NewAdd);
2165       }
2166     }
2167     
2168     return BinaryOperator::CreateSub(RHS, LHSV);
2169   }
2170
2171   // A + -B  -->  A - B
2172   if (!isa<Constant>(RHS))
2173     if (Value *V = dyn_castNegVal(RHS, Context))
2174       return BinaryOperator::CreateSub(LHS, V);
2175
2176
2177   ConstantInt *C2;
2178   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2179     if (X == RHS)   // X*C + X --> X * (C+1)
2180       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2181
2182     // X*C1 + X*C2 --> X * (C1+C2)
2183     ConstantInt *C1;
2184     if (X == dyn_castFoldableMul(RHS, C1, Context))
2185       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2186   }
2187
2188   // X + X*C --> X * (C+1)
2189   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2190     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2191
2192   // X + ~X --> -1   since   ~X = -X-1
2193   if (dyn_castNotVal(LHS, Context) == RHS ||
2194       dyn_castNotVal(RHS, Context) == LHS)
2195     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2196   
2197
2198   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2199   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2200     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2201       return R;
2202   
2203   // A+B --> A|B iff A and B have no bits set in common.
2204   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2205     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2206     APInt LHSKnownOne(IT->getBitWidth(), 0);
2207     APInt LHSKnownZero(IT->getBitWidth(), 0);
2208     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2209     if (LHSKnownZero != 0) {
2210       APInt RHSKnownOne(IT->getBitWidth(), 0);
2211       APInt RHSKnownZero(IT->getBitWidth(), 0);
2212       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2213       
2214       // No bits in common -> bitwise or.
2215       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2216         return BinaryOperator::CreateOr(LHS, RHS);
2217     }
2218   }
2219
2220   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2221   if (I.getType()->isIntOrIntVector()) {
2222     Value *W, *X, *Y, *Z;
2223     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2224         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2225       if (W != Y) {
2226         if (W == Z) {
2227           std::swap(Y, Z);
2228         } else if (Y == X) {
2229           std::swap(W, X);
2230         } else if (X == Z) {
2231           std::swap(Y, Z);
2232           std::swap(W, X);
2233         }
2234       }
2235
2236       if (W == Y) {
2237         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2238                                                             LHS->getName()), I);
2239         return BinaryOperator::CreateMul(W, NewAdd);
2240       }
2241     }
2242   }
2243
2244   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2245     Value *X = 0;
2246     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2247       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2248
2249     // (X & FF00) + xx00  -> (X+xx00) & FF00
2250     if (LHS->hasOneUse() &&
2251         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2252       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2253       if (Anded == CRHS) {
2254         // See if all bits from the first bit set in the Add RHS up are included
2255         // in the mask.  First, get the rightmost bit.
2256         const APInt& AddRHSV = CRHS->getValue();
2257
2258         // Form a mask of all bits from the lowest bit added through the top.
2259         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2260
2261         // See if the and mask includes all of these bits.
2262         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2263
2264         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2265           // Okay, the xform is safe.  Insert the new add pronto.
2266           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2267                                                             LHS->getName()), I);
2268           return BinaryOperator::CreateAnd(NewAdd, C2);
2269         }
2270       }
2271     }
2272
2273     // Try to fold constant add into select arguments.
2274     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2275       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2276         return R;
2277   }
2278
2279   // add (cast *A to intptrtype) B -> 
2280   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2281   {
2282     CastInst *CI = dyn_cast<CastInst>(LHS);
2283     Value *Other = RHS;
2284     if (!CI) {
2285       CI = dyn_cast<CastInst>(RHS);
2286       Other = LHS;
2287     }
2288     if (CI && CI->getType()->isSized() && 
2289         (CI->getType()->getScalarSizeInBits() ==
2290          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2291         && isa<PointerType>(CI->getOperand(0)->getType())) {
2292       unsigned AS =
2293         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2294       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2295                                   Context->getPointerType(Type::Int8Ty, AS), I);
2296       GetElementPtrInst *GEP = GetElementPtrInst::Create(I2, Other, "ctg2");
2297       // A GEP formed from an arbitrary add may overflow.
2298       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
2299       I2 = InsertNewInstBefore(GEP, I);
2300       return new PtrToIntInst(I2, CI->getType());
2301     }
2302   }
2303   
2304   // add (select X 0 (sub n A)) A  -->  select X A n
2305   {
2306     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2307     Value *A = RHS;
2308     if (!SI) {
2309       SI = dyn_cast<SelectInst>(RHS);
2310       A = LHS;
2311     }
2312     if (SI && SI->hasOneUse()) {
2313       Value *TV = SI->getTrueValue();
2314       Value *FV = SI->getFalseValue();
2315       Value *N;
2316
2317       // Can we fold the add into the argument of the select?
2318       // We check both true and false select arguments for a matching subtract.
2319       if (match(FV, m_Zero(), *Context) &&
2320           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2321         // Fold the add into the true select value.
2322         return SelectInst::Create(SI->getCondition(), N, A);
2323       if (match(TV, m_Zero(), *Context) &&
2324           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2325         // Fold the add into the false select value.
2326         return SelectInst::Create(SI->getCondition(), A, N);
2327     }
2328   }
2329
2330   // Check for (add (sext x), y), see if we can merge this into an
2331   // integer add followed by a sext.
2332   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2333     // (add (sext x), cst) --> (sext (add x, cst'))
2334     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2335       Constant *CI = 
2336         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2337       if (LHSConv->hasOneUse() &&
2338           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2339           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2340         // Insert the new, smaller add.
2341         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2342                                                         CI, "addconv");
2343         InsertNewInstBefore(NewAdd, I);
2344         return new SExtInst(NewAdd, I.getType());
2345       }
2346     }
2347     
2348     // (add (sext x), (sext y)) --> (sext (add int x, y))
2349     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2350       // Only do this if x/y have the same type, if at last one of them has a
2351       // single use (so we don't increase the number of sexts), and if the
2352       // integer add will not overflow.
2353       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2354           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2355           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2356                                    RHSConv->getOperand(0))) {
2357         // Insert the new integer add.
2358         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2359                                                         RHSConv->getOperand(0),
2360                                                         "addconv");
2361         InsertNewInstBefore(NewAdd, I);
2362         return new SExtInst(NewAdd, I.getType());
2363       }
2364     }
2365   }
2366
2367   return Changed ? &I : 0;
2368 }
2369
2370 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2371   bool Changed = SimplifyCommutative(I);
2372   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2373
2374   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2375     // X + 0 --> X
2376     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2377       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2378                               (I.getType())->getValueAPF()))
2379         return ReplaceInstUsesWith(I, LHS);
2380     }
2381
2382     if (isa<PHINode>(LHS))
2383       if (Instruction *NV = FoldOpIntoPhi(I))
2384         return NV;
2385   }
2386
2387   // -A + B  -->  B - A
2388   // -A + -B  -->  -(A + B)
2389   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2390     return BinaryOperator::CreateFSub(RHS, LHSV);
2391
2392   // A + -B  -->  A - B
2393   if (!isa<Constant>(RHS))
2394     if (Value *V = dyn_castFNegVal(RHS, Context))
2395       return BinaryOperator::CreateFSub(LHS, V);
2396
2397   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2398   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2399     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2400       return ReplaceInstUsesWith(I, LHS);
2401
2402   // Check for (add double (sitofp x), y), see if we can merge this into an
2403   // integer add followed by a promotion.
2404   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2405     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2406     // ... if the constant fits in the integer value.  This is useful for things
2407     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2408     // requires a constant pool load, and generally allows the add to be better
2409     // instcombined.
2410     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2411       Constant *CI = 
2412       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2413       if (LHSConv->hasOneUse() &&
2414           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2415           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2416         // Insert the new integer add.
2417         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2418                                                         CI, "addconv");
2419         InsertNewInstBefore(NewAdd, I);
2420         return new SIToFPInst(NewAdd, I.getType());
2421       }
2422     }
2423     
2424     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2425     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2426       // Only do this if x/y have the same type, if at last one of them has a
2427       // single use (so we don't increase the number of int->fp conversions),
2428       // and if the integer add will not overflow.
2429       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2430           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2431           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2432                                    RHSConv->getOperand(0))) {
2433         // Insert the new integer add.
2434         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2435                                                         RHSConv->getOperand(0),
2436                                                         "addconv");
2437         InsertNewInstBefore(NewAdd, I);
2438         return new SIToFPInst(NewAdd, I.getType());
2439       }
2440     }
2441   }
2442   
2443   return Changed ? &I : 0;
2444 }
2445
2446 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2447   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2448
2449   if (Op0 == Op1)                        // sub X, X  -> 0
2450     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2451
2452   // If this is a 'B = x-(-A)', change to B = x+A...
2453   if (Value *V = dyn_castNegVal(Op1, Context))
2454     return BinaryOperator::CreateAdd(Op0, V);
2455
2456   if (isa<UndefValue>(Op0))
2457     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2458   if (isa<UndefValue>(Op1))
2459     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2460
2461   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2462     // Replace (-1 - A) with (~A)...
2463     if (C->isAllOnesValue())
2464       return BinaryOperator::CreateNot(*Context, Op1);
2465
2466     // C - ~X == X + (1+C)
2467     Value *X = 0;
2468     if (match(Op1, m_Not(m_Value(X)), *Context))
2469       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2470
2471     // -(X >>u 31) -> (X >>s 31)
2472     // -(X >>s 31) -> (X >>u 31)
2473     if (C->isZero()) {
2474       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2475         if (SI->getOpcode() == Instruction::LShr) {
2476           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2477             // Check to see if we are shifting out everything but the sign bit.
2478             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2479                 SI->getType()->getPrimitiveSizeInBits()-1) {
2480               // Ok, the transformation is safe.  Insert AShr.
2481               return BinaryOperator::Create(Instruction::AShr, 
2482                                           SI->getOperand(0), CU, SI->getName());
2483             }
2484           }
2485         }
2486         else if (SI->getOpcode() == Instruction::AShr) {
2487           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2488             // Check to see if we are shifting out everything but the sign bit.
2489             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2490                 SI->getType()->getPrimitiveSizeInBits()-1) {
2491               // Ok, the transformation is safe.  Insert LShr. 
2492               return BinaryOperator::CreateLShr(
2493                                           SI->getOperand(0), CU, SI->getName());
2494             }
2495           }
2496         }
2497       }
2498     }
2499
2500     // Try to fold constant sub into select arguments.
2501     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2502       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2503         return R;
2504
2505     // C - zext(bool) -> bool ? C - 1 : C
2506     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2507       if (ZI->getSrcTy() == Type::Int1Ty)
2508         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2509   }
2510
2511   if (I.getType() == Type::Int1Ty)
2512     return BinaryOperator::CreateXor(Op0, Op1);
2513
2514   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2515     if (Op1I->getOpcode() == Instruction::Add) {
2516       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2517         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2518                                          I.getName());
2519       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2520         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2521                                          I.getName());
2522       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2523         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2524           // C1-(X+C2) --> (C1-C2)-X
2525           return BinaryOperator::CreateSub(
2526             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2527       }
2528     }
2529
2530     if (Op1I->hasOneUse()) {
2531       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2532       // is not used by anyone else...
2533       //
2534       if (Op1I->getOpcode() == Instruction::Sub) {
2535         // Swap the two operands of the subexpr...
2536         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2537         Op1I->setOperand(0, IIOp1);
2538         Op1I->setOperand(1, IIOp0);
2539
2540         // Create the new top level add instruction...
2541         return BinaryOperator::CreateAdd(Op0, Op1);
2542       }
2543
2544       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2545       //
2546       if (Op1I->getOpcode() == Instruction::And &&
2547           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2548         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2549
2550         Value *NewNot =
2551           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2552                                                         OtherOp, "B.not"), I);
2553         return BinaryOperator::CreateAnd(Op0, NewNot);
2554       }
2555
2556       // 0 - (X sdiv C)  -> (X sdiv -C)
2557       if (Op1I->getOpcode() == Instruction::SDiv)
2558         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2559           if (CSI->isZero())
2560             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2561               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2562                                           Context->getConstantExprNeg(DivRHS));
2563
2564       // X - X*C --> X * (1-C)
2565       ConstantInt *C2 = 0;
2566       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2567         Constant *CP1 = 
2568           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2569                                              C2);
2570         return BinaryOperator::CreateMul(Op0, CP1);
2571       }
2572     }
2573   }
2574
2575   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2576     if (Op0I->getOpcode() == Instruction::Add) {
2577       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2578         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2579       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2580         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2581     } else if (Op0I->getOpcode() == Instruction::Sub) {
2582       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2583         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2584                                          I.getName());
2585     }
2586   }
2587
2588   ConstantInt *C1;
2589   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2590     if (X == Op1)  // X*C - X --> X * (C-1)
2591       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2592
2593     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2594     if (X == dyn_castFoldableMul(Op1, C2, Context))
2595       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2596   }
2597   return 0;
2598 }
2599
2600 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2601   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2602
2603   // If this is a 'B = x-(-A)', change to B = x+A...
2604   if (Value *V = dyn_castFNegVal(Op1, Context))
2605     return BinaryOperator::CreateFAdd(Op0, V);
2606
2607   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2608     if (Op1I->getOpcode() == Instruction::FAdd) {
2609       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2610         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2611                                           I.getName());
2612       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2613         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2614                                           I.getName());
2615     }
2616   }
2617
2618   return 0;
2619 }
2620
2621 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2622 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2623 /// TrueIfSigned if the result of the comparison is true when the input value is
2624 /// signed.
2625 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2626                            bool &TrueIfSigned) {
2627   switch (pred) {
2628   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2629     TrueIfSigned = true;
2630     return RHS->isZero();
2631   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2632     TrueIfSigned = true;
2633     return RHS->isAllOnesValue();
2634   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2635     TrueIfSigned = false;
2636     return RHS->isAllOnesValue();
2637   case ICmpInst::ICMP_UGT:
2638     // True if LHS u> RHS and RHS == high-bit-mask - 1
2639     TrueIfSigned = true;
2640     return RHS->getValue() ==
2641       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2642   case ICmpInst::ICMP_UGE: 
2643     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2644     TrueIfSigned = true;
2645     return RHS->getValue().isSignBit();
2646   default:
2647     return false;
2648   }
2649 }
2650
2651 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2652   bool Changed = SimplifyCommutative(I);
2653   Value *Op0 = I.getOperand(0);
2654
2655   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2656     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2657
2658   // Simplify mul instructions with a constant RHS...
2659   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2660     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2661
2662       // ((X << C1)*C2) == (X * (C2 << C1))
2663       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2664         if (SI->getOpcode() == Instruction::Shl)
2665           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2666             return BinaryOperator::CreateMul(SI->getOperand(0),
2667                                         Context->getConstantExprShl(CI, ShOp));
2668
2669       if (CI->isZero())
2670         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2671       if (CI->equalsInt(1))                  // X * 1  == X
2672         return ReplaceInstUsesWith(I, Op0);
2673       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2674         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2675
2676       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2677       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2678         return BinaryOperator::CreateShl(Op0,
2679                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2680       }
2681     } else if (isa<VectorType>(Op1->getType())) {
2682       if (Op1->isNullValue())
2683         return ReplaceInstUsesWith(I, Op1);
2684
2685       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2686         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2687           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2688
2689         // As above, vector X*splat(1.0) -> X in all defined cases.
2690         if (Constant *Splat = Op1V->getSplatValue()) {
2691           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2692             if (CI->equalsInt(1))
2693               return ReplaceInstUsesWith(I, Op0);
2694         }
2695       }
2696     }
2697     
2698     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2699       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2700           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2701         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2702         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2703                                                      Op1, "tmp");
2704         InsertNewInstBefore(Add, I);
2705         Value *C1C2 = Context->getConstantExprMul(Op1, 
2706                                            cast<Constant>(Op0I->getOperand(1)));
2707         return BinaryOperator::CreateAdd(Add, C1C2);
2708         
2709       }
2710
2711     // Try to fold constant mul into select arguments.
2712     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2713       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2714         return R;
2715
2716     if (isa<PHINode>(Op0))
2717       if (Instruction *NV = FoldOpIntoPhi(I))
2718         return NV;
2719   }
2720
2721   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2722     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2723       return BinaryOperator::CreateMul(Op0v, Op1v);
2724
2725   // (X / Y) *  Y = X - (X % Y)
2726   // (X / Y) * -Y = (X % Y) - X
2727   {
2728     Value *Op1 = I.getOperand(1);
2729     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2730     if (!BO ||
2731         (BO->getOpcode() != Instruction::UDiv && 
2732          BO->getOpcode() != Instruction::SDiv)) {
2733       Op1 = Op0;
2734       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2735     }
2736     Value *Neg = dyn_castNegVal(Op1, Context);
2737     if (BO && BO->hasOneUse() &&
2738         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2739         (BO->getOpcode() == Instruction::UDiv ||
2740          BO->getOpcode() == Instruction::SDiv)) {
2741       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2742
2743       Instruction *Rem;
2744       if (BO->getOpcode() == Instruction::UDiv)
2745         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2746       else
2747         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2748
2749       InsertNewInstBefore(Rem, I);
2750       Rem->takeName(BO);
2751
2752       if (Op1BO == Op1)
2753         return BinaryOperator::CreateSub(Op0BO, Rem);
2754       else
2755         return BinaryOperator::CreateSub(Rem, Op0BO);
2756     }
2757   }
2758
2759   if (I.getType() == Type::Int1Ty)
2760     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2761
2762   // If one of the operands of the multiply is a cast from a boolean value, then
2763   // we know the bool is either zero or one, so this is a 'masking' multiply.
2764   // See if we can simplify things based on how the boolean was originally
2765   // formed.
2766   CastInst *BoolCast = 0;
2767   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2768     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2769       BoolCast = CI;
2770   if (!BoolCast)
2771     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2772       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2773         BoolCast = CI;
2774   if (BoolCast) {
2775     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2776       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2777       const Type *SCOpTy = SCIOp0->getType();
2778       bool TIS = false;
2779       
2780       // If the icmp is true iff the sign bit of X is set, then convert this
2781       // multiply into a shift/and combination.
2782       if (isa<ConstantInt>(SCIOp1) &&
2783           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2784           TIS) {
2785         // Shift the X value right to turn it into "all signbits".
2786         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2787                                           SCOpTy->getPrimitiveSizeInBits()-1);
2788         Value *V =
2789           InsertNewInstBefore(
2790             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2791                                             BoolCast->getOperand(0)->getName()+
2792                                             ".mask"), I);
2793
2794         // If the multiply type is not the same as the source type, sign extend
2795         // or truncate to the multiply type.
2796         if (I.getType() != V->getType()) {
2797           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2798           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2799           Instruction::CastOps opcode = 
2800             (SrcBits == DstBits ? Instruction::BitCast : 
2801              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2802           V = InsertCastBefore(opcode, V, I.getType(), I);
2803         }
2804
2805         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2806         return BinaryOperator::CreateAnd(V, OtherOp);
2807       }
2808     }
2809   }
2810
2811   return Changed ? &I : 0;
2812 }
2813
2814 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2815   bool Changed = SimplifyCommutative(I);
2816   Value *Op0 = I.getOperand(0);
2817
2818   // Simplify mul instructions with a constant RHS...
2819   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2820     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2821       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2822       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2823       if (Op1F->isExactlyValue(1.0))
2824         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2825     } else if (isa<VectorType>(Op1->getType())) {
2826       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2827         // As above, vector X*splat(1.0) -> X in all defined cases.
2828         if (Constant *Splat = Op1V->getSplatValue()) {
2829           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2830             if (F->isExactlyValue(1.0))
2831               return ReplaceInstUsesWith(I, Op0);
2832         }
2833       }
2834     }
2835
2836     // Try to fold constant mul into select arguments.
2837     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2838       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2839         return R;
2840
2841     if (isa<PHINode>(Op0))
2842       if (Instruction *NV = FoldOpIntoPhi(I))
2843         return NV;
2844   }
2845
2846   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2847     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2848       return BinaryOperator::CreateFMul(Op0v, Op1v);
2849
2850   return Changed ? &I : 0;
2851 }
2852
2853 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2854 /// instruction.
2855 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2856   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2857   
2858   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2859   int NonNullOperand = -1;
2860   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2861     if (ST->isNullValue())
2862       NonNullOperand = 2;
2863   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2864   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2865     if (ST->isNullValue())
2866       NonNullOperand = 1;
2867   
2868   if (NonNullOperand == -1)
2869     return false;
2870   
2871   Value *SelectCond = SI->getOperand(0);
2872   
2873   // Change the div/rem to use 'Y' instead of the select.
2874   I.setOperand(1, SI->getOperand(NonNullOperand));
2875   
2876   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2877   // problem.  However, the select, or the condition of the select may have
2878   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2879   // propagate the known value for the select into other uses of it, and
2880   // propagate a known value of the condition into its other users.
2881   
2882   // If the select and condition only have a single use, don't bother with this,
2883   // early exit.
2884   if (SI->use_empty() && SelectCond->hasOneUse())
2885     return true;
2886   
2887   // Scan the current block backward, looking for other uses of SI.
2888   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2889   
2890   while (BBI != BBFront) {
2891     --BBI;
2892     // If we found a call to a function, we can't assume it will return, so
2893     // information from below it cannot be propagated above it.
2894     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2895       break;
2896     
2897     // Replace uses of the select or its condition with the known values.
2898     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2899          I != E; ++I) {
2900       if (*I == SI) {
2901         *I = SI->getOperand(NonNullOperand);
2902         AddToWorkList(BBI);
2903       } else if (*I == SelectCond) {
2904         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2905                                    Context->getConstantIntFalse();
2906         AddToWorkList(BBI);
2907       }
2908     }
2909     
2910     // If we past the instruction, quit looking for it.
2911     if (&*BBI == SI)
2912       SI = 0;
2913     if (&*BBI == SelectCond)
2914       SelectCond = 0;
2915     
2916     // If we ran out of things to eliminate, break out of the loop.
2917     if (SelectCond == 0 && SI == 0)
2918       break;
2919     
2920   }
2921   return true;
2922 }
2923
2924
2925 /// This function implements the transforms on div instructions that work
2926 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2927 /// used by the visitors to those instructions.
2928 /// @brief Transforms common to all three div instructions
2929 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2930   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2931
2932   // undef / X -> 0        for integer.
2933   // undef / X -> undef    for FP (the undef could be a snan).
2934   if (isa<UndefValue>(Op0)) {
2935     if (Op0->getType()->isFPOrFPVector())
2936       return ReplaceInstUsesWith(I, Op0);
2937     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2938   }
2939
2940   // X / undef -> undef
2941   if (isa<UndefValue>(Op1))
2942     return ReplaceInstUsesWith(I, Op1);
2943
2944   return 0;
2945 }
2946
2947 /// This function implements the transforms common to both integer division
2948 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2949 /// division instructions.
2950 /// @brief Common integer divide transforms
2951 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2952   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2953
2954   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2955   if (Op0 == Op1) {
2956     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2957       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2958       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2959       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2960     }
2961
2962     Constant *CI = Context->getConstantInt(I.getType(), 1);
2963     return ReplaceInstUsesWith(I, CI);
2964   }
2965   
2966   if (Instruction *Common = commonDivTransforms(I))
2967     return Common;
2968   
2969   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2970   // This does not apply for fdiv.
2971   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2972     return &I;
2973
2974   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2975     // div X, 1 == X
2976     if (RHS->equalsInt(1))
2977       return ReplaceInstUsesWith(I, Op0);
2978
2979     // (X / C1) / C2  -> X / (C1*C2)
2980     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2981       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2982         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2983           if (MultiplyOverflows(RHS, LHSRHS,
2984                                 I.getOpcode()==Instruction::SDiv, Context))
2985             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2986           else 
2987             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2988                                       Context->getConstantExprMul(RHS, LHSRHS));
2989         }
2990
2991     if (!RHS->isZero()) { // avoid X udiv 0
2992       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994           return R;
2995       if (isa<PHINode>(Op0))
2996         if (Instruction *NV = FoldOpIntoPhi(I))
2997           return NV;
2998     }
2999   }
3000
3001   // 0 / X == 0, we don't need to preserve faults!
3002   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3003     if (LHS->equalsInt(0))
3004       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3005
3006   // It can't be division by zero, hence it must be division by one.
3007   if (I.getType() == Type::Int1Ty)
3008     return ReplaceInstUsesWith(I, Op0);
3009
3010   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3011     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3012       // div X, 1 == X
3013       if (X->isOne())
3014         return ReplaceInstUsesWith(I, Op0);
3015   }
3016
3017   return 0;
3018 }
3019
3020 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3021   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3022
3023   // Handle the integer div common cases
3024   if (Instruction *Common = commonIDivTransforms(I))
3025     return Common;
3026
3027   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3028     // X udiv C^2 -> X >> C
3029     // Check to see if this is an unsigned division with an exact power of 2,
3030     // if so, convert to a right shift.
3031     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3032       return BinaryOperator::CreateLShr(Op0, 
3033             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3034
3035     // X udiv C, where C >= signbit
3036     if (C->getValue().isNegative()) {
3037       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3038                                                     ICmpInst::ICMP_ULT, Op0, C),
3039                                       I);
3040       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3041                                 Context->getConstantInt(I.getType(), 1));
3042     }
3043   }
3044
3045   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3046   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3047     if (RHSI->getOpcode() == Instruction::Shl &&
3048         isa<ConstantInt>(RHSI->getOperand(0))) {
3049       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3050       if (C1.isPowerOf2()) {
3051         Value *N = RHSI->getOperand(1);
3052         const Type *NTy = N->getType();
3053         if (uint32_t C2 = C1.logBase2()) {
3054           Constant *C2V = Context->getConstantInt(NTy, C2);
3055           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3056         }
3057         return BinaryOperator::CreateLShr(Op0, N);
3058       }
3059     }
3060   }
3061   
3062   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3063   // where C1&C2 are powers of two.
3064   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3065     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3066       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3067         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3068         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3069           // Compute the shift amounts
3070           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3071           // Construct the "on true" case of the select
3072           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3073           Instruction *TSI = BinaryOperator::CreateLShr(
3074                                                  Op0, TC, SI->getName()+".t");
3075           TSI = InsertNewInstBefore(TSI, I);
3076   
3077           // Construct the "on false" case of the select
3078           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3079           Instruction *FSI = BinaryOperator::CreateLShr(
3080                                                  Op0, FC, SI->getName()+".f");
3081           FSI = InsertNewInstBefore(FSI, I);
3082
3083           // construct the select instruction and return it.
3084           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3085         }
3086       }
3087   return 0;
3088 }
3089
3090 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3091   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3092
3093   // Handle the integer div common cases
3094   if (Instruction *Common = commonIDivTransforms(I))
3095     return Common;
3096
3097   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3098     // sdiv X, -1 == -X
3099     if (RHS->isAllOnesValue())
3100       return BinaryOperator::CreateNeg(*Context, Op0);
3101   }
3102
3103   // If the sign bits of both operands are zero (i.e. we can prove they are
3104   // unsigned inputs), turn this into a udiv.
3105   if (I.getType()->isInteger()) {
3106     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3107     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3108       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3109       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3110     }
3111   }      
3112   
3113   return 0;
3114 }
3115
3116 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3117   return commonDivTransforms(I);
3118 }
3119
3120 /// This function implements the transforms on rem instructions that work
3121 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3122 /// is used by the visitors to those instructions.
3123 /// @brief Transforms common to all three rem instructions
3124 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3125   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3126
3127   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3128     if (I.getType()->isFPOrFPVector())
3129       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3130     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3131   }
3132   if (isa<UndefValue>(Op1))
3133     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3134
3135   // Handle cases involving: rem X, (select Cond, Y, Z)
3136   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3137     return &I;
3138
3139   return 0;
3140 }
3141
3142 /// This function implements the transforms common to both integer remainder
3143 /// instructions (urem and srem). It is called by the visitors to those integer
3144 /// remainder instructions.
3145 /// @brief Common integer remainder transforms
3146 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3147   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3148
3149   if (Instruction *common = commonRemTransforms(I))
3150     return common;
3151
3152   // 0 % X == 0 for integer, we don't need to preserve faults!
3153   if (Constant *LHS = dyn_cast<Constant>(Op0))
3154     if (LHS->isNullValue())
3155       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3156
3157   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3158     // X % 0 == undef, we don't need to preserve faults!
3159     if (RHS->equalsInt(0))
3160       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3161     
3162     if (RHS->equalsInt(1))  // X % 1 == 0
3163       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3164
3165     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3166       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3167         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3168           return R;
3169       } else if (isa<PHINode>(Op0I)) {
3170         if (Instruction *NV = FoldOpIntoPhi(I))
3171           return NV;
3172       }
3173
3174       // See if we can fold away this rem instruction.
3175       if (SimplifyDemandedInstructionBits(I))
3176         return &I;
3177     }
3178   }
3179
3180   return 0;
3181 }
3182
3183 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3184   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3185
3186   if (Instruction *common = commonIRemTransforms(I))
3187     return common;
3188   
3189   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3190     // X urem C^2 -> X and C
3191     // Check to see if this is an unsigned remainder with an exact power of 2,
3192     // if so, convert to a bitwise and.
3193     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3194       if (C->getValue().isPowerOf2())
3195         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3196   }
3197
3198   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3199     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3200     if (RHSI->getOpcode() == Instruction::Shl &&
3201         isa<ConstantInt>(RHSI->getOperand(0))) {
3202       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3203         Constant *N1 = Context->getAllOnesValue(I.getType());
3204         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3205                                                                    "tmp"), I);
3206         return BinaryOperator::CreateAnd(Op0, Add);
3207       }
3208     }
3209   }
3210
3211   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3212   // where C1&C2 are powers of two.
3213   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3214     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3215       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3216         // STO == 0 and SFO == 0 handled above.
3217         if ((STO->getValue().isPowerOf2()) && 
3218             (SFO->getValue().isPowerOf2())) {
3219           Value *TrueAnd = InsertNewInstBefore(
3220             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3221                                       SI->getName()+".t"), I);
3222           Value *FalseAnd = InsertNewInstBefore(
3223             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3224                                       SI->getName()+".f"), I);
3225           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3226         }
3227       }
3228   }
3229   
3230   return 0;
3231 }
3232
3233 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3234   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3235
3236   // Handle the integer rem common cases
3237   if (Instruction *common = commonIRemTransforms(I))
3238     return common;
3239   
3240   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3241     if (!isa<Constant>(RHSNeg) ||
3242         (isa<ConstantInt>(RHSNeg) &&
3243          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3244       // X % -Y -> X % Y
3245       AddUsesToWorkList(I);
3246       I.setOperand(1, RHSNeg);
3247       return &I;
3248     }
3249
3250   // If the sign bits of both operands are zero (i.e. we can prove they are
3251   // unsigned inputs), turn this into a urem.
3252   if (I.getType()->isInteger()) {
3253     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3254     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3255       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3256       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3257     }
3258   }
3259
3260   // If it's a constant vector, flip any negative values positive.
3261   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3262     unsigned VWidth = RHSV->getNumOperands();
3263
3264     bool hasNegative = false;
3265     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3266       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3267         if (RHS->getValue().isNegative())
3268           hasNegative = true;
3269
3270     if (hasNegative) {
3271       std::vector<Constant *> Elts(VWidth);
3272       for (unsigned i = 0; i != VWidth; ++i) {
3273         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3274           if (RHS->getValue().isNegative())
3275             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3276           else
3277             Elts[i] = RHS;
3278         }
3279       }
3280
3281       Constant *NewRHSV = Context->getConstantVector(Elts);
3282       if (NewRHSV != RHSV) {
3283         AddUsesToWorkList(I);
3284         I.setOperand(1, NewRHSV);
3285         return &I;
3286       }
3287     }
3288   }
3289
3290   return 0;
3291 }
3292
3293 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3294   return commonRemTransforms(I);
3295 }
3296
3297 // isOneBitSet - Return true if there is exactly one bit set in the specified
3298 // constant.
3299 static bool isOneBitSet(const ConstantInt *CI) {
3300   return CI->getValue().isPowerOf2();
3301 }
3302
3303 // isHighOnes - Return true if the constant is of the form 1+0+.
3304 // This is the same as lowones(~X).
3305 static bool isHighOnes(const ConstantInt *CI) {
3306   return (~CI->getValue() + 1).isPowerOf2();
3307 }
3308
3309 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3310 /// are carefully arranged to allow folding of expressions such as:
3311 ///
3312 ///      (A < B) | (A > B) --> (A != B)
3313 ///
3314 /// Note that this is only valid if the first and second predicates have the
3315 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3316 ///
3317 /// Three bits are used to represent the condition, as follows:
3318 ///   0  A > B
3319 ///   1  A == B
3320 ///   2  A < B
3321 ///
3322 /// <=>  Value  Definition
3323 /// 000     0   Always false
3324 /// 001     1   A >  B
3325 /// 010     2   A == B
3326 /// 011     3   A >= B
3327 /// 100     4   A <  B
3328 /// 101     5   A != B
3329 /// 110     6   A <= B
3330 /// 111     7   Always true
3331 ///  
3332 static unsigned getICmpCode(const ICmpInst *ICI) {
3333   switch (ICI->getPredicate()) {
3334     // False -> 0
3335   case ICmpInst::ICMP_UGT: return 1;  // 001
3336   case ICmpInst::ICMP_SGT: return 1;  // 001
3337   case ICmpInst::ICMP_EQ:  return 2;  // 010
3338   case ICmpInst::ICMP_UGE: return 3;  // 011
3339   case ICmpInst::ICMP_SGE: return 3;  // 011
3340   case ICmpInst::ICMP_ULT: return 4;  // 100
3341   case ICmpInst::ICMP_SLT: return 4;  // 100
3342   case ICmpInst::ICMP_NE:  return 5;  // 101
3343   case ICmpInst::ICMP_ULE: return 6;  // 110
3344   case ICmpInst::ICMP_SLE: return 6;  // 110
3345     // True -> 7
3346   default:
3347     llvm_unreachable("Invalid ICmp predicate!");
3348     return 0;
3349   }
3350 }
3351
3352 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3353 /// predicate into a three bit mask. It also returns whether it is an ordered
3354 /// predicate by reference.
3355 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3356   isOrdered = false;
3357   switch (CC) {
3358   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3359   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3360   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3361   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3362   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3363   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3364   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3365   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3366   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3367   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3368   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3369   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3370   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3371   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3372     // True -> 7
3373   default:
3374     // Not expecting FCMP_FALSE and FCMP_TRUE;
3375     llvm_unreachable("Unexpected FCmp predicate!");
3376     return 0;
3377   }
3378 }
3379
3380 /// getICmpValue - This is the complement of getICmpCode, which turns an
3381 /// opcode and two operands into either a constant true or false, or a brand 
3382 /// new ICmp instruction. The sign is passed in to determine which kind
3383 /// of predicate to use in the new icmp instruction.
3384 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3385                            LLVMContext *Context) {
3386   switch (code) {
3387   default: llvm_unreachable("Illegal ICmp code!");
3388   case  0: return Context->getConstantIntFalse();
3389   case  1: 
3390     if (sign)
3391       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3392     else
3393       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3394   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3395   case  3: 
3396     if (sign)
3397       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3398     else
3399       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3400   case  4: 
3401     if (sign)
3402       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3403     else
3404       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3405   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3406   case  6: 
3407     if (sign)
3408       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3409     else
3410       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3411   case  7: return Context->getConstantIntTrue();
3412   }
3413 }
3414
3415 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3416 /// opcode and two operands into either a FCmp instruction. isordered is passed
3417 /// in to determine which kind of predicate to use in the new fcmp instruction.
3418 static Value *getFCmpValue(bool isordered, unsigned code,
3419                            Value *LHS, Value *RHS, LLVMContext *Context) {
3420   switch (code) {
3421   default: llvm_unreachable("Illegal FCmp code!");
3422   case  0:
3423     if (isordered)
3424       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3425     else
3426       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3427   case  1: 
3428     if (isordered)
3429       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3430     else
3431       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3432   case  2: 
3433     if (isordered)
3434       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3435     else
3436       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3437   case  3: 
3438     if (isordered)
3439       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3440     else
3441       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3442   case  4: 
3443     if (isordered)
3444       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3445     else
3446       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3447   case  5: 
3448     if (isordered)
3449       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3450     else
3451       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3452   case  6: 
3453     if (isordered)
3454       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3455     else
3456       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3457   case  7: return Context->getConstantIntTrue();
3458   }
3459 }
3460
3461 /// PredicatesFoldable - Return true if both predicates match sign or if at
3462 /// least one of them is an equality comparison (which is signless).
3463 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3464   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3465          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3466          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3467 }
3468
3469 namespace { 
3470 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3471 struct FoldICmpLogical {
3472   InstCombiner &IC;
3473   Value *LHS, *RHS;
3474   ICmpInst::Predicate pred;
3475   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3476     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3477       pred(ICI->getPredicate()) {}
3478   bool shouldApply(Value *V) const {
3479     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3480       if (PredicatesFoldable(pred, ICI->getPredicate()))
3481         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3482                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3483     return false;
3484   }
3485   Instruction *apply(Instruction &Log) const {
3486     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3487     if (ICI->getOperand(0) != LHS) {
3488       assert(ICI->getOperand(1) == LHS);
3489       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3490     }
3491
3492     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3493     unsigned LHSCode = getICmpCode(ICI);
3494     unsigned RHSCode = getICmpCode(RHSICI);
3495     unsigned Code;
3496     switch (Log.getOpcode()) {
3497     case Instruction::And: Code = LHSCode & RHSCode; break;
3498     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3499     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3500     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3501     }
3502
3503     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3504                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3505       
3506     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3507     if (Instruction *I = dyn_cast<Instruction>(RV))
3508       return I;
3509     // Otherwise, it's a constant boolean value...
3510     return IC.ReplaceInstUsesWith(Log, RV);
3511   }
3512 };
3513 } // end anonymous namespace
3514
3515 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3516 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3517 // guaranteed to be a binary operator.
3518 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3519                                     ConstantInt *OpRHS,
3520                                     ConstantInt *AndRHS,
3521                                     BinaryOperator &TheAnd) {
3522   Value *X = Op->getOperand(0);
3523   Constant *Together = 0;
3524   if (!Op->isShift())
3525     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3526
3527   switch (Op->getOpcode()) {
3528   case Instruction::Xor:
3529     if (Op->hasOneUse()) {
3530       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3531       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3532       InsertNewInstBefore(And, TheAnd);
3533       And->takeName(Op);
3534       return BinaryOperator::CreateXor(And, Together);
3535     }
3536     break;
3537   case Instruction::Or:
3538     if (Together == AndRHS) // (X | C) & C --> C
3539       return ReplaceInstUsesWith(TheAnd, AndRHS);
3540
3541     if (Op->hasOneUse() && Together != OpRHS) {
3542       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3543       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3544       InsertNewInstBefore(Or, TheAnd);
3545       Or->takeName(Op);
3546       return BinaryOperator::CreateAnd(Or, AndRHS);
3547     }
3548     break;
3549   case Instruction::Add:
3550     if (Op->hasOneUse()) {
3551       // Adding a one to a single bit bit-field should be turned into an XOR
3552       // of the bit.  First thing to check is to see if this AND is with a
3553       // single bit constant.
3554       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3555
3556       // If there is only one bit set...
3557       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3558         // Ok, at this point, we know that we are masking the result of the
3559         // ADD down to exactly one bit.  If the constant we are adding has
3560         // no bits set below this bit, then we can eliminate the ADD.
3561         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3562
3563         // Check to see if any bits below the one bit set in AndRHSV are set.
3564         if ((AddRHS & (AndRHSV-1)) == 0) {
3565           // If not, the only thing that can effect the output of the AND is
3566           // the bit specified by AndRHSV.  If that bit is set, the effect of
3567           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3568           // no effect.
3569           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3570             TheAnd.setOperand(0, X);
3571             return &TheAnd;
3572           } else {
3573             // Pull the XOR out of the AND.
3574             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3575             InsertNewInstBefore(NewAnd, TheAnd);
3576             NewAnd->takeName(Op);
3577             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3578           }
3579         }
3580       }
3581     }
3582     break;
3583
3584   case Instruction::Shl: {
3585     // We know that the AND will not produce any of the bits shifted in, so if
3586     // the anded constant includes them, clear them now!
3587     //
3588     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3589     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3590     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3591     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3592
3593     if (CI->getValue() == ShlMask) { 
3594     // Masking out bits that the shift already masks
3595       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3596     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3597       TheAnd.setOperand(1, CI);
3598       return &TheAnd;
3599     }
3600     break;
3601   }
3602   case Instruction::LShr:
3603   {
3604     // We know that the AND will not produce any of the bits shifted in, so if
3605     // the anded constant includes them, clear them now!  This only applies to
3606     // unsigned shifts, because a signed shr may bring in set bits!
3607     //
3608     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3611     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3612
3613     if (CI->getValue() == ShrMask) {   
3614     // Masking out bits that the shift already masks.
3615       return ReplaceInstUsesWith(TheAnd, Op);
3616     } else if (CI != AndRHS) {
3617       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3618       return &TheAnd;
3619     }
3620     break;
3621   }
3622   case Instruction::AShr:
3623     // Signed shr.
3624     // See if this is shifting in some sign extension, then masking it out
3625     // with an and.
3626     if (Op->hasOneUse()) {
3627       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3628       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3629       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3630       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3631       if (C == AndRHS) {          // Masking out bits shifted in.
3632         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3633         // Make the argument unsigned.
3634         Value *ShVal = Op->getOperand(0);
3635         ShVal = InsertNewInstBefore(
3636             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3637                                    Op->getName()), TheAnd);
3638         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3639       }
3640     }
3641     break;
3642   }
3643   return 0;
3644 }
3645
3646
3647 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3648 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3649 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3650 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3651 /// insert new instructions.
3652 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3653                                            bool isSigned, bool Inside, 
3654                                            Instruction &IB) {
3655   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3656             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3657          "Lo is not <= Hi in range emission code!");
3658     
3659   if (Inside) {
3660     if (Lo == Hi)  // Trivially false.
3661       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3662
3663     // V >= Min && V < Hi --> V < Hi
3664     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3665       ICmpInst::Predicate pred = (isSigned ? 
3666         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3667       return new ICmpInst(*Context, pred, V, Hi);
3668     }
3669
3670     // Emit V-Lo <u Hi-Lo
3671     Constant *NegLo = Context->getConstantExprNeg(Lo);
3672     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3673     InsertNewInstBefore(Add, IB);
3674     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3675     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3676   }
3677
3678   if (Lo == Hi)  // Trivially true.
3679     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3680
3681   // V < Min || V >= Hi -> V > Hi-1
3682   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3683   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3684     ICmpInst::Predicate pred = (isSigned ? 
3685         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3686     return new ICmpInst(*Context, pred, V, Hi);
3687   }
3688
3689   // Emit V-Lo >u Hi-1-Lo
3690   // Note that Hi has already had one subtracted from it, above.
3691   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3692   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3693   InsertNewInstBefore(Add, IB);
3694   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3695   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3696 }
3697
3698 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3699 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3700 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3701 // not, since all 1s are not contiguous.
3702 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3703   const APInt& V = Val->getValue();
3704   uint32_t BitWidth = Val->getType()->getBitWidth();
3705   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3706
3707   // look for the first zero bit after the run of ones
3708   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3709   // look for the first non-zero bit
3710   ME = V.getActiveBits(); 
3711   return true;
3712 }
3713
3714 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3715 /// where isSub determines whether the operator is a sub.  If we can fold one of
3716 /// the following xforms:
3717 /// 
3718 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3719 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3720 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3721 ///
3722 /// return (A +/- B).
3723 ///
3724 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3725                                         ConstantInt *Mask, bool isSub,
3726                                         Instruction &I) {
3727   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3728   if (!LHSI || LHSI->getNumOperands() != 2 ||
3729       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3730
3731   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3732
3733   switch (LHSI->getOpcode()) {
3734   default: return 0;
3735   case Instruction::And:
3736     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3737       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3738       if ((Mask->getValue().countLeadingZeros() + 
3739            Mask->getValue().countPopulation()) == 
3740           Mask->getValue().getBitWidth())
3741         break;
3742
3743       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3744       // part, we don't need any explicit masks to take them out of A.  If that
3745       // is all N is, ignore it.
3746       uint32_t MB = 0, ME = 0;
3747       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3748         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3749         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3750         if (MaskedValueIsZero(RHS, Mask))
3751           break;
3752       }
3753     }
3754     return 0;
3755   case Instruction::Or:
3756   case Instruction::Xor:
3757     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3758     if ((Mask->getValue().countLeadingZeros() + 
3759          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3760         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3761       break;
3762     return 0;
3763   }
3764   
3765   Instruction *New;
3766   if (isSub)
3767     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3768   else
3769     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3770   return InsertNewInstBefore(New, I);
3771 }
3772
3773 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3774 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3775                                           ICmpInst *LHS, ICmpInst *RHS) {
3776   Value *Val, *Val2;
3777   ConstantInt *LHSCst, *RHSCst;
3778   ICmpInst::Predicate LHSCC, RHSCC;
3779   
3780   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3781   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3782                          m_ConstantInt(LHSCst)), *Context) ||
3783       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3784                          m_ConstantInt(RHSCst)), *Context))
3785     return 0;
3786   
3787   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3788   // where C is a power of 2
3789   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3790       LHSCst->getValue().isPowerOf2()) {
3791     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3792     InsertNewInstBefore(NewOr, I);
3793     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3794   }
3795   
3796   // From here on, we only handle:
3797   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3798   if (Val != Val2) return 0;
3799   
3800   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3801   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3802       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3803       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3804       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3805     return 0;
3806   
3807   // We can't fold (ugt x, C) & (sgt x, C2).
3808   if (!PredicatesFoldable(LHSCC, RHSCC))
3809     return 0;
3810     
3811   // Ensure that the larger constant is on the RHS.
3812   bool ShouldSwap;
3813   if (ICmpInst::isSignedPredicate(LHSCC) ||
3814       (ICmpInst::isEquality(LHSCC) && 
3815        ICmpInst::isSignedPredicate(RHSCC)))
3816     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3817   else
3818     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3819     
3820   if (ShouldSwap) {
3821     std::swap(LHS, RHS);
3822     std::swap(LHSCst, RHSCst);
3823     std::swap(LHSCC, RHSCC);
3824   }
3825
3826   // At this point, we know we have have two icmp instructions
3827   // comparing a value against two constants and and'ing the result
3828   // together.  Because of the above check, we know that we only have
3829   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3830   // (from the FoldICmpLogical check above), that the two constants 
3831   // are not equal and that the larger constant is on the RHS
3832   assert(LHSCst != RHSCst && "Compares not folded above?");
3833
3834   switch (LHSCC) {
3835   default: llvm_unreachable("Unknown integer condition code!");
3836   case ICmpInst::ICMP_EQ:
3837     switch (RHSCC) {
3838     default: llvm_unreachable("Unknown integer condition code!");
3839     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3840     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3841     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3842       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3843     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3844     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3845     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3846       return ReplaceInstUsesWith(I, LHS);
3847     }
3848   case ICmpInst::ICMP_NE:
3849     switch (RHSCC) {
3850     default: llvm_unreachable("Unknown integer condition code!");
3851     case ICmpInst::ICMP_ULT:
3852       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3853         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3854       break;                        // (X != 13 & X u< 15) -> no change
3855     case ICmpInst::ICMP_SLT:
3856       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3857         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3858       break;                        // (X != 13 & X s< 15) -> no change
3859     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3860     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3861     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3862       return ReplaceInstUsesWith(I, RHS);
3863     case ICmpInst::ICMP_NE:
3864       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3865         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3866         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3867                                                      Val->getName()+".off");
3868         InsertNewInstBefore(Add, I);
3869         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3870                             Context->getConstantInt(Add->getType(), 1));
3871       }
3872       break;                        // (X != 13 & X != 15) -> no change
3873     }
3874     break;
3875   case ICmpInst::ICMP_ULT:
3876     switch (RHSCC) {
3877     default: llvm_unreachable("Unknown integer condition code!");
3878     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3879     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3880       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3881     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3882       break;
3883     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3884     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3885       return ReplaceInstUsesWith(I, LHS);
3886     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3887       break;
3888     }
3889     break;
3890   case ICmpInst::ICMP_SLT:
3891     switch (RHSCC) {
3892     default: llvm_unreachable("Unknown integer condition code!");
3893     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3894     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3895       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3896     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3897       break;
3898     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3899     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3900       return ReplaceInstUsesWith(I, LHS);
3901     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3902       break;
3903     }
3904     break;
3905   case ICmpInst::ICMP_UGT:
3906     switch (RHSCC) {
3907     default: llvm_unreachable("Unknown integer condition code!");
3908     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3909     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3910       return ReplaceInstUsesWith(I, RHS);
3911     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3912       break;
3913     case ICmpInst::ICMP_NE:
3914       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3915         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3916       break;                        // (X u> 13 & X != 15) -> no change
3917     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3918       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3919                              RHSCst, false, true, I);
3920     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3921       break;
3922     }
3923     break;
3924   case ICmpInst::ICMP_SGT:
3925     switch (RHSCC) {
3926     default: llvm_unreachable("Unknown integer condition code!");
3927     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3928     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3929       return ReplaceInstUsesWith(I, RHS);
3930     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3931       break;
3932     case ICmpInst::ICMP_NE:
3933       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3934         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3935       break;                        // (X s> 13 & X != 15) -> no change
3936     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3937       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3938                              RHSCst, true, true, I);
3939     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3940       break;
3941     }
3942     break;
3943   }
3944  
3945   return 0;
3946 }
3947
3948
3949 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3950   bool Changed = SimplifyCommutative(I);
3951   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3952
3953   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3954     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3955
3956   // and X, X = X
3957   if (Op0 == Op1)
3958     return ReplaceInstUsesWith(I, Op1);
3959
3960   // See if we can simplify any instructions used by the instruction whose sole 
3961   // purpose is to compute bits we don't care about.
3962   if (SimplifyDemandedInstructionBits(I))
3963     return &I;
3964   if (isa<VectorType>(I.getType())) {
3965     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3966       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3967         return ReplaceInstUsesWith(I, I.getOperand(0));
3968     } else if (isa<ConstantAggregateZero>(Op1)) {
3969       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3970     }
3971   }
3972
3973   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3974     const APInt& AndRHSMask = AndRHS->getValue();
3975     APInt NotAndRHS(~AndRHSMask);
3976
3977     // Optimize a variety of ((val OP C1) & C2) combinations...
3978     if (isa<BinaryOperator>(Op0)) {
3979       Instruction *Op0I = cast<Instruction>(Op0);
3980       Value *Op0LHS = Op0I->getOperand(0);
3981       Value *Op0RHS = Op0I->getOperand(1);
3982       switch (Op0I->getOpcode()) {
3983       case Instruction::Xor:
3984       case Instruction::Or:
3985         // If the mask is only needed on one incoming arm, push it up.
3986         if (Op0I->hasOneUse()) {
3987           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3988             // Not masking anything out for the LHS, move to RHS.
3989             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3990                                                    Op0RHS->getName()+".masked");
3991             InsertNewInstBefore(NewRHS, I);
3992             return BinaryOperator::Create(
3993                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3994           }
3995           if (!isa<Constant>(Op0RHS) &&
3996               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3997             // Not masking anything out for the RHS, move to LHS.
3998             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3999                                                    Op0LHS->getName()+".masked");
4000             InsertNewInstBefore(NewLHS, I);
4001             return BinaryOperator::Create(
4002                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4003           }
4004         }
4005
4006         break;
4007       case Instruction::Add:
4008         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4009         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4010         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4011         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4012           return BinaryOperator::CreateAnd(V, AndRHS);
4013         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4014           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4015         break;
4016
4017       case Instruction::Sub:
4018         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4019         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4020         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4021         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4022           return BinaryOperator::CreateAnd(V, AndRHS);
4023
4024         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4025         // has 1's for all bits that the subtraction with A might affect.
4026         if (Op0I->hasOneUse()) {
4027           uint32_t BitWidth = AndRHSMask.getBitWidth();
4028           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4029           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4030
4031           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4032           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4033               MaskedValueIsZero(Op0LHS, Mask)) {
4034             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4035             InsertNewInstBefore(NewNeg, I);
4036             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4037           }
4038         }
4039         break;
4040
4041       case Instruction::Shl:
4042       case Instruction::LShr:
4043         // (1 << x) & 1 --> zext(x == 0)
4044         // (1 >> x) & 1 --> zext(x == 0)
4045         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4046           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4047                                     Op0RHS, Context->getNullValue(I.getType()));
4048           InsertNewInstBefore(NewICmp, I);
4049           return new ZExtInst(NewICmp, I.getType());
4050         }
4051         break;
4052       }
4053
4054       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4055         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4056           return Res;
4057     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4058       // If this is an integer truncation or change from signed-to-unsigned, and
4059       // if the source is an and/or with immediate, transform it.  This
4060       // frequently occurs for bitfield accesses.
4061       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4062         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4063             CastOp->getNumOperands() == 2)
4064           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4065             if (CastOp->getOpcode() == Instruction::And) {
4066               // Change: and (cast (and X, C1) to T), C2
4067               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4068               // This will fold the two constants together, which may allow 
4069               // other simplifications.
4070               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4071                 CastOp->getOperand(0), I.getType(), 
4072                 CastOp->getName()+".shrunk");
4073               NewCast = InsertNewInstBefore(NewCast, I);
4074               // trunc_or_bitcast(C1)&C2
4075               Constant *C3 =
4076                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4077               C3 = Context->getConstantExprAnd(C3, AndRHS);
4078               return BinaryOperator::CreateAnd(NewCast, C3);
4079             } else if (CastOp->getOpcode() == Instruction::Or) {
4080               // Change: and (cast (or X, C1) to T), C2
4081               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4082               Constant *C3 =
4083                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4084               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4085                 // trunc(C1)&C2
4086                 return ReplaceInstUsesWith(I, AndRHS);
4087             }
4088           }
4089       }
4090     }
4091
4092     // Try to fold constant and into select arguments.
4093     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4094       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4095         return R;
4096     if (isa<PHINode>(Op0))
4097       if (Instruction *NV = FoldOpIntoPhi(I))
4098         return NV;
4099   }
4100
4101   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4102   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4103
4104   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4105     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4106
4107   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4108   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4109     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4110                                                I.getName()+".demorgan");
4111     InsertNewInstBefore(Or, I);
4112     return BinaryOperator::CreateNot(*Context, Or);
4113   }
4114   
4115   {
4116     Value *A = 0, *B = 0, *C = 0, *D = 0;
4117     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4118       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4119         return ReplaceInstUsesWith(I, Op1);
4120     
4121       // (A|B) & ~(A&B) -> A^B
4122       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4123         if ((A == C && B == D) || (A == D && B == C))
4124           return BinaryOperator::CreateXor(A, B);
4125       }
4126     }
4127     
4128     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4129       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4130         return ReplaceInstUsesWith(I, Op0);
4131
4132       // ~(A&B) & (A|B) -> A^B
4133       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4134         if ((A == C && B == D) || (A == D && B == C))
4135           return BinaryOperator::CreateXor(A, B);
4136       }
4137     }
4138     
4139     if (Op0->hasOneUse() &&
4140         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4141       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4142         I.swapOperands();     // Simplify below
4143         std::swap(Op0, Op1);
4144       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4145         cast<BinaryOperator>(Op0)->swapOperands();
4146         I.swapOperands();     // Simplify below
4147         std::swap(Op0, Op1);
4148       }
4149     }
4150
4151     if (Op1->hasOneUse() &&
4152         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4153       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4154         cast<BinaryOperator>(Op1)->swapOperands();
4155         std::swap(A, B);
4156       }
4157       if (A == Op0) {                                // A&(A^B) -> A & ~B
4158         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4159         InsertNewInstBefore(NotB, I);
4160         return BinaryOperator::CreateAnd(A, NotB);
4161       }
4162     }
4163
4164     // (A&((~A)|B)) -> A&B
4165     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4166         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4167       return BinaryOperator::CreateAnd(A, Op1);
4168     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4169         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4170       return BinaryOperator::CreateAnd(A, Op0);
4171   }
4172   
4173   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4174     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4175     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4176       return R;
4177
4178     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4179       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4180         return Res;
4181   }
4182
4183   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4184   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4185     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4186       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4187         const Type *SrcTy = Op0C->getOperand(0)->getType();
4188         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4189             // Only do this if the casts both really cause code to be generated.
4190             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4191                               I.getType(), TD) &&
4192             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4193                               I.getType(), TD)) {
4194           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4195                                                          Op1C->getOperand(0),
4196                                                          I.getName());
4197           InsertNewInstBefore(NewOp, I);
4198           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4199         }
4200       }
4201     
4202   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4203   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4204     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4205       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4206           SI0->getOperand(1) == SI1->getOperand(1) &&
4207           (SI0->hasOneUse() || SI1->hasOneUse())) {
4208         Instruction *NewOp =
4209           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4210                                                         SI1->getOperand(0),
4211                                                         SI0->getName()), I);
4212         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4213                                       SI1->getOperand(1));
4214       }
4215   }
4216
4217   // If and'ing two fcmp, try combine them into one.
4218   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4219     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4220       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4221           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4222         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4223         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4224           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4225             // If either of the constants are nans, then the whole thing returns
4226             // false.
4227             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4228               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4229             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4230                                 LHS->getOperand(0), RHS->getOperand(0));
4231           }
4232       } else {
4233         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4234         FCmpInst::Predicate Op0CC, Op1CC;
4235         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4236                   m_Value(Op0RHS)), *Context) &&
4237             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4238                   m_Value(Op1RHS)), *Context)) {
4239           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4240             // Swap RHS operands to match LHS.
4241             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4242             std::swap(Op1LHS, Op1RHS);
4243           }
4244           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4245             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4246             if (Op0CC == Op1CC)
4247               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4248                                   Op0LHS, Op0RHS);
4249             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4250                      Op1CC == FCmpInst::FCMP_FALSE)
4251               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4252             else if (Op0CC == FCmpInst::FCMP_TRUE)
4253               return ReplaceInstUsesWith(I, Op1);
4254             else if (Op1CC == FCmpInst::FCMP_TRUE)
4255               return ReplaceInstUsesWith(I, Op0);
4256             bool Op0Ordered;
4257             bool Op1Ordered;
4258             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4259             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4260             if (Op1Pred == 0) {
4261               std::swap(Op0, Op1);
4262               std::swap(Op0Pred, Op1Pred);
4263               std::swap(Op0Ordered, Op1Ordered);
4264             }
4265             if (Op0Pred == 0) {
4266               // uno && ueq -> uno && (uno || eq) -> ueq
4267               // ord && olt -> ord && (ord && lt) -> olt
4268               if (Op0Ordered == Op1Ordered)
4269                 return ReplaceInstUsesWith(I, Op1);
4270               // uno && oeq -> uno && (ord && eq) -> false
4271               // uno && ord -> false
4272               if (!Op0Ordered)
4273                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4274               // ord && ueq -> ord && (uno || eq) -> oeq
4275               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4276                                                     Op0LHS, Op0RHS, Context));
4277             }
4278           }
4279         }
4280       }
4281     }
4282   }
4283
4284   return Changed ? &I : 0;
4285 }
4286
4287 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4288 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4289 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4290 /// the expression came from the corresponding "byte swapped" byte in some other
4291 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4292 /// we know that the expression deposits the low byte of %X into the high byte
4293 /// of the bswap result and that all other bytes are zero.  This expression is
4294 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4295 /// match.
4296 ///
4297 /// This function returns true if the match was unsuccessful and false if so.
4298 /// On entry to the function the "OverallLeftShift" is a signed integer value
4299 /// indicating the number of bytes that the subexpression is later shifted.  For
4300 /// example, if the expression is later right shifted by 16 bits, the
4301 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4302 /// byte of ByteValues is actually being set.
4303 ///
4304 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4305 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4306 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4307 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4308 /// always in the local (OverallLeftShift) coordinate space.
4309 ///
4310 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4311                               SmallVector<Value*, 8> &ByteValues) {
4312   if (Instruction *I = dyn_cast<Instruction>(V)) {
4313     // If this is an or instruction, it may be an inner node of the bswap.
4314     if (I->getOpcode() == Instruction::Or) {
4315       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4316                                ByteValues) ||
4317              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4318                                ByteValues);
4319     }
4320   
4321     // If this is a logical shift by a constant multiple of 8, recurse with
4322     // OverallLeftShift and ByteMask adjusted.
4323     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4324       unsigned ShAmt = 
4325         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4326       // Ensure the shift amount is defined and of a byte value.
4327       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4328         return true;
4329
4330       unsigned ByteShift = ShAmt >> 3;
4331       if (I->getOpcode() == Instruction::Shl) {
4332         // X << 2 -> collect(X, +2)
4333         OverallLeftShift += ByteShift;
4334         ByteMask >>= ByteShift;
4335       } else {
4336         // X >>u 2 -> collect(X, -2)
4337         OverallLeftShift -= ByteShift;
4338         ByteMask <<= ByteShift;
4339         ByteMask &= (~0U >> (32-ByteValues.size()));
4340       }
4341
4342       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4343       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4344
4345       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4346                                ByteValues);
4347     }
4348
4349     // If this is a logical 'and' with a mask that clears bytes, clear the
4350     // corresponding bytes in ByteMask.
4351     if (I->getOpcode() == Instruction::And &&
4352         isa<ConstantInt>(I->getOperand(1))) {
4353       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4354       unsigned NumBytes = ByteValues.size();
4355       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4356       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4357       
4358       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4359         // If this byte is masked out by a later operation, we don't care what
4360         // the and mask is.
4361         if ((ByteMask & (1 << i)) == 0)
4362           continue;
4363         
4364         // If the AndMask is all zeros for this byte, clear the bit.
4365         APInt MaskB = AndMask & Byte;
4366         if (MaskB == 0) {
4367           ByteMask &= ~(1U << i);
4368           continue;
4369         }
4370         
4371         // If the AndMask is not all ones for this byte, it's not a bytezap.
4372         if (MaskB != Byte)
4373           return true;
4374
4375         // Otherwise, this byte is kept.
4376       }
4377
4378       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4379                                ByteValues);
4380     }
4381   }
4382   
4383   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4384   // the input value to the bswap.  Some observations: 1) if more than one byte
4385   // is demanded from this input, then it could not be successfully assembled
4386   // into a byteswap.  At least one of the two bytes would not be aligned with
4387   // their ultimate destination.
4388   if (!isPowerOf2_32(ByteMask)) return true;
4389   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4390   
4391   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4392   // is demanded, it needs to go into byte 0 of the result.  This means that the
4393   // byte needs to be shifted until it lands in the right byte bucket.  The
4394   // shift amount depends on the position: if the byte is coming from the high
4395   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4396   // low part, it must be shifted left.
4397   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4398   if (InputByteNo < ByteValues.size()/2) {
4399     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4400       return true;
4401   } else {
4402     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4403       return true;
4404   }
4405   
4406   // If the destination byte value is already defined, the values are or'd
4407   // together, which isn't a bswap (unless it's an or of the same bits).
4408   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4409     return true;
4410   ByteValues[DestByteNo] = V;
4411   return false;
4412 }
4413
4414 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4415 /// If so, insert the new bswap intrinsic and return it.
4416 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4417   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4418   if (!ITy || ITy->getBitWidth() % 16 || 
4419       // ByteMask only allows up to 32-byte values.
4420       ITy->getBitWidth() > 32*8) 
4421     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4422   
4423   /// ByteValues - For each byte of the result, we keep track of which value
4424   /// defines each byte.
4425   SmallVector<Value*, 8> ByteValues;
4426   ByteValues.resize(ITy->getBitWidth()/8);
4427     
4428   // Try to find all the pieces corresponding to the bswap.
4429   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4430   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4431     return 0;
4432   
4433   // Check to see if all of the bytes come from the same value.
4434   Value *V = ByteValues[0];
4435   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4436   
4437   // Check to make sure that all of the bytes come from the same value.
4438   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4439     if (ByteValues[i] != V)
4440       return 0;
4441   const Type *Tys[] = { ITy };
4442   Module *M = I.getParent()->getParent()->getParent();
4443   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4444   return CallInst::Create(F, V);
4445 }
4446
4447 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4448 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4449 /// we can simplify this expression to "cond ? C : D or B".
4450 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4451                                          Value *C, Value *D,
4452                                          LLVMContext *Context) {
4453   // If A is not a select of -1/0, this cannot match.
4454   Value *Cond = 0;
4455   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4456     return 0;
4457
4458   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4459   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4460     return SelectInst::Create(Cond, C, B);
4461   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4462     return SelectInst::Create(Cond, C, B);
4463   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4464   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4465     return SelectInst::Create(Cond, C, D);
4466   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4467     return SelectInst::Create(Cond, C, D);
4468   return 0;
4469 }
4470
4471 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4472 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4473                                          ICmpInst *LHS, ICmpInst *RHS) {
4474   Value *Val, *Val2;
4475   ConstantInt *LHSCst, *RHSCst;
4476   ICmpInst::Predicate LHSCC, RHSCC;
4477   
4478   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4479   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4480              m_ConstantInt(LHSCst)), *Context) ||
4481       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4482              m_ConstantInt(RHSCst)), *Context))
4483     return 0;
4484   
4485   // From here on, we only handle:
4486   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4487   if (Val != Val2) return 0;
4488   
4489   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4490   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4491       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4492       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4493       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4494     return 0;
4495   
4496   // We can't fold (ugt x, C) | (sgt x, C2).
4497   if (!PredicatesFoldable(LHSCC, RHSCC))
4498     return 0;
4499   
4500   // Ensure that the larger constant is on the RHS.
4501   bool ShouldSwap;
4502   if (ICmpInst::isSignedPredicate(LHSCC) ||
4503       (ICmpInst::isEquality(LHSCC) && 
4504        ICmpInst::isSignedPredicate(RHSCC)))
4505     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4506   else
4507     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4508   
4509   if (ShouldSwap) {
4510     std::swap(LHS, RHS);
4511     std::swap(LHSCst, RHSCst);
4512     std::swap(LHSCC, RHSCC);
4513   }
4514   
4515   // At this point, we know we have have two icmp instructions
4516   // comparing a value against two constants and or'ing the result
4517   // together.  Because of the above check, we know that we only have
4518   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4519   // FoldICmpLogical check above), that the two constants are not
4520   // equal.
4521   assert(LHSCst != RHSCst && "Compares not folded above?");
4522
4523   switch (LHSCC) {
4524   default: llvm_unreachable("Unknown integer condition code!");
4525   case ICmpInst::ICMP_EQ:
4526     switch (RHSCC) {
4527     default: llvm_unreachable("Unknown integer condition code!");
4528     case ICmpInst::ICMP_EQ:
4529       if (LHSCst == SubOne(RHSCst, Context)) {
4530         // (X == 13 | X == 14) -> X-13 <u 2
4531         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4532         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4533                                                      Val->getName()+".off");
4534         InsertNewInstBefore(Add, I);
4535         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4536         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4537       }
4538       break;                         // (X == 13 | X == 15) -> no change
4539     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4540     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4541       break;
4542     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4543     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4544     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4545       return ReplaceInstUsesWith(I, RHS);
4546     }
4547     break;
4548   case ICmpInst::ICMP_NE:
4549     switch (RHSCC) {
4550     default: llvm_unreachable("Unknown integer condition code!");
4551     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4552     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4553     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4554       return ReplaceInstUsesWith(I, LHS);
4555     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4556     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4557     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4558       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4559     }
4560     break;
4561   case ICmpInst::ICMP_ULT:
4562     switch (RHSCC) {
4563     default: llvm_unreachable("Unknown integer condition code!");
4564     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4565       break;
4566     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4567       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4568       // this can cause overflow.
4569       if (RHSCst->isMaxValue(false))
4570         return ReplaceInstUsesWith(I, LHS);
4571       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4572                              false, false, I);
4573     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4574       break;
4575     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4576     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4577       return ReplaceInstUsesWith(I, RHS);
4578     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4579       break;
4580     }
4581     break;
4582   case ICmpInst::ICMP_SLT:
4583     switch (RHSCC) {
4584     default: llvm_unreachable("Unknown integer condition code!");
4585     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4586       break;
4587     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4588       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4589       // this can cause overflow.
4590       if (RHSCst->isMaxValue(true))
4591         return ReplaceInstUsesWith(I, LHS);
4592       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4593                              true, false, I);
4594     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4595       break;
4596     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4597     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4598       return ReplaceInstUsesWith(I, RHS);
4599     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4600       break;
4601     }
4602     break;
4603   case ICmpInst::ICMP_UGT:
4604     switch (RHSCC) {
4605     default: llvm_unreachable("Unknown integer condition code!");
4606     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4607     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4608       return ReplaceInstUsesWith(I, LHS);
4609     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4610       break;
4611     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4612     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4613       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4614     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4615       break;
4616     }
4617     break;
4618   case ICmpInst::ICMP_SGT:
4619     switch (RHSCC) {
4620     default: llvm_unreachable("Unknown integer condition code!");
4621     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4622     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4623       return ReplaceInstUsesWith(I, LHS);
4624     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4625       break;
4626     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4627     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4628       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4629     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4630       break;
4631     }
4632     break;
4633   }
4634   return 0;
4635 }
4636
4637 /// FoldOrWithConstants - This helper function folds:
4638 ///
4639 ///     ((A | B) & C1) | (B & C2)
4640 ///
4641 /// into:
4642 /// 
4643 ///     (A & C1) | B
4644 ///
4645 /// when the XOR of the two constants is "all ones" (-1).
4646 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4647                                                Value *A, Value *B, Value *C) {
4648   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4649   if (!CI1) return 0;
4650
4651   Value *V1 = 0;
4652   ConstantInt *CI2 = 0;
4653   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4654
4655   APInt Xor = CI1->getValue() ^ CI2->getValue();
4656   if (!Xor.isAllOnesValue()) return 0;
4657
4658   if (V1 == A || V1 == B) {
4659     Instruction *NewOp =
4660       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4661     return BinaryOperator::CreateOr(NewOp, V1);
4662   }
4663
4664   return 0;
4665 }
4666
4667 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4668   bool Changed = SimplifyCommutative(I);
4669   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4670
4671   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4672     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4673
4674   // or X, X = X
4675   if (Op0 == Op1)
4676     return ReplaceInstUsesWith(I, Op0);
4677
4678   // See if we can simplify any instructions used by the instruction whose sole 
4679   // purpose is to compute bits we don't care about.
4680   if (SimplifyDemandedInstructionBits(I))
4681     return &I;
4682   if (isa<VectorType>(I.getType())) {
4683     if (isa<ConstantAggregateZero>(Op1)) {
4684       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4685     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4686       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4687         return ReplaceInstUsesWith(I, I.getOperand(1));
4688     }
4689   }
4690
4691   // or X, -1 == -1
4692   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4693     ConstantInt *C1 = 0; Value *X = 0;
4694     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4695     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4696         isOnlyUse(Op0)) {
4697       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4698       InsertNewInstBefore(Or, I);
4699       Or->takeName(Op0);
4700       return BinaryOperator::CreateAnd(Or, 
4701                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4702     }
4703
4704     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4705     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4706         isOnlyUse(Op0)) {
4707       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4708       InsertNewInstBefore(Or, I);
4709       Or->takeName(Op0);
4710       return BinaryOperator::CreateXor(Or,
4711                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4712     }
4713
4714     // Try to fold constant and into select arguments.
4715     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4716       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4717         return R;
4718     if (isa<PHINode>(Op0))
4719       if (Instruction *NV = FoldOpIntoPhi(I))
4720         return NV;
4721   }
4722
4723   Value *A = 0, *B = 0;
4724   ConstantInt *C1 = 0, *C2 = 0;
4725
4726   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4727     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4728       return ReplaceInstUsesWith(I, Op1);
4729   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4730     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4731       return ReplaceInstUsesWith(I, Op0);
4732
4733   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4734   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4735   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4736       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4737       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4738        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4739     if (Instruction *BSwap = MatchBSwap(I))
4740       return BSwap;
4741   }
4742   
4743   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4744   if (Op0->hasOneUse() &&
4745       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4746       MaskedValueIsZero(Op1, C1->getValue())) {
4747     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4748     InsertNewInstBefore(NOr, I);
4749     NOr->takeName(Op0);
4750     return BinaryOperator::CreateXor(NOr, C1);
4751   }
4752
4753   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4754   if (Op1->hasOneUse() &&
4755       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4756       MaskedValueIsZero(Op0, C1->getValue())) {
4757     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4758     InsertNewInstBefore(NOr, I);
4759     NOr->takeName(Op0);
4760     return BinaryOperator::CreateXor(NOr, C1);
4761   }
4762
4763   // (A & C)|(B & D)
4764   Value *C = 0, *D = 0;
4765   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4766       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4767     Value *V1 = 0, *V2 = 0, *V3 = 0;
4768     C1 = dyn_cast<ConstantInt>(C);
4769     C2 = dyn_cast<ConstantInt>(D);
4770     if (C1 && C2) {  // (A & C1)|(B & C2)
4771       // If we have: ((V + N) & C1) | (V & C2)
4772       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4773       // replace with V+N.
4774       if (C1->getValue() == ~C2->getValue()) {
4775         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4776             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4777           // Add commutes, try both ways.
4778           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4779             return ReplaceInstUsesWith(I, A);
4780           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4781             return ReplaceInstUsesWith(I, A);
4782         }
4783         // Or commutes, try both ways.
4784         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4785             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4786           // Add commutes, try both ways.
4787           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4788             return ReplaceInstUsesWith(I, B);
4789           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4790             return ReplaceInstUsesWith(I, B);
4791         }
4792       }
4793       V1 = 0; V2 = 0; V3 = 0;
4794     }
4795     
4796     // Check to see if we have any common things being and'ed.  If so, find the
4797     // terms for V1 & (V2|V3).
4798     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4799       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4800         V1 = A, V2 = C, V3 = D;
4801       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4802         V1 = A, V2 = B, V3 = C;
4803       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4804         V1 = C, V2 = A, V3 = D;
4805       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4806         V1 = C, V2 = A, V3 = B;
4807       
4808       if (V1) {
4809         Value *Or =
4810           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4811         return BinaryOperator::CreateAnd(V1, Or);
4812       }
4813     }
4814
4815     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4816     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4817       return Match;
4818     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4819       return Match;
4820     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4821       return Match;
4822     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4823       return Match;
4824
4825     // ((A&~B)|(~A&B)) -> A^B
4826     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4827          match(B, m_Not(m_Specific(A)), *Context)))
4828       return BinaryOperator::CreateXor(A, D);
4829     // ((~B&A)|(~A&B)) -> A^B
4830     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4831          match(B, m_Not(m_Specific(C)), *Context)))
4832       return BinaryOperator::CreateXor(C, D);
4833     // ((A&~B)|(B&~A)) -> A^B
4834     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4835          match(D, m_Not(m_Specific(A)), *Context)))
4836       return BinaryOperator::CreateXor(A, B);
4837     // ((~B&A)|(B&~A)) -> A^B
4838     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4839          match(D, m_Not(m_Specific(C)), *Context)))
4840       return BinaryOperator::CreateXor(C, B);
4841   }
4842   
4843   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4844   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4845     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4846       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4847           SI0->getOperand(1) == SI1->getOperand(1) &&
4848           (SI0->hasOneUse() || SI1->hasOneUse())) {
4849         Instruction *NewOp =
4850         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4851                                                      SI1->getOperand(0),
4852                                                      SI0->getName()), I);
4853         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4854                                       SI1->getOperand(1));
4855       }
4856   }
4857
4858   // ((A|B)&1)|(B&-2) -> (A&1) | B
4859   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4860       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4861     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4862     if (Ret) return Ret;
4863   }
4864   // (B&-2)|((A|B)&1) -> (A&1) | B
4865   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4866       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4867     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4868     if (Ret) return Ret;
4869   }
4870
4871   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4872     if (A == Op1)   // ~A | A == -1
4873       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4874   } else {
4875     A = 0;
4876   }
4877   // Note, A is still live here!
4878   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4879     if (Op0 == B)
4880       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4881
4882     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4883     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4884       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4885                                               I.getName()+".demorgan"), I);
4886       return BinaryOperator::CreateNot(*Context, And);
4887     }
4888   }
4889
4890   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4891   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4892     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4893       return R;
4894
4895     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4896       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4897         return Res;
4898   }
4899     
4900   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4901   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4902     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4903       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4904         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4905             !isa<ICmpInst>(Op1C->getOperand(0))) {
4906           const Type *SrcTy = Op0C->getOperand(0)->getType();
4907           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4908               // Only do this if the casts both really cause code to be
4909               // generated.
4910               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4911                                 I.getType(), TD) &&
4912               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4913                                 I.getType(), TD)) {
4914             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4915                                                           Op1C->getOperand(0),
4916                                                           I.getName());
4917             InsertNewInstBefore(NewOp, I);
4918             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4919           }
4920         }
4921       }
4922   }
4923   
4924     
4925   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4926   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4927     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4928       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4929           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4930           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4931         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4932           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4933             // If either of the constants are nans, then the whole thing returns
4934             // true.
4935             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4936               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4937             
4938             // Otherwise, no need to compare the two constants, compare the
4939             // rest.
4940             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4941                                 LHS->getOperand(0), RHS->getOperand(0));
4942           }
4943       } else {
4944         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4945         FCmpInst::Predicate Op0CC, Op1CC;
4946         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4947                   m_Value(Op0RHS)), *Context) &&
4948             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4949                   m_Value(Op1RHS)), *Context)) {
4950           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4951             // Swap RHS operands to match LHS.
4952             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4953             std::swap(Op1LHS, Op1RHS);
4954           }
4955           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4956             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4957             if (Op0CC == Op1CC)
4958               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4959                                   Op0LHS, Op0RHS);
4960             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4961                      Op1CC == FCmpInst::FCMP_TRUE)
4962               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4963             else if (Op0CC == FCmpInst::FCMP_FALSE)
4964               return ReplaceInstUsesWith(I, Op1);
4965             else if (Op1CC == FCmpInst::FCMP_FALSE)
4966               return ReplaceInstUsesWith(I, Op0);
4967             bool Op0Ordered;
4968             bool Op1Ordered;
4969             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4970             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4971             if (Op0Ordered == Op1Ordered) {
4972               // If both are ordered or unordered, return a new fcmp with
4973               // or'ed predicates.
4974               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4975                                        Op0LHS, Op0RHS, Context);
4976               if (Instruction *I = dyn_cast<Instruction>(RV))
4977                 return I;
4978               // Otherwise, it's a constant boolean value...
4979               return ReplaceInstUsesWith(I, RV);
4980             }
4981           }
4982         }
4983       }
4984     }
4985   }
4986
4987   return Changed ? &I : 0;
4988 }
4989
4990 namespace {
4991
4992 // XorSelf - Implements: X ^ X --> 0
4993 struct XorSelf {
4994   Value *RHS;
4995   XorSelf(Value *rhs) : RHS(rhs) {}
4996   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4997   Instruction *apply(BinaryOperator &Xor) const {
4998     return &Xor;
4999   }
5000 };
5001
5002 }
5003
5004 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5005   bool Changed = SimplifyCommutative(I);
5006   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5007
5008   if (isa<UndefValue>(Op1)) {
5009     if (isa<UndefValue>(Op0))
5010       // Handle undef ^ undef -> 0 special case. This is a common
5011       // idiom (misuse).
5012       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5013     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5014   }
5015
5016   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5017   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5018     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5019     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5020   }
5021   
5022   // See if we can simplify any instructions used by the instruction whose sole 
5023   // purpose is to compute bits we don't care about.
5024   if (SimplifyDemandedInstructionBits(I))
5025     return &I;
5026   if (isa<VectorType>(I.getType()))
5027     if (isa<ConstantAggregateZero>(Op1))
5028       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5029
5030   // Is this a ~ operation?
5031   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5032     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5033     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5034     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5035       if (Op0I->getOpcode() == Instruction::And || 
5036           Op0I->getOpcode() == Instruction::Or) {
5037         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5038         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5039           Instruction *NotY =
5040             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5041                                       Op0I->getOperand(1)->getName()+".not");
5042           InsertNewInstBefore(NotY, I);
5043           if (Op0I->getOpcode() == Instruction::And)
5044             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5045           else
5046             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5047         }
5048       }
5049     }
5050   }
5051   
5052   
5053   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5054     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5055       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5056       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5057         return new ICmpInst(*Context, ICI->getInversePredicate(),
5058                             ICI->getOperand(0), ICI->getOperand(1));
5059
5060       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5061         return new FCmpInst(*Context, FCI->getInversePredicate(),
5062                             FCI->getOperand(0), FCI->getOperand(1));
5063     }
5064
5065     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5066     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5067       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5068         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5069           Instruction::CastOps Opcode = Op0C->getOpcode();
5070           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5071             if (RHS == Context->getConstantExprCast(Opcode, 
5072                                              Context->getConstantIntTrue(),
5073                                              Op0C->getDestTy())) {
5074               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5075                                      *Context,
5076                                      CI->getOpcode(), CI->getInversePredicate(),
5077                                      CI->getOperand(0), CI->getOperand(1)), I);
5078               NewCI->takeName(CI);
5079               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5080             }
5081           }
5082         }
5083       }
5084     }
5085
5086     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5087       // ~(c-X) == X-c-1 == X+(-c-1)
5088       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5089         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5090           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5091           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5092                                       Context->getConstantInt(I.getType(), 1));
5093           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5094         }
5095           
5096       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5097         if (Op0I->getOpcode() == Instruction::Add) {
5098           // ~(X-c) --> (-c-1)-X
5099           if (RHS->isAllOnesValue()) {
5100             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5101             return BinaryOperator::CreateSub(
5102                            Context->getConstantExprSub(NegOp0CI,
5103                                       Context->getConstantInt(I.getType(), 1)),
5104                                       Op0I->getOperand(0));
5105           } else if (RHS->getValue().isSignBit()) {
5106             // (X + C) ^ signbit -> (X + C + signbit)
5107             Constant *C =
5108                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5109             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5110
5111           }
5112         } else if (Op0I->getOpcode() == Instruction::Or) {
5113           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5114           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5115             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5116             // Anything in both C1 and C2 is known to be zero, remove it from
5117             // NewRHS.
5118             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5119             NewRHS = Context->getConstantExprAnd(NewRHS, 
5120                                        Context->getConstantExprNot(CommonBits));
5121             AddToWorkList(Op0I);
5122             I.setOperand(0, Op0I->getOperand(0));
5123             I.setOperand(1, NewRHS);
5124             return &I;
5125           }
5126         }
5127       }
5128     }
5129
5130     // Try to fold constant and into select arguments.
5131     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5132       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5133         return R;
5134     if (isa<PHINode>(Op0))
5135       if (Instruction *NV = FoldOpIntoPhi(I))
5136         return NV;
5137   }
5138
5139   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5140     if (X == Op1)
5141       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5142
5143   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5144     if (X == Op0)
5145       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5146
5147   
5148   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5149   if (Op1I) {
5150     Value *A, *B;
5151     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5152       if (A == Op0) {              // B^(B|A) == (A|B)^B
5153         Op1I->swapOperands();
5154         I.swapOperands();
5155         std::swap(Op0, Op1);
5156       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5157         I.swapOperands();     // Simplified below.
5158         std::swap(Op0, Op1);
5159       }
5160     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5161       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5162     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5163       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5164     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5165                Op1I->hasOneUse()){
5166       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5167         Op1I->swapOperands();
5168         std::swap(A, B);
5169       }
5170       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5171         I.swapOperands();     // Simplified below.
5172         std::swap(Op0, Op1);
5173       }
5174     }
5175   }
5176   
5177   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5178   if (Op0I) {
5179     Value *A, *B;
5180     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5181         Op0I->hasOneUse()) {
5182       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5183         std::swap(A, B);
5184       if (B == Op1) {                                // (A|B)^B == A & ~B
5185         Instruction *NotB =
5186           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5187                                                         Op1, "tmp"), I);
5188         return BinaryOperator::CreateAnd(A, NotB);
5189       }
5190     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5191       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5192     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5193       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5194     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5195                Op0I->hasOneUse()){
5196       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5197         std::swap(A, B);
5198       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5199           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5200         Instruction *N =
5201           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5202         return BinaryOperator::CreateAnd(N, Op1);
5203       }
5204     }
5205   }
5206   
5207   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5208   if (Op0I && Op1I && Op0I->isShift() && 
5209       Op0I->getOpcode() == Op1I->getOpcode() && 
5210       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5211       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5212     Instruction *NewOp =
5213       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5214                                                     Op1I->getOperand(0),
5215                                                     Op0I->getName()), I);
5216     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5217                                   Op1I->getOperand(1));
5218   }
5219     
5220   if (Op0I && Op1I) {
5221     Value *A, *B, *C, *D;
5222     // (A & B)^(A | B) -> A ^ B
5223     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5224         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5225       if ((A == C && B == D) || (A == D && B == C)) 
5226         return BinaryOperator::CreateXor(A, B);
5227     }
5228     // (A | B)^(A & B) -> A ^ B
5229     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5230         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5231       if ((A == C && B == D) || (A == D && B == C)) 
5232         return BinaryOperator::CreateXor(A, B);
5233     }
5234     
5235     // (A & B)^(C & D)
5236     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5237         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5238         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5239       // (X & Y)^(X & Y) -> (Y^Z) & X
5240       Value *X = 0, *Y = 0, *Z = 0;
5241       if (A == C)
5242         X = A, Y = B, Z = D;
5243       else if (A == D)
5244         X = A, Y = B, Z = C;
5245       else if (B == C)
5246         X = B, Y = A, Z = D;
5247       else if (B == D)
5248         X = B, Y = A, Z = C;
5249       
5250       if (X) {
5251         Instruction *NewOp =
5252         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5253         return BinaryOperator::CreateAnd(NewOp, X);
5254       }
5255     }
5256   }
5257     
5258   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5259   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5260     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5261       return R;
5262
5263   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5264   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5265     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5266       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5267         const Type *SrcTy = Op0C->getOperand(0)->getType();
5268         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5269             // Only do this if the casts both really cause code to be generated.
5270             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5271                               I.getType(), TD) &&
5272             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5273                               I.getType(), TD)) {
5274           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5275                                                          Op1C->getOperand(0),
5276                                                          I.getName());
5277           InsertNewInstBefore(NewOp, I);
5278           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5279         }
5280       }
5281   }
5282
5283   return Changed ? &I : 0;
5284 }
5285
5286 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5287                                    LLVMContext *Context) {
5288   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5289 }
5290
5291 static bool HasAddOverflow(ConstantInt *Result,
5292                            ConstantInt *In1, ConstantInt *In2,
5293                            bool IsSigned) {
5294   if (IsSigned)
5295     if (In2->getValue().isNegative())
5296       return Result->getValue().sgt(In1->getValue());
5297     else
5298       return Result->getValue().slt(In1->getValue());
5299   else
5300     return Result->getValue().ult(In1->getValue());
5301 }
5302
5303 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5304 /// overflowed for this type.
5305 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5306                             Constant *In2, LLVMContext *Context,
5307                             bool IsSigned = false) {
5308   Result = Context->getConstantExprAdd(In1, In2);
5309
5310   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5311     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5312       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5313       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5314                          ExtractElement(In1, Idx, Context),
5315                          ExtractElement(In2, Idx, Context),
5316                          IsSigned))
5317         return true;
5318     }
5319     return false;
5320   }
5321
5322   return HasAddOverflow(cast<ConstantInt>(Result),
5323                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5324                         IsSigned);
5325 }
5326
5327 static bool HasSubOverflow(ConstantInt *Result,
5328                            ConstantInt *In1, ConstantInt *In2,
5329                            bool IsSigned) {
5330   if (IsSigned)
5331     if (In2->getValue().isNegative())
5332       return Result->getValue().slt(In1->getValue());
5333     else
5334       return Result->getValue().sgt(In1->getValue());
5335   else
5336     return Result->getValue().ugt(In1->getValue());
5337 }
5338
5339 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5340 /// overflowed for this type.
5341 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5342                             Constant *In2, LLVMContext *Context,
5343                             bool IsSigned = false) {
5344   Result = Context->getConstantExprSub(In1, In2);
5345
5346   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5347     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5348       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5349       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5350                          ExtractElement(In1, Idx, Context),
5351                          ExtractElement(In2, Idx, Context),
5352                          IsSigned))
5353         return true;
5354     }
5355     return false;
5356   }
5357
5358   return HasSubOverflow(cast<ConstantInt>(Result),
5359                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5360                         IsSigned);
5361 }
5362
5363 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5364 /// code necessary to compute the offset from the base pointer (without adding
5365 /// in the base pointer).  Return the result as a signed integer of intptr size.
5366 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5367   TargetData &TD = IC.getTargetData();
5368   gep_type_iterator GTI = gep_type_begin(GEP);
5369   const Type *IntPtrTy = TD.getIntPtrType();
5370   LLVMContext *Context = IC.getContext();
5371   Value *Result = Context->getNullValue(IntPtrTy);
5372
5373   // Build a mask for high order bits.
5374   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5375   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5376
5377   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5378        ++i, ++GTI) {
5379     Value *Op = *i;
5380     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5381     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5382       if (OpC->isZero()) continue;
5383       
5384       // Handle a struct index, which adds its field offset to the pointer.
5385       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5386         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5387         
5388         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5389           Result = 
5390              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5391         else
5392           Result = IC.InsertNewInstBefore(
5393                    BinaryOperator::CreateAdd(Result,
5394                                         Context->getConstantInt(IntPtrTy, Size),
5395                                              GEP->getName()+".offs"), I);
5396         continue;
5397       }
5398       
5399       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5400       Constant *OC =
5401               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5402       Scale = Context->getConstantExprMul(OC, Scale);
5403       if (Constant *RC = dyn_cast<Constant>(Result))
5404         Result = Context->getConstantExprAdd(RC, Scale);
5405       else {
5406         // Emit an add instruction.
5407         Result = IC.InsertNewInstBefore(
5408            BinaryOperator::CreateAdd(Result, Scale,
5409                                      GEP->getName()+".offs"), I);
5410       }
5411       continue;
5412     }
5413     // Convert to correct type.
5414     if (Op->getType() != IntPtrTy) {
5415       if (Constant *OpC = dyn_cast<Constant>(Op))
5416         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5417       else
5418         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5419                                                                 true,
5420                                                       Op->getName()+".c"), I);
5421     }
5422     if (Size != 1) {
5423       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5424       if (Constant *OpC = dyn_cast<Constant>(Op))
5425         Op = Context->getConstantExprMul(OpC, Scale);
5426       else    // We'll let instcombine(mul) convert this to a shl if possible.
5427         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5428                                                   GEP->getName()+".idx"), I);
5429     }
5430
5431     // Emit an add instruction.
5432     if (isa<Constant>(Op) && isa<Constant>(Result))
5433       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5434                                     cast<Constant>(Result));
5435     else
5436       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5437                                                   GEP->getName()+".offs"), I);
5438   }
5439   return Result;
5440 }
5441
5442
5443 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5444 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5445 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5446 /// be complex, and scales are involved.  The above expression would also be
5447 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5448 /// This later form is less amenable to optimization though, and we are allowed
5449 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5450 ///
5451 /// If we can't emit an optimized form for this expression, this returns null.
5452 /// 
5453 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5454                                           InstCombiner &IC) {
5455   TargetData &TD = IC.getTargetData();
5456   gep_type_iterator GTI = gep_type_begin(GEP);
5457
5458   // Check to see if this gep only has a single variable index.  If so, and if
5459   // any constant indices are a multiple of its scale, then we can compute this
5460   // in terms of the scale of the variable index.  For example, if the GEP
5461   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5462   // because the expression will cross zero at the same point.
5463   unsigned i, e = GEP->getNumOperands();
5464   int64_t Offset = 0;
5465   for (i = 1; i != e; ++i, ++GTI) {
5466     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5467       // Compute the aggregate offset of constant indices.
5468       if (CI->isZero()) continue;
5469
5470       // Handle a struct index, which adds its field offset to the pointer.
5471       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5472         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5473       } else {
5474         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5475         Offset += Size*CI->getSExtValue();
5476       }
5477     } else {
5478       // Found our variable index.
5479       break;
5480     }
5481   }
5482   
5483   // If there are no variable indices, we must have a constant offset, just
5484   // evaluate it the general way.
5485   if (i == e) return 0;
5486   
5487   Value *VariableIdx = GEP->getOperand(i);
5488   // Determine the scale factor of the variable element.  For example, this is
5489   // 4 if the variable index is into an array of i32.
5490   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5491   
5492   // Verify that there are no other variable indices.  If so, emit the hard way.
5493   for (++i, ++GTI; i != e; ++i, ++GTI) {
5494     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5495     if (!CI) return 0;
5496    
5497     // Compute the aggregate offset of constant indices.
5498     if (CI->isZero()) continue;
5499     
5500     // Handle a struct index, which adds its field offset to the pointer.
5501     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5502       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5503     } else {
5504       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5505       Offset += Size*CI->getSExtValue();
5506     }
5507   }
5508   
5509   // Okay, we know we have a single variable index, which must be a
5510   // pointer/array/vector index.  If there is no offset, life is simple, return
5511   // the index.
5512   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5513   if (Offset == 0) {
5514     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5515     // we don't need to bother extending: the extension won't affect where the
5516     // computation crosses zero.
5517     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5518       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5519                                   VariableIdx->getNameStart(), &I);
5520     return VariableIdx;
5521   }
5522   
5523   // Otherwise, there is an index.  The computation we will do will be modulo
5524   // the pointer size, so get it.
5525   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5526   
5527   Offset &= PtrSizeMask;
5528   VariableScale &= PtrSizeMask;
5529
5530   // To do this transformation, any constant index must be a multiple of the
5531   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5532   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5533   // multiple of the variable scale.
5534   int64_t NewOffs = Offset / (int64_t)VariableScale;
5535   if (Offset != NewOffs*(int64_t)VariableScale)
5536     return 0;
5537
5538   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5539   const Type *IntPtrTy = TD.getIntPtrType();
5540   if (VariableIdx->getType() != IntPtrTy)
5541     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5542                                               true /*SExt*/, 
5543                                               VariableIdx->getNameStart(), &I);
5544   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5545   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5546 }
5547
5548
5549 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5550 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5551 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5552                                        ICmpInst::Predicate Cond,
5553                                        Instruction &I) {
5554   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5555
5556   // Look through bitcasts.
5557   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5558     RHS = BCI->getOperand(0);
5559
5560   Value *PtrBase = GEPLHS->getOperand(0);
5561   if (PtrBase == RHS) {
5562     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5563     // This transformation (ignoring the base and scales) is valid because we
5564     // know pointers can't overflow.  See if we can output an optimized form.
5565     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5566     
5567     // If not, synthesize the offset the hard way.
5568     if (Offset == 0)
5569       Offset = EmitGEPOffset(GEPLHS, I, *this);
5570     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5571                         Context->getNullValue(Offset->getType()));
5572   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5573     // If the base pointers are different, but the indices are the same, just
5574     // compare the base pointer.
5575     if (PtrBase != GEPRHS->getOperand(0)) {
5576       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5577       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5578                         GEPRHS->getOperand(0)->getType();
5579       if (IndicesTheSame)
5580         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5581           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5582             IndicesTheSame = false;
5583             break;
5584           }
5585
5586       // If all indices are the same, just compare the base pointers.
5587       if (IndicesTheSame)
5588         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5589                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5590
5591       // Otherwise, the base pointers are different and the indices are
5592       // different, bail out.
5593       return 0;
5594     }
5595
5596     // If one of the GEPs has all zero indices, recurse.
5597     bool AllZeros = true;
5598     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5599       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5600           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5601         AllZeros = false;
5602         break;
5603       }
5604     if (AllZeros)
5605       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5606                           ICmpInst::getSwappedPredicate(Cond), I);
5607
5608     // If the other GEP has all zero indices, recurse.
5609     AllZeros = true;
5610     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5611       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5612           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5613         AllZeros = false;
5614         break;
5615       }
5616     if (AllZeros)
5617       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5618
5619     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5620       // If the GEPs only differ by one index, compare it.
5621       unsigned NumDifferences = 0;  // Keep track of # differences.
5622       unsigned DiffOperand = 0;     // The operand that differs.
5623       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5624         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5625           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5626                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5627             // Irreconcilable differences.
5628             NumDifferences = 2;
5629             break;
5630           } else {
5631             if (NumDifferences++) break;
5632             DiffOperand = i;
5633           }
5634         }
5635
5636       if (NumDifferences == 0)   // SAME GEP?
5637         return ReplaceInstUsesWith(I, // No comparison is needed here.
5638                                    Context->getConstantInt(Type::Int1Ty,
5639                                              ICmpInst::isTrueWhenEqual(Cond)));
5640
5641       else if (NumDifferences == 1) {
5642         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5643         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5644         // Make sure we do a signed comparison here.
5645         return new ICmpInst(*Context,
5646                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5647       }
5648     }
5649
5650     // Only lower this if the icmp is the only user of the GEP or if we expect
5651     // the result to fold to a constant!
5652     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5653         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5654       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5655       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5656       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5657       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5658     }
5659   }
5660   return 0;
5661 }
5662
5663 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5664 ///
5665 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5666                                                 Instruction *LHSI,
5667                                                 Constant *RHSC) {
5668   if (!isa<ConstantFP>(RHSC)) return 0;
5669   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5670   
5671   // Get the width of the mantissa.  We don't want to hack on conversions that
5672   // might lose information from the integer, e.g. "i64 -> float"
5673   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5674   if (MantissaWidth == -1) return 0;  // Unknown.
5675   
5676   // Check to see that the input is converted from an integer type that is small
5677   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5678   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5679   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5680   
5681   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5682   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5683   if (LHSUnsigned)
5684     ++InputSize;
5685   
5686   // If the conversion would lose info, don't hack on this.
5687   if ((int)InputSize > MantissaWidth)
5688     return 0;
5689   
5690   // Otherwise, we can potentially simplify the comparison.  We know that it
5691   // will always come through as an integer value and we know the constant is
5692   // not a NAN (it would have been previously simplified).
5693   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5694   
5695   ICmpInst::Predicate Pred;
5696   switch (I.getPredicate()) {
5697   default: llvm_unreachable("Unexpected predicate!");
5698   case FCmpInst::FCMP_UEQ:
5699   case FCmpInst::FCMP_OEQ:
5700     Pred = ICmpInst::ICMP_EQ;
5701     break;
5702   case FCmpInst::FCMP_UGT:
5703   case FCmpInst::FCMP_OGT:
5704     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5705     break;
5706   case FCmpInst::FCMP_UGE:
5707   case FCmpInst::FCMP_OGE:
5708     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5709     break;
5710   case FCmpInst::FCMP_ULT:
5711   case FCmpInst::FCMP_OLT:
5712     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5713     break;
5714   case FCmpInst::FCMP_ULE:
5715   case FCmpInst::FCMP_OLE:
5716     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5717     break;
5718   case FCmpInst::FCMP_UNE:
5719   case FCmpInst::FCMP_ONE:
5720     Pred = ICmpInst::ICMP_NE;
5721     break;
5722   case FCmpInst::FCMP_ORD:
5723     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5724   case FCmpInst::FCMP_UNO:
5725     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5726   }
5727   
5728   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5729   
5730   // Now we know that the APFloat is a normal number, zero or inf.
5731   
5732   // See if the FP constant is too large for the integer.  For example,
5733   // comparing an i8 to 300.0.
5734   unsigned IntWidth = IntTy->getScalarSizeInBits();
5735   
5736   if (!LHSUnsigned) {
5737     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5738     // and large values.
5739     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5740     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5741                           APFloat::rmNearestTiesToEven);
5742     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5743       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5744           Pred == ICmpInst::ICMP_SLE)
5745         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5746       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5747     }
5748   } else {
5749     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5750     // +INF and large values.
5751     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5752     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5753                           APFloat::rmNearestTiesToEven);
5754     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5755       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5756           Pred == ICmpInst::ICMP_ULE)
5757         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5758       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5759     }
5760   }
5761   
5762   if (!LHSUnsigned) {
5763     // See if the RHS value is < SignedMin.
5764     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5765     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5766                           APFloat::rmNearestTiesToEven);
5767     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5768       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5769           Pred == ICmpInst::ICMP_SGE)
5770         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5771       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5772     }
5773   }
5774
5775   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5776   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5777   // casting the FP value to the integer value and back, checking for equality.
5778   // Don't do this for zero, because -0.0 is not fractional.
5779   Constant *RHSInt = LHSUnsigned
5780     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5781     : Context->getConstantExprFPToSI(RHSC, IntTy);
5782   if (!RHS.isZero()) {
5783     bool Equal = LHSUnsigned
5784       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5785       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5786     if (!Equal) {
5787       // If we had a comparison against a fractional value, we have to adjust
5788       // the compare predicate and sometimes the value.  RHSC is rounded towards
5789       // zero at this point.
5790       switch (Pred) {
5791       default: llvm_unreachable("Unexpected integer comparison!");
5792       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5793         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5794       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5795         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5796       case ICmpInst::ICMP_ULE:
5797         // (float)int <= 4.4   --> int <= 4
5798         // (float)int <= -4.4  --> false
5799         if (RHS.isNegative())
5800           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5801         break;
5802       case ICmpInst::ICMP_SLE:
5803         // (float)int <= 4.4   --> int <= 4
5804         // (float)int <= -4.4  --> int < -4
5805         if (RHS.isNegative())
5806           Pred = ICmpInst::ICMP_SLT;
5807         break;
5808       case ICmpInst::ICMP_ULT:
5809         // (float)int < -4.4   --> false
5810         // (float)int < 4.4    --> int <= 4
5811         if (RHS.isNegative())
5812           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5813         Pred = ICmpInst::ICMP_ULE;
5814         break;
5815       case ICmpInst::ICMP_SLT:
5816         // (float)int < -4.4   --> int < -4
5817         // (float)int < 4.4    --> int <= 4
5818         if (!RHS.isNegative())
5819           Pred = ICmpInst::ICMP_SLE;
5820         break;
5821       case ICmpInst::ICMP_UGT:
5822         // (float)int > 4.4    --> int > 4
5823         // (float)int > -4.4   --> true
5824         if (RHS.isNegative())
5825           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5826         break;
5827       case ICmpInst::ICMP_SGT:
5828         // (float)int > 4.4    --> int > 4
5829         // (float)int > -4.4   --> int >= -4
5830         if (RHS.isNegative())
5831           Pred = ICmpInst::ICMP_SGE;
5832         break;
5833       case ICmpInst::ICMP_UGE:
5834         // (float)int >= -4.4   --> true
5835         // (float)int >= 4.4    --> int > 4
5836         if (!RHS.isNegative())
5837           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5838         Pred = ICmpInst::ICMP_UGT;
5839         break;
5840       case ICmpInst::ICMP_SGE:
5841         // (float)int >= -4.4   --> int >= -4
5842         // (float)int >= 4.4    --> int > 4
5843         if (!RHS.isNegative())
5844           Pred = ICmpInst::ICMP_SGT;
5845         break;
5846       }
5847     }
5848   }
5849
5850   // Lower this FP comparison into an appropriate integer version of the
5851   // comparison.
5852   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5853 }
5854
5855 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5856   bool Changed = SimplifyCompare(I);
5857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5858
5859   // Fold trivial predicates.
5860   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5861     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5862   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5863     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5864   
5865   // Simplify 'fcmp pred X, X'
5866   if (Op0 == Op1) {
5867     switch (I.getPredicate()) {
5868     default: llvm_unreachable("Unknown predicate!");
5869     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5870     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5871     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5872       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5873     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5874     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5875     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5876       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5877       
5878     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5879     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5880     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5881     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5882       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5883       I.setPredicate(FCmpInst::FCMP_UNO);
5884       I.setOperand(1, Context->getNullValue(Op0->getType()));
5885       return &I;
5886       
5887     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5888     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5889     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5890     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5891       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5892       I.setPredicate(FCmpInst::FCMP_ORD);
5893       I.setOperand(1, Context->getNullValue(Op0->getType()));
5894       return &I;
5895     }
5896   }
5897     
5898   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5899     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5900
5901   // Handle fcmp with constant RHS
5902   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5903     // If the constant is a nan, see if we can fold the comparison based on it.
5904     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5905       if (CFP->getValueAPF().isNaN()) {
5906         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5907           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5908         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5909                "Comparison must be either ordered or unordered!");
5910         // True if unordered.
5911         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5912       }
5913     }
5914     
5915     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5916       switch (LHSI->getOpcode()) {
5917       case Instruction::PHI:
5918         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5919         // block.  If in the same block, we're encouraging jump threading.  If
5920         // not, we are just pessimizing the code by making an i1 phi.
5921         if (LHSI->getParent() == I.getParent())
5922           if (Instruction *NV = FoldOpIntoPhi(I))
5923             return NV;
5924         break;
5925       case Instruction::SIToFP:
5926       case Instruction::UIToFP:
5927         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5928           return NV;
5929         break;
5930       case Instruction::Select:
5931         // If either operand of the select is a constant, we can fold the
5932         // comparison into the select arms, which will cause one to be
5933         // constant folded and the select turned into a bitwise or.
5934         Value *Op1 = 0, *Op2 = 0;
5935         if (LHSI->hasOneUse()) {
5936           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5937             // Fold the known value into the constant operand.
5938             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5939             // Insert a new FCmp of the other select operand.
5940             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5941                                                       LHSI->getOperand(2), RHSC,
5942                                                       I.getName()), I);
5943           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5944             // Fold the known value into the constant operand.
5945             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5946             // Insert a new FCmp of the other select operand.
5947             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5948                                                       LHSI->getOperand(1), RHSC,
5949                                                       I.getName()), I);
5950           }
5951         }
5952
5953         if (Op1)
5954           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5955         break;
5956       }
5957   }
5958
5959   return Changed ? &I : 0;
5960 }
5961
5962 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5963   bool Changed = SimplifyCompare(I);
5964   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5965   const Type *Ty = Op0->getType();
5966
5967   // icmp X, X
5968   if (Op0 == Op1)
5969     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5970                                                    I.isTrueWhenEqual()));
5971
5972   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5973     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5974   
5975   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5976   // addresses never equal each other!  We already know that Op0 != Op1.
5977   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5978        isa<ConstantPointerNull>(Op0)) &&
5979       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5980        isa<ConstantPointerNull>(Op1)))
5981     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5982                                                    !I.isTrueWhenEqual()));
5983
5984   // icmp's with boolean values can always be turned into bitwise operations
5985   if (Ty == Type::Int1Ty) {
5986     switch (I.getPredicate()) {
5987     default: llvm_unreachable("Invalid icmp instruction!");
5988     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5989       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5990       InsertNewInstBefore(Xor, I);
5991       return BinaryOperator::CreateNot(*Context, Xor);
5992     }
5993     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5994       return BinaryOperator::CreateXor(Op0, Op1);
5995
5996     case ICmpInst::ICMP_UGT:
5997       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5998       // FALL THROUGH
5999     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6000       Instruction *Not = BinaryOperator::CreateNot(*Context,
6001                                                    Op0, I.getName()+"tmp");
6002       InsertNewInstBefore(Not, I);
6003       return BinaryOperator::CreateAnd(Not, Op1);
6004     }
6005     case ICmpInst::ICMP_SGT:
6006       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6007       // FALL THROUGH
6008     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6009       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6010                                                    Op1, I.getName()+"tmp");
6011       InsertNewInstBefore(Not, I);
6012       return BinaryOperator::CreateAnd(Not, Op0);
6013     }
6014     case ICmpInst::ICMP_UGE:
6015       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6016       // FALL THROUGH
6017     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6018       Instruction *Not = BinaryOperator::CreateNot(*Context,
6019                                                    Op0, I.getName()+"tmp");
6020       InsertNewInstBefore(Not, I);
6021       return BinaryOperator::CreateOr(Not, Op1);
6022     }
6023     case ICmpInst::ICMP_SGE:
6024       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6025       // FALL THROUGH
6026     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6027       Instruction *Not = BinaryOperator::CreateNot(*Context,
6028                                                    Op1, I.getName()+"tmp");
6029       InsertNewInstBefore(Not, I);
6030       return BinaryOperator::CreateOr(Not, Op0);
6031     }
6032     }
6033   }
6034
6035   unsigned BitWidth = 0;
6036   if (TD)
6037     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6038   else if (Ty->isIntOrIntVector())
6039     BitWidth = Ty->getScalarSizeInBits();
6040
6041   bool isSignBit = false;
6042
6043   // See if we are doing a comparison with a constant.
6044   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6045     Value *A = 0, *B = 0;
6046     
6047     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6048     if (I.isEquality() && CI->isNullValue() &&
6049         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6050       // (icmp cond A B) if cond is equality
6051       return new ICmpInst(*Context, I.getPredicate(), A, B);
6052     }
6053     
6054     // If we have an icmp le or icmp ge instruction, turn it into the
6055     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6056     // them being folded in the code below.
6057     switch (I.getPredicate()) {
6058     default: break;
6059     case ICmpInst::ICMP_ULE:
6060       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6061         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6062       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6063                           AddOne(CI, Context));
6064     case ICmpInst::ICMP_SLE:
6065       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6066         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6067       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6068                           AddOne(CI, Context));
6069     case ICmpInst::ICMP_UGE:
6070       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6071         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6072       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6073                           SubOne(CI, Context));
6074     case ICmpInst::ICMP_SGE:
6075       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6076         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6077       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6078                           SubOne(CI, Context));
6079     }
6080     
6081     // If this comparison is a normal comparison, it demands all
6082     // bits, if it is a sign bit comparison, it only demands the sign bit.
6083     bool UnusedBit;
6084     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6085   }
6086
6087   // See if we can fold the comparison based on range information we can get
6088   // by checking whether bits are known to be zero or one in the input.
6089   if (BitWidth != 0) {
6090     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6091     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6092
6093     if (SimplifyDemandedBits(I.getOperandUse(0),
6094                              isSignBit ? APInt::getSignBit(BitWidth)
6095                                        : APInt::getAllOnesValue(BitWidth),
6096                              Op0KnownZero, Op0KnownOne, 0))
6097       return &I;
6098     if (SimplifyDemandedBits(I.getOperandUse(1),
6099                              APInt::getAllOnesValue(BitWidth),
6100                              Op1KnownZero, Op1KnownOne, 0))
6101       return &I;
6102
6103     // Given the known and unknown bits, compute a range that the LHS could be
6104     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6105     // EQ and NE we use unsigned values.
6106     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6107     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6108     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6109       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6110                                              Op0Min, Op0Max);
6111       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6112                                              Op1Min, Op1Max);
6113     } else {
6114       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6115                                                Op0Min, Op0Max);
6116       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6117                                                Op1Min, Op1Max);
6118     }
6119
6120     // If Min and Max are known to be the same, then SimplifyDemandedBits
6121     // figured out that the LHS is a constant.  Just constant fold this now so
6122     // that code below can assume that Min != Max.
6123     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6124       return new ICmpInst(*Context, I.getPredicate(),
6125                           Context->getConstantInt(Op0Min), Op1);
6126     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6127       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6128                           Context->getConstantInt(Op1Min));
6129
6130     // Based on the range information we know about the LHS, see if we can
6131     // simplify this comparison.  For example, (x&4) < 8  is always true.
6132     switch (I.getPredicate()) {
6133     default: llvm_unreachable("Unknown icmp opcode!");
6134     case ICmpInst::ICMP_EQ:
6135       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6136         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6137       break;
6138     case ICmpInst::ICMP_NE:
6139       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6140         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6141       break;
6142     case ICmpInst::ICMP_ULT:
6143       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6144         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6145       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6146         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6147       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6148         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6149       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6151           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6152                               SubOne(CI, Context));
6153
6154         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6155         if (CI->isMinValue(true))
6156           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6157                            Context->getAllOnesValue(Op0->getType()));
6158       }
6159       break;
6160     case ICmpInst::ICMP_UGT:
6161       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6162         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6163       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6164         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6165
6166       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6167         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6168       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6170           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6171                               AddOne(CI, Context));
6172
6173         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6174         if (CI->isMaxValue(true))
6175           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6176                               Context->getNullValue(Op0->getType()));
6177       }
6178       break;
6179     case ICmpInst::ICMP_SLT:
6180       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6181         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6182       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6183         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6184       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6185         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6186       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6187         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6188           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6189                               SubOne(CI, Context));
6190       }
6191       break;
6192     case ICmpInst::ICMP_SGT:
6193       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6194         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6195       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6196         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6197
6198       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6199         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6200       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6201         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6202           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6203                               AddOne(CI, Context));
6204       }
6205       break;
6206     case ICmpInst::ICMP_SGE:
6207       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6208       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6209         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6210       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6211         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6212       break;
6213     case ICmpInst::ICMP_SLE:
6214       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6215       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6216         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6217       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6218         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6219       break;
6220     case ICmpInst::ICMP_UGE:
6221       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6222       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6223         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6224       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6225         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6226       break;
6227     case ICmpInst::ICMP_ULE:
6228       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6229       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6230         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6231       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6232         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6233       break;
6234     }
6235
6236     // Turn a signed comparison into an unsigned one if both operands
6237     // are known to have the same sign.
6238     if (I.isSignedPredicate() &&
6239         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6240          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6241       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6242   }
6243
6244   // Test if the ICmpInst instruction is used exclusively by a select as
6245   // part of a minimum or maximum operation. If so, refrain from doing
6246   // any other folding. This helps out other analyses which understand
6247   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6248   // and CodeGen. And in this case, at least one of the comparison
6249   // operands has at least one user besides the compare (the select),
6250   // which would often largely negate the benefit of folding anyway.
6251   if (I.hasOneUse())
6252     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6253       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6254           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6255         return 0;
6256
6257   // See if we are doing a comparison between a constant and an instruction that
6258   // can be folded into the comparison.
6259   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6260     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6261     // instruction, see if that instruction also has constants so that the 
6262     // instruction can be folded into the icmp 
6263     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6264       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6265         return Res;
6266   }
6267
6268   // Handle icmp with constant (but not simple integer constant) RHS
6269   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6270     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6271       switch (LHSI->getOpcode()) {
6272       case Instruction::GetElementPtr:
6273         if (RHSC->isNullValue()) {
6274           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6275           bool isAllZeros = true;
6276           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6277             if (!isa<Constant>(LHSI->getOperand(i)) ||
6278                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6279               isAllZeros = false;
6280               break;
6281             }
6282           if (isAllZeros)
6283             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6284                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6285         }
6286         break;
6287
6288       case Instruction::PHI:
6289         // Only fold icmp into the PHI if the phi and fcmp are in the same
6290         // block.  If in the same block, we're encouraging jump threading.  If
6291         // not, we are just pessimizing the code by making an i1 phi.
6292         if (LHSI->getParent() == I.getParent())
6293           if (Instruction *NV = FoldOpIntoPhi(I))
6294             return NV;
6295         break;
6296       case Instruction::Select: {
6297         // If either operand of the select is a constant, we can fold the
6298         // comparison into the select arms, which will cause one to be
6299         // constant folded and the select turned into a bitwise or.
6300         Value *Op1 = 0, *Op2 = 0;
6301         if (LHSI->hasOneUse()) {
6302           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6303             // Fold the known value into the constant operand.
6304             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6305             // Insert a new ICmp of the other select operand.
6306             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6307                                                    LHSI->getOperand(2), RHSC,
6308                                                    I.getName()), I);
6309           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6310             // Fold the known value into the constant operand.
6311             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6312             // Insert a new ICmp of the other select operand.
6313             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6314                                                    LHSI->getOperand(1), RHSC,
6315                                                    I.getName()), I);
6316           }
6317         }
6318
6319         if (Op1)
6320           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6321         break;
6322       }
6323       case Instruction::Malloc:
6324         // If we have (malloc != null), and if the malloc has a single use, we
6325         // can assume it is successful and remove the malloc.
6326         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6327           AddToWorkList(LHSI);
6328           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6329                                                          !I.isTrueWhenEqual()));
6330         }
6331         break;
6332       }
6333   }
6334
6335   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6336   if (User *GEP = dyn_castGetElementPtr(Op0))
6337     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6338       return NI;
6339   if (User *GEP = dyn_castGetElementPtr(Op1))
6340     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6341                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6342       return NI;
6343
6344   // Test to see if the operands of the icmp are casted versions of other
6345   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6346   // now.
6347   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6348     if (isa<PointerType>(Op0->getType()) && 
6349         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6350       // We keep moving the cast from the left operand over to the right
6351       // operand, where it can often be eliminated completely.
6352       Op0 = CI->getOperand(0);
6353
6354       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6355       // so eliminate it as well.
6356       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6357         Op1 = CI2->getOperand(0);
6358
6359       // If Op1 is a constant, we can fold the cast into the constant.
6360       if (Op0->getType() != Op1->getType()) {
6361         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6362           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6363         } else {
6364           // Otherwise, cast the RHS right before the icmp
6365           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6366         }
6367       }
6368       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6369     }
6370   }
6371   
6372   if (isa<CastInst>(Op0)) {
6373     // Handle the special case of: icmp (cast bool to X), <cst>
6374     // This comes up when you have code like
6375     //   int X = A < B;
6376     //   if (X) ...
6377     // For generality, we handle any zero-extension of any operand comparison
6378     // with a constant or another cast from the same type.
6379     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6380       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6381         return R;
6382   }
6383   
6384   // See if it's the same type of instruction on the left and right.
6385   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6386     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6387       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6388           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6389         switch (Op0I->getOpcode()) {
6390         default: break;
6391         case Instruction::Add:
6392         case Instruction::Sub:
6393         case Instruction::Xor:
6394           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6395             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6396                                 Op1I->getOperand(0));
6397           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6398           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6399             if (CI->getValue().isSignBit()) {
6400               ICmpInst::Predicate Pred = I.isSignedPredicate()
6401                                              ? I.getUnsignedPredicate()
6402                                              : I.getSignedPredicate();
6403               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6404                                   Op1I->getOperand(0));
6405             }
6406             
6407             if (CI->getValue().isMaxSignedValue()) {
6408               ICmpInst::Predicate Pred = I.isSignedPredicate()
6409                                              ? I.getUnsignedPredicate()
6410                                              : I.getSignedPredicate();
6411               Pred = I.getSwappedPredicate(Pred);
6412               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6413                                   Op1I->getOperand(0));
6414             }
6415           }
6416           break;
6417         case Instruction::Mul:
6418           if (!I.isEquality())
6419             break;
6420
6421           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6423             // Mask = -1 >> count-trailing-zeros(Cst).
6424             if (!CI->isZero() && !CI->isOne()) {
6425               const APInt &AP = CI->getValue();
6426               ConstantInt *Mask = Context->getConstantInt(
6427                                       APInt::getLowBitsSet(AP.getBitWidth(),
6428                                                            AP.getBitWidth() -
6429                                                       AP.countTrailingZeros()));
6430               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6431                                                             Mask);
6432               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6433                                                             Mask);
6434               InsertNewInstBefore(And1, I);
6435               InsertNewInstBefore(And2, I);
6436               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6437             }
6438           }
6439           break;
6440         }
6441       }
6442     }
6443   }
6444   
6445   // ~x < ~y --> y < x
6446   { Value *A, *B;
6447     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6448         match(Op1, m_Not(m_Value(B)), *Context))
6449       return new ICmpInst(*Context, I.getPredicate(), B, A);
6450   }
6451   
6452   if (I.isEquality()) {
6453     Value *A, *B, *C, *D;
6454     
6455     // -x == -y --> x == y
6456     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6457         match(Op1, m_Neg(m_Value(B)), *Context))
6458       return new ICmpInst(*Context, I.getPredicate(), A, B);
6459     
6460     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6461       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6462         Value *OtherVal = A == Op1 ? B : A;
6463         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6464                             Context->getNullValue(A->getType()));
6465       }
6466
6467       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6468         // A^c1 == C^c2 --> A == C^(c1^c2)
6469         ConstantInt *C1, *C2;
6470         if (match(B, m_ConstantInt(C1), *Context) &&
6471             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6472           Constant *NC = 
6473                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6474           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6475           return new ICmpInst(*Context, I.getPredicate(), A,
6476                               InsertNewInstBefore(Xor, I));
6477         }
6478         
6479         // A^B == A^D -> B == D
6480         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6481         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6482         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6483         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6484       }
6485     }
6486     
6487     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6488         (A == Op0 || B == Op0)) {
6489       // A == (A^B)  ->  B == 0
6490       Value *OtherVal = A == Op0 ? B : A;
6491       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6492                           Context->getNullValue(A->getType()));
6493     }
6494
6495     // (A-B) == A  ->  B == 0
6496     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6497       return new ICmpInst(*Context, I.getPredicate(), B, 
6498                           Context->getNullValue(B->getType()));
6499
6500     // A == (A-B)  ->  B == 0
6501     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6502       return new ICmpInst(*Context, I.getPredicate(), B,
6503                           Context->getNullValue(B->getType()));
6504     
6505     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6506     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6507         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6508         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6509       Value *X = 0, *Y = 0, *Z = 0;
6510       
6511       if (A == C) {
6512         X = B; Y = D; Z = A;
6513       } else if (A == D) {
6514         X = B; Y = C; Z = A;
6515       } else if (B == C) {
6516         X = A; Y = D; Z = B;
6517       } else if (B == D) {
6518         X = A; Y = C; Z = B;
6519       }
6520       
6521       if (X) {   // Build (X^Y) & Z
6522         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6523         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6524         I.setOperand(0, Op1);
6525         I.setOperand(1, Context->getNullValue(Op1->getType()));
6526         return &I;
6527       }
6528     }
6529   }
6530   return Changed ? &I : 0;
6531 }
6532
6533
6534 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6535 /// and CmpRHS are both known to be integer constants.
6536 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6537                                           ConstantInt *DivRHS) {
6538   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6539   const APInt &CmpRHSV = CmpRHS->getValue();
6540   
6541   // FIXME: If the operand types don't match the type of the divide 
6542   // then don't attempt this transform. The code below doesn't have the
6543   // logic to deal with a signed divide and an unsigned compare (and
6544   // vice versa). This is because (x /s C1) <s C2  produces different 
6545   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6546   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6547   // work. :(  The if statement below tests that condition and bails 
6548   // if it finds it. 
6549   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6550   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6551     return 0;
6552   if (DivRHS->isZero())
6553     return 0; // The ProdOV computation fails on divide by zero.
6554   if (DivIsSigned && DivRHS->isAllOnesValue())
6555     return 0; // The overflow computation also screws up here
6556   if (DivRHS->isOne())
6557     return 0; // Not worth bothering, and eliminates some funny cases
6558               // with INT_MIN.
6559
6560   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6561   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6562   // C2 (CI). By solving for X we can turn this into a range check 
6563   // instead of computing a divide. 
6564   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6565
6566   // Determine if the product overflows by seeing if the product is
6567   // not equal to the divide. Make sure we do the same kind of divide
6568   // as in the LHS instruction that we're folding. 
6569   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6570                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6571
6572   // Get the ICmp opcode
6573   ICmpInst::Predicate Pred = ICI.getPredicate();
6574
6575   // Figure out the interval that is being checked.  For example, a comparison
6576   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6577   // Compute this interval based on the constants involved and the signedness of
6578   // the compare/divide.  This computes a half-open interval, keeping track of
6579   // whether either value in the interval overflows.  After analysis each
6580   // overflow variable is set to 0 if it's corresponding bound variable is valid
6581   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6582   int LoOverflow = 0, HiOverflow = 0;
6583   Constant *LoBound = 0, *HiBound = 0;
6584   
6585   if (!DivIsSigned) {  // udiv
6586     // e.g. X/5 op 3  --> [15, 20)
6587     LoBound = Prod;
6588     HiOverflow = LoOverflow = ProdOV;
6589     if (!HiOverflow)
6590       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6591   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6592     if (CmpRHSV == 0) {       // (X / pos) op 0
6593       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6594       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6595                                                                     Context)));
6596       HiBound = DivRHS;
6597     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6598       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6599       HiOverflow = LoOverflow = ProdOV;
6600       if (!HiOverflow)
6601         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6602     } else {                       // (X / pos) op neg
6603       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6604       HiBound = AddOne(Prod, Context);
6605       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6606       if (!LoOverflow) {
6607         ConstantInt* DivNeg =
6608                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6609         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6610                                      true) ? -1 : 0;
6611        }
6612     }
6613   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6614     if (CmpRHSV == 0) {       // (X / neg) op 0
6615       // e.g. X/-5 op 0  --> [-4, 5)
6616       LoBound = AddOne(DivRHS, Context);
6617       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6618       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6619         HiOverflow = 1;            // [INTMIN+1, overflow)
6620         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6621       }
6622     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6623       // e.g. X/-5 op 3  --> [-19, -14)
6624       HiBound = AddOne(Prod, Context);
6625       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6626       if (!LoOverflow)
6627         LoOverflow = AddWithOverflow(LoBound, HiBound,
6628                                      DivRHS, Context, true) ? -1 : 0;
6629     } else {                       // (X / neg) op neg
6630       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6631       LoOverflow = HiOverflow = ProdOV;
6632       if (!HiOverflow)
6633         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6634     }
6635     
6636     // Dividing by a negative swaps the condition.  LT <-> GT
6637     Pred = ICmpInst::getSwappedPredicate(Pred);
6638   }
6639
6640   Value *X = DivI->getOperand(0);
6641   switch (Pred) {
6642   default: llvm_unreachable("Unhandled icmp opcode!");
6643   case ICmpInst::ICMP_EQ:
6644     if (LoOverflow && HiOverflow)
6645       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6646     else if (HiOverflow)
6647       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6648                           ICmpInst::ICMP_UGE, X, LoBound);
6649     else if (LoOverflow)
6650       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6651                           ICmpInst::ICMP_ULT, X, HiBound);
6652     else
6653       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6654   case ICmpInst::ICMP_NE:
6655     if (LoOverflow && HiOverflow)
6656       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6657     else if (HiOverflow)
6658       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6659                           ICmpInst::ICMP_ULT, X, LoBound);
6660     else if (LoOverflow)
6661       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6662                           ICmpInst::ICMP_UGE, X, HiBound);
6663     else
6664       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6665   case ICmpInst::ICMP_ULT:
6666   case ICmpInst::ICMP_SLT:
6667     if (LoOverflow == +1)   // Low bound is greater than input range.
6668       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6669     if (LoOverflow == -1)   // Low bound is less than input range.
6670       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6671     return new ICmpInst(*Context, Pred, X, LoBound);
6672   case ICmpInst::ICMP_UGT:
6673   case ICmpInst::ICMP_SGT:
6674     if (HiOverflow == +1)       // High bound greater than input range.
6675       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6676     else if (HiOverflow == -1)  // High bound less than input range.
6677       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6678     if (Pred == ICmpInst::ICMP_UGT)
6679       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6680     else
6681       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6682   }
6683 }
6684
6685
6686 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6687 ///
6688 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6689                                                           Instruction *LHSI,
6690                                                           ConstantInt *RHS) {
6691   const APInt &RHSV = RHS->getValue();
6692   
6693   switch (LHSI->getOpcode()) {
6694   case Instruction::Trunc:
6695     if (ICI.isEquality() && LHSI->hasOneUse()) {
6696       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6697       // of the high bits truncated out of x are known.
6698       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6699              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6700       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6701       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6702       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6703       
6704       // If all the high bits are known, we can do this xform.
6705       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6706         // Pull in the high bits from known-ones set.
6707         APInt NewRHS(RHS->getValue());
6708         NewRHS.zext(SrcBits);
6709         NewRHS |= KnownOne;
6710         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6711                             Context->getConstantInt(NewRHS));
6712       }
6713     }
6714     break;
6715       
6716   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6717     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6718       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6719       // fold the xor.
6720       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6721           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6722         Value *CompareVal = LHSI->getOperand(0);
6723         
6724         // If the sign bit of the XorCST is not set, there is no change to
6725         // the operation, just stop using the Xor.
6726         if (!XorCST->getValue().isNegative()) {
6727           ICI.setOperand(0, CompareVal);
6728           AddToWorkList(LHSI);
6729           return &ICI;
6730         }
6731         
6732         // Was the old condition true if the operand is positive?
6733         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6734         
6735         // If so, the new one isn't.
6736         isTrueIfPositive ^= true;
6737         
6738         if (isTrueIfPositive)
6739           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6740                               SubOne(RHS, Context));
6741         else
6742           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6743                               AddOne(RHS, Context));
6744       }
6745
6746       if (LHSI->hasOneUse()) {
6747         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6748         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6749           const APInt &SignBit = XorCST->getValue();
6750           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6751                                          ? ICI.getUnsignedPredicate()
6752                                          : ICI.getSignedPredicate();
6753           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6754                               Context->getConstantInt(RHSV ^ SignBit));
6755         }
6756
6757         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6758         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6759           const APInt &NotSignBit = XorCST->getValue();
6760           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6761                                          ? ICI.getUnsignedPredicate()
6762                                          : ICI.getSignedPredicate();
6763           Pred = ICI.getSwappedPredicate(Pred);
6764           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6765                               Context->getConstantInt(RHSV ^ NotSignBit));
6766         }
6767       }
6768     }
6769     break;
6770   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6771     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6772         LHSI->getOperand(0)->hasOneUse()) {
6773       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6774       
6775       // If the LHS is an AND of a truncating cast, we can widen the
6776       // and/compare to be the input width without changing the value
6777       // produced, eliminating a cast.
6778       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6779         // We can do this transformation if either the AND constant does not
6780         // have its sign bit set or if it is an equality comparison. 
6781         // Extending a relational comparison when we're checking the sign
6782         // bit would not work.
6783         if (Cast->hasOneUse() &&
6784             (ICI.isEquality() ||
6785              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6786           uint32_t BitWidth = 
6787             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6788           APInt NewCST = AndCST->getValue();
6789           NewCST.zext(BitWidth);
6790           APInt NewCI = RHSV;
6791           NewCI.zext(BitWidth);
6792           Instruction *NewAnd = 
6793             BinaryOperator::CreateAnd(Cast->getOperand(0),
6794                                Context->getConstantInt(NewCST),LHSI->getName());
6795           InsertNewInstBefore(NewAnd, ICI);
6796           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6797                               Context->getConstantInt(NewCI));
6798         }
6799       }
6800       
6801       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6802       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6803       // happens a LOT in code produced by the C front-end, for bitfield
6804       // access.
6805       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6806       if (Shift && !Shift->isShift())
6807         Shift = 0;
6808       
6809       ConstantInt *ShAmt;
6810       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6811       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6812       const Type *AndTy = AndCST->getType();          // Type of the and.
6813       
6814       // We can fold this as long as we can't shift unknown bits
6815       // into the mask.  This can only happen with signed shift
6816       // rights, as they sign-extend.
6817       if (ShAmt) {
6818         bool CanFold = Shift->isLogicalShift();
6819         if (!CanFold) {
6820           // To test for the bad case of the signed shr, see if any
6821           // of the bits shifted in could be tested after the mask.
6822           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6823           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6824           
6825           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6826           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6827                AndCST->getValue()) == 0)
6828             CanFold = true;
6829         }
6830         
6831         if (CanFold) {
6832           Constant *NewCst;
6833           if (Shift->getOpcode() == Instruction::Shl)
6834             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6835           else
6836             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6837           
6838           // Check to see if we are shifting out any of the bits being
6839           // compared.
6840           if (Context->getConstantExpr(Shift->getOpcode(),
6841                                        NewCst, ShAmt) != RHS) {
6842             // If we shifted bits out, the fold is not going to work out.
6843             // As a special case, check to see if this means that the
6844             // result is always true or false now.
6845             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6846               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6847             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6848               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6849           } else {
6850             ICI.setOperand(1, NewCst);
6851             Constant *NewAndCST;
6852             if (Shift->getOpcode() == Instruction::Shl)
6853               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6854             else
6855               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6856             LHSI->setOperand(1, NewAndCST);
6857             LHSI->setOperand(0, Shift->getOperand(0));
6858             AddToWorkList(Shift); // Shift is dead.
6859             AddUsesToWorkList(ICI);
6860             return &ICI;
6861           }
6862         }
6863       }
6864       
6865       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6866       // preferable because it allows the C<<Y expression to be hoisted out
6867       // of a loop if Y is invariant and X is not.
6868       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6869           ICI.isEquality() && !Shift->isArithmeticShift() &&
6870           !isa<Constant>(Shift->getOperand(0))) {
6871         // Compute C << Y.
6872         Value *NS;
6873         if (Shift->getOpcode() == Instruction::LShr) {
6874           NS = BinaryOperator::CreateShl(AndCST, 
6875                                          Shift->getOperand(1), "tmp");
6876         } else {
6877           // Insert a logical shift.
6878           NS = BinaryOperator::CreateLShr(AndCST,
6879                                           Shift->getOperand(1), "tmp");
6880         }
6881         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6882         
6883         // Compute X & (C << Y).
6884         Instruction *NewAnd = 
6885           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6886         InsertNewInstBefore(NewAnd, ICI);
6887         
6888         ICI.setOperand(0, NewAnd);
6889         return &ICI;
6890       }
6891     }
6892     break;
6893     
6894   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6895     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6896     if (!ShAmt) break;
6897     
6898     uint32_t TypeBits = RHSV.getBitWidth();
6899     
6900     // Check that the shift amount is in range.  If not, don't perform
6901     // undefined shifts.  When the shift is visited it will be
6902     // simplified.
6903     if (ShAmt->uge(TypeBits))
6904       break;
6905     
6906     if (ICI.isEquality()) {
6907       // If we are comparing against bits always shifted out, the
6908       // comparison cannot succeed.
6909       Constant *Comp =
6910         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6911                                                                  ShAmt);
6912       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6913         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6914         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6915         return ReplaceInstUsesWith(ICI, Cst);
6916       }
6917       
6918       if (LHSI->hasOneUse()) {
6919         // Otherwise strength reduce the shift into an and.
6920         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6921         Constant *Mask =
6922           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6923                                                        TypeBits-ShAmtVal));
6924         
6925         Instruction *AndI =
6926           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6927                                     Mask, LHSI->getName()+".mask");
6928         Value *And = InsertNewInstBefore(AndI, ICI);
6929         return new ICmpInst(*Context, ICI.getPredicate(), And,
6930                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6931       }
6932     }
6933     
6934     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6935     bool TrueIfSigned = false;
6936     if (LHSI->hasOneUse() &&
6937         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6938       // (X << 31) <s 0  --> (X&1) != 0
6939       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6940                                            (TypeBits-ShAmt->getZExtValue()-1));
6941       Instruction *AndI =
6942         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6943                                   Mask, LHSI->getName()+".mask");
6944       Value *And = InsertNewInstBefore(AndI, ICI);
6945       
6946       return new ICmpInst(*Context,
6947                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6948                           And, Context->getNullValue(And->getType()));
6949     }
6950     break;
6951   }
6952     
6953   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6954   case Instruction::AShr: {
6955     // Only handle equality comparisons of shift-by-constant.
6956     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6957     if (!ShAmt || !ICI.isEquality()) break;
6958
6959     // Check that the shift amount is in range.  If not, don't perform
6960     // undefined shifts.  When the shift is visited it will be
6961     // simplified.
6962     uint32_t TypeBits = RHSV.getBitWidth();
6963     if (ShAmt->uge(TypeBits))
6964       break;
6965     
6966     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6967       
6968     // If we are comparing against bits always shifted out, the
6969     // comparison cannot succeed.
6970     APInt Comp = RHSV << ShAmtVal;
6971     if (LHSI->getOpcode() == Instruction::LShr)
6972       Comp = Comp.lshr(ShAmtVal);
6973     else
6974       Comp = Comp.ashr(ShAmtVal);
6975     
6976     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6977       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6978       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6979       return ReplaceInstUsesWith(ICI, Cst);
6980     }
6981     
6982     // Otherwise, check to see if the bits shifted out are known to be zero.
6983     // If so, we can compare against the unshifted value:
6984     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6985     if (LHSI->hasOneUse() &&
6986         MaskedValueIsZero(LHSI->getOperand(0), 
6987                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6988       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6989                           Context->getConstantExprShl(RHS, ShAmt));
6990     }
6991       
6992     if (LHSI->hasOneUse()) {
6993       // Otherwise strength reduce the shift into an and.
6994       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6995       Constant *Mask = Context->getConstantInt(Val);
6996       
6997       Instruction *AndI =
6998         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6999                                   Mask, LHSI->getName()+".mask");
7000       Value *And = InsertNewInstBefore(AndI, ICI);
7001       return new ICmpInst(*Context, ICI.getPredicate(), And,
7002                           Context->getConstantExprShl(RHS, ShAmt));
7003     }
7004     break;
7005   }
7006     
7007   case Instruction::SDiv:
7008   case Instruction::UDiv:
7009     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7010     // Fold this div into the comparison, producing a range check. 
7011     // Determine, based on the divide type, what the range is being 
7012     // checked.  If there is an overflow on the low or high side, remember 
7013     // it, otherwise compute the range [low, hi) bounding the new value.
7014     // See: InsertRangeTest above for the kinds of replacements possible.
7015     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7016       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7017                                           DivRHS))
7018         return R;
7019     break;
7020
7021   case Instruction::Add:
7022     // Fold: icmp pred (add, X, C1), C2
7023
7024     if (!ICI.isEquality()) {
7025       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7026       if (!LHSC) break;
7027       const APInt &LHSV = LHSC->getValue();
7028
7029       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7030                             .subtract(LHSV);
7031
7032       if (ICI.isSignedPredicate()) {
7033         if (CR.getLower().isSignBit()) {
7034           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7035                               Context->getConstantInt(CR.getUpper()));
7036         } else if (CR.getUpper().isSignBit()) {
7037           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7038                               Context->getConstantInt(CR.getLower()));
7039         }
7040       } else {
7041         if (CR.getLower().isMinValue()) {
7042           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7043                               Context->getConstantInt(CR.getUpper()));
7044         } else if (CR.getUpper().isMinValue()) {
7045           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7046                               Context->getConstantInt(CR.getLower()));
7047         }
7048       }
7049     }
7050     break;
7051   }
7052   
7053   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7054   if (ICI.isEquality()) {
7055     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7056     
7057     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7058     // the second operand is a constant, simplify a bit.
7059     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7060       switch (BO->getOpcode()) {
7061       case Instruction::SRem:
7062         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7063         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7064           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7065           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7066             Instruction *NewRem =
7067               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7068                                          BO->getName());
7069             InsertNewInstBefore(NewRem, ICI);
7070             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7071                                 Context->getNullValue(BO->getType()));
7072           }
7073         }
7074         break;
7075       case Instruction::Add:
7076         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7077         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7078           if (BO->hasOneUse())
7079             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7080                                 Context->getConstantExprSub(RHS, BOp1C));
7081         } else if (RHSV == 0) {
7082           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7083           // efficiently invertible, or if the add has just this one use.
7084           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7085           
7086           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7087             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7088           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7089             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7090           else if (BO->hasOneUse()) {
7091             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7092             InsertNewInstBefore(Neg, ICI);
7093             Neg->takeName(BO);
7094             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7095           }
7096         }
7097         break;
7098       case Instruction::Xor:
7099         // For the xor case, we can xor two constants together, eliminating
7100         // the explicit xor.
7101         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7102           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7103                               Context->getConstantExprXor(RHS, BOC));
7104         
7105         // FALLTHROUGH
7106       case Instruction::Sub:
7107         // Replace (([sub|xor] A, B) != 0) with (A != B)
7108         if (RHSV == 0)
7109           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7110                               BO->getOperand(1));
7111         break;
7112         
7113       case Instruction::Or:
7114         // If bits are being or'd in that are not present in the constant we
7115         // are comparing against, then the comparison could never succeed!
7116         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7117           Constant *NotCI = Context->getConstantExprNot(RHS);
7118           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7119             return ReplaceInstUsesWith(ICI,
7120                                        Context->getConstantInt(Type::Int1Ty, 
7121                                        isICMP_NE));
7122         }
7123         break;
7124         
7125       case Instruction::And:
7126         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7127           // If bits are being compared against that are and'd out, then the
7128           // comparison can never succeed!
7129           if ((RHSV & ~BOC->getValue()) != 0)
7130             return ReplaceInstUsesWith(ICI,
7131                                        Context->getConstantInt(Type::Int1Ty,
7132                                        isICMP_NE));
7133           
7134           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7135           if (RHS == BOC && RHSV.isPowerOf2())
7136             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7137                                 ICmpInst::ICMP_NE, LHSI,
7138                                 Context->getNullValue(RHS->getType()));
7139           
7140           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7141           if (BOC->getValue().isSignBit()) {
7142             Value *X = BO->getOperand(0);
7143             Constant *Zero = Context->getNullValue(X->getType());
7144             ICmpInst::Predicate pred = isICMP_NE ? 
7145               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7146             return new ICmpInst(*Context, pred, X, Zero);
7147           }
7148           
7149           // ((X & ~7) == 0) --> X < 8
7150           if (RHSV == 0 && isHighOnes(BOC)) {
7151             Value *X = BO->getOperand(0);
7152             Constant *NegX = Context->getConstantExprNeg(BOC);
7153             ICmpInst::Predicate pred = isICMP_NE ? 
7154               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7155             return new ICmpInst(*Context, pred, X, NegX);
7156           }
7157         }
7158       default: break;
7159       }
7160     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7161       // Handle icmp {eq|ne} <intrinsic>, intcst.
7162       if (II->getIntrinsicID() == Intrinsic::bswap) {
7163         AddToWorkList(II);
7164         ICI.setOperand(0, II->getOperand(1));
7165         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7166         return &ICI;
7167       }
7168     }
7169   }
7170   return 0;
7171 }
7172
7173 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7174 /// We only handle extending casts so far.
7175 ///
7176 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7177   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7178   Value *LHSCIOp        = LHSCI->getOperand(0);
7179   const Type *SrcTy     = LHSCIOp->getType();
7180   const Type *DestTy    = LHSCI->getType();
7181   Value *RHSCIOp;
7182
7183   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7184   // integer type is the same size as the pointer type.
7185   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7186       getTargetData().getPointerSizeInBits() == 
7187          cast<IntegerType>(DestTy)->getBitWidth()) {
7188     Value *RHSOp = 0;
7189     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7190       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7191     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7192       RHSOp = RHSC->getOperand(0);
7193       // If the pointer types don't match, insert a bitcast.
7194       if (LHSCIOp->getType() != RHSOp->getType())
7195         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7196     }
7197
7198     if (RHSOp)
7199       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7200   }
7201   
7202   // The code below only handles extension cast instructions, so far.
7203   // Enforce this.
7204   if (LHSCI->getOpcode() != Instruction::ZExt &&
7205       LHSCI->getOpcode() != Instruction::SExt)
7206     return 0;
7207
7208   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7209   bool isSignedCmp = ICI.isSignedPredicate();
7210
7211   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7212     // Not an extension from the same type?
7213     RHSCIOp = CI->getOperand(0);
7214     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7215       return 0;
7216     
7217     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7218     // and the other is a zext), then we can't handle this.
7219     if (CI->getOpcode() != LHSCI->getOpcode())
7220       return 0;
7221
7222     // Deal with equality cases early.
7223     if (ICI.isEquality())
7224       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7225
7226     // A signed comparison of sign extended values simplifies into a
7227     // signed comparison.
7228     if (isSignedCmp && isSignedExt)
7229       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7230
7231     // The other three cases all fold into an unsigned comparison.
7232     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7233   }
7234
7235   // If we aren't dealing with a constant on the RHS, exit early
7236   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7237   if (!CI)
7238     return 0;
7239
7240   // Compute the constant that would happen if we truncated to SrcTy then
7241   // reextended to DestTy.
7242   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7243   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7244                                                 Res1, DestTy);
7245
7246   // If the re-extended constant didn't change...
7247   if (Res2 == CI) {
7248     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7249     // For example, we might have:
7250     //    %A = sext i16 %X to i32
7251     //    %B = icmp ugt i32 %A, 1330
7252     // It is incorrect to transform this into 
7253     //    %B = icmp ugt i16 %X, 1330
7254     // because %A may have negative value. 
7255     //
7256     // However, we allow this when the compare is EQ/NE, because they are
7257     // signless.
7258     if (isSignedExt == isSignedCmp || ICI.isEquality())
7259       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7260     return 0;
7261   }
7262
7263   // The re-extended constant changed so the constant cannot be represented 
7264   // in the shorter type. Consequently, we cannot emit a simple comparison.
7265
7266   // First, handle some easy cases. We know the result cannot be equal at this
7267   // point so handle the ICI.isEquality() cases
7268   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7269     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7270   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7271     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7272
7273   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7274   // should have been folded away previously and not enter in here.
7275   Value *Result;
7276   if (isSignedCmp) {
7277     // We're performing a signed comparison.
7278     if (cast<ConstantInt>(CI)->getValue().isNegative())
7279       Result = Context->getConstantIntFalse();          // X < (small) --> false
7280     else
7281       Result = Context->getConstantIntTrue();           // X < (large) --> true
7282   } else {
7283     // We're performing an unsigned comparison.
7284     if (isSignedExt) {
7285       // We're performing an unsigned comp with a sign extended value.
7286       // This is true if the input is >= 0. [aka >s -1]
7287       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7288       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7289                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7290     } else {
7291       // Unsigned extend & unsigned compare -> always true.
7292       Result = Context->getConstantIntTrue();
7293     }
7294   }
7295
7296   // Finally, return the value computed.
7297   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7298       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7299     return ReplaceInstUsesWith(ICI, Result);
7300
7301   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7302           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7303          "ICmp should be folded!");
7304   if (Constant *CI = dyn_cast<Constant>(Result))
7305     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7306   return BinaryOperator::CreateNot(*Context, Result);
7307 }
7308
7309 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7310   return commonShiftTransforms(I);
7311 }
7312
7313 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7314   return commonShiftTransforms(I);
7315 }
7316
7317 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7318   if (Instruction *R = commonShiftTransforms(I))
7319     return R;
7320   
7321   Value *Op0 = I.getOperand(0);
7322   
7323   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7324   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7325     if (CSI->isAllOnesValue())
7326       return ReplaceInstUsesWith(I, CSI);
7327
7328   // See if we can turn a signed shr into an unsigned shr.
7329   if (MaskedValueIsZero(Op0,
7330                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7331     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7332
7333   // Arithmetic shifting an all-sign-bit value is a no-op.
7334   unsigned NumSignBits = ComputeNumSignBits(Op0);
7335   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7336     return ReplaceInstUsesWith(I, Op0);
7337
7338   return 0;
7339 }
7340
7341 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7342   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7343   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7344
7345   // shl X, 0 == X and shr X, 0 == X
7346   // shl 0, X == 0 and shr 0, X == 0
7347   if (Op1 == Context->getNullValue(Op1->getType()) ||
7348       Op0 == Context->getNullValue(Op0->getType()))
7349     return ReplaceInstUsesWith(I, Op0);
7350   
7351   if (isa<UndefValue>(Op0)) {            
7352     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7353       return ReplaceInstUsesWith(I, Op0);
7354     else                                    // undef << X -> 0, undef >>u X -> 0
7355       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7356   }
7357   if (isa<UndefValue>(Op1)) {
7358     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7359       return ReplaceInstUsesWith(I, Op0);          
7360     else                                     // X << undef, X >>u undef -> 0
7361       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7362   }
7363
7364   // See if we can fold away this shift.
7365   if (SimplifyDemandedInstructionBits(I))
7366     return &I;
7367
7368   // Try to fold constant and into select arguments.
7369   if (isa<Constant>(Op0))
7370     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7371       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7372         return R;
7373
7374   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7375     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7376       return Res;
7377   return 0;
7378 }
7379
7380 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7381                                                BinaryOperator &I) {
7382   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7383
7384   // See if we can simplify any instructions used by the instruction whose sole 
7385   // purpose is to compute bits we don't care about.
7386   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7387   
7388   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7389   // a signed shift.
7390   //
7391   if (Op1->uge(TypeBits)) {
7392     if (I.getOpcode() != Instruction::AShr)
7393       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7394     else {
7395       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7396       return &I;
7397     }
7398   }
7399   
7400   // ((X*C1) << C2) == (X * (C1 << C2))
7401   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7402     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7403       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7404         return BinaryOperator::CreateMul(BO->getOperand(0),
7405                                         Context->getConstantExprShl(BOOp, Op1));
7406   
7407   // Try to fold constant and into select arguments.
7408   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7409     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7410       return R;
7411   if (isa<PHINode>(Op0))
7412     if (Instruction *NV = FoldOpIntoPhi(I))
7413       return NV;
7414   
7415   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7416   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7417     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7418     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7419     // place.  Don't try to do this transformation in this case.  Also, we
7420     // require that the input operand is a shift-by-constant so that we have
7421     // confidence that the shifts will get folded together.  We could do this
7422     // xform in more cases, but it is unlikely to be profitable.
7423     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7424         isa<ConstantInt>(TrOp->getOperand(1))) {
7425       // Okay, we'll do this xform.  Make the shift of shift.
7426       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7427       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7428                                                 I.getName());
7429       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7430
7431       // For logical shifts, the truncation has the effect of making the high
7432       // part of the register be zeros.  Emulate this by inserting an AND to
7433       // clear the top bits as needed.  This 'and' will usually be zapped by
7434       // other xforms later if dead.
7435       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7436       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7437       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7438       
7439       // The mask we constructed says what the trunc would do if occurring
7440       // between the shifts.  We want to know the effect *after* the second
7441       // shift.  We know that it is a logical shift by a constant, so adjust the
7442       // mask as appropriate.
7443       if (I.getOpcode() == Instruction::Shl)
7444         MaskV <<= Op1->getZExtValue();
7445       else {
7446         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7447         MaskV = MaskV.lshr(Op1->getZExtValue());
7448       }
7449
7450       Instruction *And =
7451         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7452                                   TI->getName());
7453       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7454
7455       // Return the value truncated to the interesting size.
7456       return new TruncInst(And, I.getType());
7457     }
7458   }
7459   
7460   if (Op0->hasOneUse()) {
7461     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7462       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7463       Value *V1, *V2;
7464       ConstantInt *CC;
7465       switch (Op0BO->getOpcode()) {
7466         default: break;
7467         case Instruction::Add:
7468         case Instruction::And:
7469         case Instruction::Or:
7470         case Instruction::Xor: {
7471           // These operators commute.
7472           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7473           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7474               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7475                     m_Specific(Op1)), *Context)){
7476             Instruction *YS = BinaryOperator::CreateShl(
7477                                             Op0BO->getOperand(0), Op1,
7478                                             Op0BO->getName());
7479             InsertNewInstBefore(YS, I); // (Y << C)
7480             Instruction *X = 
7481               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7482                                      Op0BO->getOperand(1)->getName());
7483             InsertNewInstBefore(X, I);  // (X + (Y << C))
7484             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7485             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7486                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7487           }
7488           
7489           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7490           Value *Op0BOOp1 = Op0BO->getOperand(1);
7491           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7492               match(Op0BOOp1, 
7493                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7494                           m_ConstantInt(CC)), *Context) &&
7495               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7496             Instruction *YS = BinaryOperator::CreateShl(
7497                                                      Op0BO->getOperand(0), Op1,
7498                                                      Op0BO->getName());
7499             InsertNewInstBefore(YS, I); // (Y << C)
7500             Instruction *XM =
7501               BinaryOperator::CreateAnd(V1,
7502                                         Context->getConstantExprShl(CC, Op1),
7503                                         V1->getName()+".mask");
7504             InsertNewInstBefore(XM, I); // X & (CC << C)
7505             
7506             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7507           }
7508         }
7509           
7510         // FALL THROUGH.
7511         case Instruction::Sub: {
7512           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7513           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7514               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7515                     m_Specific(Op1)), *Context)){
7516             Instruction *YS = BinaryOperator::CreateShl(
7517                                                      Op0BO->getOperand(1), Op1,
7518                                                      Op0BO->getName());
7519             InsertNewInstBefore(YS, I); // (Y << C)
7520             Instruction *X =
7521               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7522                                      Op0BO->getOperand(0)->getName());
7523             InsertNewInstBefore(X, I);  // (X + (Y << C))
7524             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7525             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7526                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7527           }
7528           
7529           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7530           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7531               match(Op0BO->getOperand(0),
7532                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7533                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7534               cast<BinaryOperator>(Op0BO->getOperand(0))
7535                   ->getOperand(0)->hasOneUse()) {
7536             Instruction *YS = BinaryOperator::CreateShl(
7537                                                      Op0BO->getOperand(1), Op1,
7538                                                      Op0BO->getName());
7539             InsertNewInstBefore(YS, I); // (Y << C)
7540             Instruction *XM =
7541               BinaryOperator::CreateAnd(V1, 
7542                                         Context->getConstantExprShl(CC, Op1),
7543                                         V1->getName()+".mask");
7544             InsertNewInstBefore(XM, I); // X & (CC << C)
7545             
7546             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7547           }
7548           
7549           break;
7550         }
7551       }
7552       
7553       
7554       // If the operand is an bitwise operator with a constant RHS, and the
7555       // shift is the only use, we can pull it out of the shift.
7556       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7557         bool isValid = true;     // Valid only for And, Or, Xor
7558         bool highBitSet = false; // Transform if high bit of constant set?
7559         
7560         switch (Op0BO->getOpcode()) {
7561           default: isValid = false; break;   // Do not perform transform!
7562           case Instruction::Add:
7563             isValid = isLeftShift;
7564             break;
7565           case Instruction::Or:
7566           case Instruction::Xor:
7567             highBitSet = false;
7568             break;
7569           case Instruction::And:
7570             highBitSet = true;
7571             break;
7572         }
7573         
7574         // If this is a signed shift right, and the high bit is modified
7575         // by the logical operation, do not perform the transformation.
7576         // The highBitSet boolean indicates the value of the high bit of
7577         // the constant which would cause it to be modified for this
7578         // operation.
7579         //
7580         if (isValid && I.getOpcode() == Instruction::AShr)
7581           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7582         
7583         if (isValid) {
7584           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7585           
7586           Instruction *NewShift =
7587             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7588           InsertNewInstBefore(NewShift, I);
7589           NewShift->takeName(Op0BO);
7590           
7591           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7592                                         NewRHS);
7593         }
7594       }
7595     }
7596   }
7597   
7598   // Find out if this is a shift of a shift by a constant.
7599   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7600   if (ShiftOp && !ShiftOp->isShift())
7601     ShiftOp = 0;
7602   
7603   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7604     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7605     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7606     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7607     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7608     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7609     Value *X = ShiftOp->getOperand(0);
7610     
7611     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7612     
7613     const IntegerType *Ty = cast<IntegerType>(I.getType());
7614     
7615     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7616     if (I.getOpcode() == ShiftOp->getOpcode()) {
7617       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7618       // saturates.
7619       if (AmtSum >= TypeBits) {
7620         if (I.getOpcode() != Instruction::AShr)
7621           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7622         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7623       }
7624       
7625       return BinaryOperator::Create(I.getOpcode(), X,
7626                                     Context->getConstantInt(Ty, AmtSum));
7627     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7628                I.getOpcode() == Instruction::AShr) {
7629       if (AmtSum >= TypeBits)
7630         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7631       
7632       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7633       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7634     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7635                I.getOpcode() == Instruction::LShr) {
7636       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7637       if (AmtSum >= TypeBits)
7638         AmtSum = TypeBits-1;
7639       
7640       Instruction *Shift =
7641         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7642       InsertNewInstBefore(Shift, I);
7643
7644       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7645       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7646     }
7647     
7648     // Okay, if we get here, one shift must be left, and the other shift must be
7649     // right.  See if the amounts are equal.
7650     if (ShiftAmt1 == ShiftAmt2) {
7651       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7652       if (I.getOpcode() == Instruction::Shl) {
7653         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7654         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7655       }
7656       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7657       if (I.getOpcode() == Instruction::LShr) {
7658         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7659         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7660       }
7661       // We can simplify ((X << C) >>s C) into a trunc + sext.
7662       // NOTE: we could do this for any C, but that would make 'unusual' integer
7663       // types.  For now, just stick to ones well-supported by the code
7664       // generators.
7665       const Type *SExtType = 0;
7666       switch (Ty->getBitWidth() - ShiftAmt1) {
7667       case 1  :
7668       case 8  :
7669       case 16 :
7670       case 32 :
7671       case 64 :
7672       case 128:
7673         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7674         break;
7675       default: break;
7676       }
7677       if (SExtType) {
7678         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7679         InsertNewInstBefore(NewTrunc, I);
7680         return new SExtInst(NewTrunc, Ty);
7681       }
7682       // Otherwise, we can't handle it yet.
7683     } else if (ShiftAmt1 < ShiftAmt2) {
7684       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7685       
7686       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7687       if (I.getOpcode() == Instruction::Shl) {
7688         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7689                ShiftOp->getOpcode() == Instruction::AShr);
7690         Instruction *Shift =
7691           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7692         InsertNewInstBefore(Shift, I);
7693         
7694         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7695         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7696       }
7697       
7698       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7699       if (I.getOpcode() == Instruction::LShr) {
7700         assert(ShiftOp->getOpcode() == Instruction::Shl);
7701         Instruction *Shift =
7702           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7703         InsertNewInstBefore(Shift, I);
7704         
7705         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7706         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7707       }
7708       
7709       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7710     } else {
7711       assert(ShiftAmt2 < ShiftAmt1);
7712       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7713
7714       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7715       if (I.getOpcode() == Instruction::Shl) {
7716         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7717                ShiftOp->getOpcode() == Instruction::AShr);
7718         Instruction *Shift =
7719           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7720                                  Context->getConstantInt(Ty, ShiftDiff));
7721         InsertNewInstBefore(Shift, I);
7722         
7723         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7724         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7725       }
7726       
7727       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7728       if (I.getOpcode() == Instruction::LShr) {
7729         assert(ShiftOp->getOpcode() == Instruction::Shl);
7730         Instruction *Shift =
7731           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7732         InsertNewInstBefore(Shift, I);
7733         
7734         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7735         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7736       }
7737       
7738       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7739     }
7740   }
7741   return 0;
7742 }
7743
7744
7745 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7746 /// expression.  If so, decompose it, returning some value X, such that Val is
7747 /// X*Scale+Offset.
7748 ///
7749 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7750                                         int &Offset, LLVMContext *Context) {
7751   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7752   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7753     Offset = CI->getZExtValue();
7754     Scale  = 0;
7755     return Context->getConstantInt(Type::Int32Ty, 0);
7756   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7757     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7758       if (I->getOpcode() == Instruction::Shl) {
7759         // This is a value scaled by '1 << the shift amt'.
7760         Scale = 1U << RHS->getZExtValue();
7761         Offset = 0;
7762         return I->getOperand(0);
7763       } else if (I->getOpcode() == Instruction::Mul) {
7764         // This value is scaled by 'RHS'.
7765         Scale = RHS->getZExtValue();
7766         Offset = 0;
7767         return I->getOperand(0);
7768       } else if (I->getOpcode() == Instruction::Add) {
7769         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7770         // where C1 is divisible by C2.
7771         unsigned SubScale;
7772         Value *SubVal = 
7773           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7774                                     Offset, Context);
7775         Offset += RHS->getZExtValue();
7776         Scale = SubScale;
7777         return SubVal;
7778       }
7779     }
7780   }
7781
7782   // Otherwise, we can't look past this.
7783   Scale = 1;
7784   Offset = 0;
7785   return Val;
7786 }
7787
7788
7789 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7790 /// try to eliminate the cast by moving the type information into the alloc.
7791 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7792                                                    AllocationInst &AI) {
7793   const PointerType *PTy = cast<PointerType>(CI.getType());
7794   
7795   // Remove any uses of AI that are dead.
7796   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7797   
7798   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7799     Instruction *User = cast<Instruction>(*UI++);
7800     if (isInstructionTriviallyDead(User)) {
7801       while (UI != E && *UI == User)
7802         ++UI; // If this instruction uses AI more than once, don't break UI.
7803       
7804       ++NumDeadInst;
7805       DOUT << "IC: DCE: " << *User;
7806       EraseInstFromFunction(*User);
7807     }
7808   }
7809   
7810   // Get the type really allocated and the type casted to.
7811   const Type *AllocElTy = AI.getAllocatedType();
7812   const Type *CastElTy = PTy->getElementType();
7813   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7814
7815   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7816   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7817   if (CastElTyAlign < AllocElTyAlign) return 0;
7818
7819   // If the allocation has multiple uses, only promote it if we are strictly
7820   // increasing the alignment of the resultant allocation.  If we keep it the
7821   // same, we open the door to infinite loops of various kinds.  (A reference
7822   // from a dbg.declare doesn't count as a use for this purpose.)
7823   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7824       CastElTyAlign == AllocElTyAlign) return 0;
7825
7826   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7827   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7828   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7829
7830   // See if we can satisfy the modulus by pulling a scale out of the array
7831   // size argument.
7832   unsigned ArraySizeScale;
7833   int ArrayOffset;
7834   Value *NumElements = // See if the array size is a decomposable linear expr.
7835     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7836                               ArrayOffset, Context);
7837  
7838   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7839   // do the xform.
7840   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7841       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7842
7843   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7844   Value *Amt = 0;
7845   if (Scale == 1) {
7846     Amt = NumElements;
7847   } else {
7848     // If the allocation size is constant, form a constant mul expression
7849     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7850     if (isa<ConstantInt>(NumElements))
7851       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7852                                  cast<ConstantInt>(Amt));
7853     // otherwise multiply the amount and the number of elements
7854     else {
7855       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7856       Amt = InsertNewInstBefore(Tmp, AI);
7857     }
7858   }
7859   
7860   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7861     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7862     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7863     Amt = InsertNewInstBefore(Tmp, AI);
7864   }
7865   
7866   AllocationInst *New;
7867   if (isa<MallocInst>(AI))
7868     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7869   else
7870     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7871   InsertNewInstBefore(New, AI);
7872   New->takeName(&AI);
7873   
7874   // If the allocation has one real use plus a dbg.declare, just remove the
7875   // declare.
7876   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7877     EraseInstFromFunction(*DI);
7878   }
7879   // If the allocation has multiple real uses, insert a cast and change all
7880   // things that used it to use the new cast.  This will also hack on CI, but it
7881   // will die soon.
7882   else if (!AI.hasOneUse()) {
7883     AddUsesToWorkList(AI);
7884     // New is the allocation instruction, pointer typed. AI is the original
7885     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7886     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7887     InsertNewInstBefore(NewCast, AI);
7888     AI.replaceAllUsesWith(NewCast);
7889   }
7890   return ReplaceInstUsesWith(CI, New);
7891 }
7892
7893 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7894 /// and return it as type Ty without inserting any new casts and without
7895 /// changing the computed value.  This is used by code that tries to decide
7896 /// whether promoting or shrinking integer operations to wider or smaller types
7897 /// will allow us to eliminate a truncate or extend.
7898 ///
7899 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7900 /// extension operation if Ty is larger.
7901 ///
7902 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7903 /// should return true if trunc(V) can be computed by computing V in the smaller
7904 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7905 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7906 /// efficiently truncated.
7907 ///
7908 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7909 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7910 /// the final result.
7911 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7912                                               unsigned CastOpc,
7913                                               int &NumCastsRemoved){
7914   // We can always evaluate constants in another type.
7915   if (isa<Constant>(V))
7916     return true;
7917   
7918   Instruction *I = dyn_cast<Instruction>(V);
7919   if (!I) return false;
7920   
7921   const Type *OrigTy = V->getType();
7922   
7923   // If this is an extension or truncate, we can often eliminate it.
7924   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7925     // If this is a cast from the destination type, we can trivially eliminate
7926     // it, and this will remove a cast overall.
7927     if (I->getOperand(0)->getType() == Ty) {
7928       // If the first operand is itself a cast, and is eliminable, do not count
7929       // this as an eliminable cast.  We would prefer to eliminate those two
7930       // casts first.
7931       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7932         ++NumCastsRemoved;
7933       return true;
7934     }
7935   }
7936
7937   // We can't extend or shrink something that has multiple uses: doing so would
7938   // require duplicating the instruction in general, which isn't profitable.
7939   if (!I->hasOneUse()) return false;
7940
7941   unsigned Opc = I->getOpcode();
7942   switch (Opc) {
7943   case Instruction::Add:
7944   case Instruction::Sub:
7945   case Instruction::Mul:
7946   case Instruction::And:
7947   case Instruction::Or:
7948   case Instruction::Xor:
7949     // These operators can all arbitrarily be extended or truncated.
7950     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951                                       NumCastsRemoved) &&
7952            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7953                                       NumCastsRemoved);
7954
7955   case Instruction::UDiv:
7956   case Instruction::URem: {
7957     // UDiv and URem can be truncated if all the truncated bits are zero.
7958     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7959     uint32_t BitWidth = Ty->getScalarSizeInBits();
7960     if (BitWidth < OrigBitWidth) {
7961       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7962       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7963           MaskedValueIsZero(I->getOperand(1), Mask)) {
7964         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7965                                           NumCastsRemoved) &&
7966                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7967                                           NumCastsRemoved);
7968       }
7969     }
7970     break;
7971   }
7972   case Instruction::Shl:
7973     // If we are truncating the result of this SHL, and if it's a shift of a
7974     // constant amount, we can always perform a SHL in a smaller type.
7975     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7976       uint32_t BitWidth = Ty->getScalarSizeInBits();
7977       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7978           CI->getLimitedValue(BitWidth) < BitWidth)
7979         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7980                                           NumCastsRemoved);
7981     }
7982     break;
7983   case Instruction::LShr:
7984     // If this is a truncate of a logical shr, we can truncate it to a smaller
7985     // lshr iff we know that the bits we would otherwise be shifting in are
7986     // already zeros.
7987     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7988       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7989       uint32_t BitWidth = Ty->getScalarSizeInBits();
7990       if (BitWidth < OrigBitWidth &&
7991           MaskedValueIsZero(I->getOperand(0),
7992             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7993           CI->getLimitedValue(BitWidth) < BitWidth) {
7994         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7995                                           NumCastsRemoved);
7996       }
7997     }
7998     break;
7999   case Instruction::ZExt:
8000   case Instruction::SExt:
8001   case Instruction::Trunc:
8002     // If this is the same kind of case as our original (e.g. zext+zext), we
8003     // can safely replace it.  Note that replacing it does not reduce the number
8004     // of casts in the input.
8005     if (Opc == CastOpc)
8006       return true;
8007
8008     // sext (zext ty1), ty2 -> zext ty2
8009     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8010       return true;
8011     break;
8012   case Instruction::Select: {
8013     SelectInst *SI = cast<SelectInst>(I);
8014     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8015                                       NumCastsRemoved) &&
8016            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8017                                       NumCastsRemoved);
8018   }
8019   case Instruction::PHI: {
8020     // We can change a phi if we can change all operands.
8021     PHINode *PN = cast<PHINode>(I);
8022     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8023       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8024                                       NumCastsRemoved))
8025         return false;
8026     return true;
8027   }
8028   default:
8029     // TODO: Can handle more cases here.
8030     break;
8031   }
8032   
8033   return false;
8034 }
8035
8036 /// EvaluateInDifferentType - Given an expression that 
8037 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8038 /// evaluate the expression.
8039 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8040                                              bool isSigned) {
8041   if (Constant *C = dyn_cast<Constant>(V))
8042     return Context->getConstantExprIntegerCast(C, Ty,
8043                                                isSigned /*Sext or ZExt*/);
8044
8045   // Otherwise, it must be an instruction.
8046   Instruction *I = cast<Instruction>(V);
8047   Instruction *Res = 0;
8048   unsigned Opc = I->getOpcode();
8049   switch (Opc) {
8050   case Instruction::Add:
8051   case Instruction::Sub:
8052   case Instruction::Mul:
8053   case Instruction::And:
8054   case Instruction::Or:
8055   case Instruction::Xor:
8056   case Instruction::AShr:
8057   case Instruction::LShr:
8058   case Instruction::Shl:
8059   case Instruction::UDiv:
8060   case Instruction::URem: {
8061     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8062     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8063     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8064     break;
8065   }    
8066   case Instruction::Trunc:
8067   case Instruction::ZExt:
8068   case Instruction::SExt:
8069     // If the source type of the cast is the type we're trying for then we can
8070     // just return the source.  There's no need to insert it because it is not
8071     // new.
8072     if (I->getOperand(0)->getType() == Ty)
8073       return I->getOperand(0);
8074     
8075     // Otherwise, must be the same type of cast, so just reinsert a new one.
8076     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8077                            Ty);
8078     break;
8079   case Instruction::Select: {
8080     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8081     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8082     Res = SelectInst::Create(I->getOperand(0), True, False);
8083     break;
8084   }
8085   case Instruction::PHI: {
8086     PHINode *OPN = cast<PHINode>(I);
8087     PHINode *NPN = PHINode::Create(Ty);
8088     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8089       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8090       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8091     }
8092     Res = NPN;
8093     break;
8094   }
8095   default: 
8096     // TODO: Can handle more cases here.
8097     llvm_unreachable("Unreachable!");
8098     break;
8099   }
8100   
8101   Res->takeName(I);
8102   return InsertNewInstBefore(Res, *I);
8103 }
8104
8105 /// @brief Implement the transforms common to all CastInst visitors.
8106 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8107   Value *Src = CI.getOperand(0);
8108
8109   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8110   // eliminate it now.
8111   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8112     if (Instruction::CastOps opc = 
8113         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8114       // The first cast (CSrc) is eliminable so we need to fix up or replace
8115       // the second cast (CI). CSrc will then have a good chance of being dead.
8116       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8117     }
8118   }
8119
8120   // If we are casting a select then fold the cast into the select
8121   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8122     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8123       return NV;
8124
8125   // If we are casting a PHI then fold the cast into the PHI
8126   if (isa<PHINode>(Src))
8127     if (Instruction *NV = FoldOpIntoPhi(CI))
8128       return NV;
8129   
8130   return 0;
8131 }
8132
8133 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8134 /// or not there is a sequence of GEP indices into the type that will land us at
8135 /// the specified offset.  If so, fill them into NewIndices and return the
8136 /// resultant element type, otherwise return null.
8137 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8138                                        SmallVectorImpl<Value*> &NewIndices,
8139                                        const TargetData *TD,
8140                                        LLVMContext *Context) {
8141   if (!Ty->isSized()) return 0;
8142   
8143   // Start with the index over the outer type.  Note that the type size
8144   // might be zero (even if the offset isn't zero) if the indexed type
8145   // is something like [0 x {int, int}]
8146   const Type *IntPtrTy = TD->getIntPtrType();
8147   int64_t FirstIdx = 0;
8148   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8149     FirstIdx = Offset/TySize;
8150     Offset -= FirstIdx*TySize;
8151     
8152     // Handle hosts where % returns negative instead of values [0..TySize).
8153     if (Offset < 0) {
8154       --FirstIdx;
8155       Offset += TySize;
8156       assert(Offset >= 0);
8157     }
8158     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8159   }
8160   
8161   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8162     
8163   // Index into the types.  If we fail, set OrigBase to null.
8164   while (Offset) {
8165     // Indexing into tail padding between struct/array elements.
8166     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8167       return 0;
8168     
8169     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8170       const StructLayout *SL = TD->getStructLayout(STy);
8171       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8172              "Offset must stay within the indexed type");
8173       
8174       unsigned Elt = SL->getElementContainingOffset(Offset);
8175       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8176       
8177       Offset -= SL->getElementOffset(Elt);
8178       Ty = STy->getElementType(Elt);
8179     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8180       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8181       assert(EltSize && "Cannot index into a zero-sized array");
8182       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8183       Offset %= EltSize;
8184       Ty = AT->getElementType();
8185     } else {
8186       // Otherwise, we can't index into the middle of this atomic type, bail.
8187       return 0;
8188     }
8189   }
8190   
8191   return Ty;
8192 }
8193
8194 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8195 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8196   Value *Src = CI.getOperand(0);
8197   
8198   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8199     // If casting the result of a getelementptr instruction with no offset, turn
8200     // this into a cast of the original pointer!
8201     if (GEP->hasAllZeroIndices()) {
8202       // Changing the cast operand is usually not a good idea but it is safe
8203       // here because the pointer operand is being replaced with another 
8204       // pointer operand so the opcode doesn't need to change.
8205       AddToWorkList(GEP);
8206       CI.setOperand(0, GEP->getOperand(0));
8207       return &CI;
8208     }
8209     
8210     // If the GEP has a single use, and the base pointer is a bitcast, and the
8211     // GEP computes a constant offset, see if we can convert these three
8212     // instructions into fewer.  This typically happens with unions and other
8213     // non-type-safe code.
8214     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8215       if (GEP->hasAllConstantIndices()) {
8216         // We are guaranteed to get a constant from EmitGEPOffset.
8217         ConstantInt *OffsetV =
8218                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8219         int64_t Offset = OffsetV->getSExtValue();
8220         
8221         // Get the base pointer input of the bitcast, and the type it points to.
8222         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8223         const Type *GEPIdxTy =
8224           cast<PointerType>(OrigBase->getType())->getElementType();
8225         SmallVector<Value*, 8> NewIndices;
8226         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8227           // If we were able to index down into an element, create the GEP
8228           // and bitcast the result.  This eliminates one bitcast, potentially
8229           // two.
8230           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8231                                                         NewIndices.begin(),
8232                                                         NewIndices.end(), "");
8233           InsertNewInstBefore(NGEP, CI);
8234           NGEP->takeName(GEP);
8235           
8236           if (isa<BitCastInst>(CI))
8237             return new BitCastInst(NGEP, CI.getType());
8238           assert(isa<PtrToIntInst>(CI));
8239           return new PtrToIntInst(NGEP, CI.getType());
8240         }
8241       }      
8242     }
8243   }
8244     
8245   return commonCastTransforms(CI);
8246 }
8247
8248 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8249 /// type like i42.  We don't want to introduce operations on random non-legal
8250 /// integer types where they don't already exist in the code.  In the future,
8251 /// we should consider making this based off target-data, so that 32-bit targets
8252 /// won't get i64 operations etc.
8253 static bool isSafeIntegerType(const Type *Ty) {
8254   switch (Ty->getPrimitiveSizeInBits()) {
8255   case 8:
8256   case 16:
8257   case 32:
8258   case 64:
8259     return true;
8260   default: 
8261     return false;
8262   }
8263 }
8264
8265 /// commonIntCastTransforms - This function implements the common transforms
8266 /// for trunc, zext, and sext.
8267 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8268   if (Instruction *Result = commonCastTransforms(CI))
8269     return Result;
8270
8271   Value *Src = CI.getOperand(0);
8272   const Type *SrcTy = Src->getType();
8273   const Type *DestTy = CI.getType();
8274   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8275   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8276
8277   // See if we can simplify any instructions used by the LHS whose sole 
8278   // purpose is to compute bits we don't care about.
8279   if (SimplifyDemandedInstructionBits(CI))
8280     return &CI;
8281
8282   // If the source isn't an instruction or has more than one use then we
8283   // can't do anything more. 
8284   Instruction *SrcI = dyn_cast<Instruction>(Src);
8285   if (!SrcI || !Src->hasOneUse())
8286     return 0;
8287
8288   // Attempt to propagate the cast into the instruction for int->int casts.
8289   int NumCastsRemoved = 0;
8290   // Only do this if the dest type is a simple type, don't convert the
8291   // expression tree to something weird like i93 unless the source is also
8292   // strange.
8293   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8294        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8295       CanEvaluateInDifferentType(SrcI, DestTy,
8296                                  CI.getOpcode(), NumCastsRemoved)) {
8297     // If this cast is a truncate, evaluting in a different type always
8298     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8299     // we need to do an AND to maintain the clear top-part of the computation,
8300     // so we require that the input have eliminated at least one cast.  If this
8301     // is a sign extension, we insert two new casts (to do the extension) so we
8302     // require that two casts have been eliminated.
8303     bool DoXForm = false;
8304     bool JustReplace = false;
8305     switch (CI.getOpcode()) {
8306     default:
8307       // All the others use floating point so we shouldn't actually 
8308       // get here because of the check above.
8309       llvm_unreachable("Unknown cast type");
8310     case Instruction::Trunc:
8311       DoXForm = true;
8312       break;
8313     case Instruction::ZExt: {
8314       DoXForm = NumCastsRemoved >= 1;
8315       if (!DoXForm && 0) {
8316         // If it's unnecessary to issue an AND to clear the high bits, it's
8317         // always profitable to do this xform.
8318         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8319         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8320         if (MaskedValueIsZero(TryRes, Mask))
8321           return ReplaceInstUsesWith(CI, TryRes);
8322         
8323         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8324           if (TryI->use_empty())
8325             EraseInstFromFunction(*TryI);
8326       }
8327       break;
8328     }
8329     case Instruction::SExt: {
8330       DoXForm = NumCastsRemoved >= 2;
8331       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8332         // If we do not have to emit the truncate + sext pair, then it's always
8333         // profitable to do this xform.
8334         //
8335         // It's not safe to eliminate the trunc + sext pair if one of the
8336         // eliminated cast is a truncate. e.g.
8337         // t2 = trunc i32 t1 to i16
8338         // t3 = sext i16 t2 to i32
8339         // !=
8340         // i32 t1
8341         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8342         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8343         if (NumSignBits > (DestBitSize - SrcBitSize))
8344           return ReplaceInstUsesWith(CI, TryRes);
8345         
8346         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8347           if (TryI->use_empty())
8348             EraseInstFromFunction(*TryI);
8349       }
8350       break;
8351     }
8352     }
8353     
8354     if (DoXForm) {
8355       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8356            << " cast: " << CI;
8357       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8358                                            CI.getOpcode() == Instruction::SExt);
8359       if (JustReplace)
8360         // Just replace this cast with the result.
8361         return ReplaceInstUsesWith(CI, Res);
8362
8363       assert(Res->getType() == DestTy);
8364       switch (CI.getOpcode()) {
8365       default: llvm_unreachable("Unknown cast type!");
8366       case Instruction::Trunc:
8367         // Just replace this cast with the result.
8368         return ReplaceInstUsesWith(CI, Res);
8369       case Instruction::ZExt: {
8370         assert(SrcBitSize < DestBitSize && "Not a zext?");
8371
8372         // If the high bits are already zero, just replace this cast with the
8373         // result.
8374         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8375         if (MaskedValueIsZero(Res, Mask))
8376           return ReplaceInstUsesWith(CI, Res);
8377
8378         // We need to emit an AND to clear the high bits.
8379         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8380                                                             SrcBitSize));
8381         return BinaryOperator::CreateAnd(Res, C);
8382       }
8383       case Instruction::SExt: {
8384         // If the high bits are already filled with sign bit, just replace this
8385         // cast with the result.
8386         unsigned NumSignBits = ComputeNumSignBits(Res);
8387         if (NumSignBits > (DestBitSize - SrcBitSize))
8388           return ReplaceInstUsesWith(CI, Res);
8389
8390         // We need to emit a cast to truncate, then a cast to sext.
8391         return CastInst::Create(Instruction::SExt,
8392             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8393                              CI), DestTy);
8394       }
8395       }
8396     }
8397   }
8398   
8399   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8400   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8401
8402   switch (SrcI->getOpcode()) {
8403   case Instruction::Add:
8404   case Instruction::Mul:
8405   case Instruction::And:
8406   case Instruction::Or:
8407   case Instruction::Xor:
8408     // If we are discarding information, rewrite.
8409     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8410       // Don't insert two casts unless at least one can be eliminated.
8411       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8412           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8413         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8414         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8415         return BinaryOperator::Create(
8416             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8417       }
8418     }
8419
8420     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8421     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8422         SrcI->getOpcode() == Instruction::Xor &&
8423         Op1 == Context->getConstantIntTrue() &&
8424         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8425       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8426       return BinaryOperator::CreateXor(New,
8427                                       Context->getConstantInt(CI.getType(), 1));
8428     }
8429     break;
8430
8431   case Instruction::Shl: {
8432     // Canonicalize trunc inside shl, if we can.
8433     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8434     if (CI && DestBitSize < SrcBitSize &&
8435         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8436       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8437       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8438       return BinaryOperator::CreateShl(Op0c, Op1c);
8439     }
8440     break;
8441   }
8442   }
8443   return 0;
8444 }
8445
8446 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8447   if (Instruction *Result = commonIntCastTransforms(CI))
8448     return Result;
8449   
8450   Value *Src = CI.getOperand(0);
8451   const Type *Ty = CI.getType();
8452   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8453   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8454
8455   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8456   if (DestBitWidth == 1 &&
8457       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8458     Constant *One = Context->getConstantInt(Src->getType(), 1);
8459     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8460     Value *Zero = Context->getNullValue(Src->getType());
8461     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8462   }
8463
8464   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8465   ConstantInt *ShAmtV = 0;
8466   Value *ShiftOp = 0;
8467   if (Src->hasOneUse() &&
8468       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8469     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8470     
8471     // Get a mask for the bits shifting in.
8472     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8473     if (MaskedValueIsZero(ShiftOp, Mask)) {
8474       if (ShAmt >= DestBitWidth)        // All zeros.
8475         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8476       
8477       // Okay, we can shrink this.  Truncate the input, then return a new
8478       // shift.
8479       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8480       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8481       return BinaryOperator::CreateLShr(V1, V2);
8482     }
8483   }
8484   
8485   return 0;
8486 }
8487
8488 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8489 /// in order to eliminate the icmp.
8490 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8491                                              bool DoXform) {
8492   // If we are just checking for a icmp eq of a single bit and zext'ing it
8493   // to an integer, then shift the bit to the appropriate place and then
8494   // cast to integer to avoid the comparison.
8495   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8496     const APInt &Op1CV = Op1C->getValue();
8497       
8498     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8499     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8500     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8501         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8502       if (!DoXform) return ICI;
8503
8504       Value *In = ICI->getOperand(0);
8505       Value *Sh = Context->getConstantInt(In->getType(),
8506                                    In->getType()->getScalarSizeInBits()-1);
8507       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8508                                                         In->getName()+".lobit"),
8509                                CI);
8510       if (In->getType() != CI.getType())
8511         In = CastInst::CreateIntegerCast(In, CI.getType(),
8512                                          false/*ZExt*/, "tmp", &CI);
8513
8514       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8515         Constant *One = Context->getConstantInt(In->getType(), 1);
8516         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8517                                                          In->getName()+".not"),
8518                                  CI);
8519       }
8520
8521       return ReplaceInstUsesWith(CI, In);
8522     }
8523       
8524       
8525       
8526     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8527     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8528     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8529     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8530     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8531     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8532     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8533     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8534     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8535         // This only works for EQ and NE
8536         ICI->isEquality()) {
8537       // If Op1C some other power of two, convert:
8538       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8539       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8540       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8541       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8542         
8543       APInt KnownZeroMask(~KnownZero);
8544       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8545         if (!DoXform) return ICI;
8546
8547         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8548         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8549           // (X&4) == 2 --> false
8550           // (X&4) != 2 --> true
8551           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8552           Res = Context->getConstantExprZExt(Res, CI.getType());
8553           return ReplaceInstUsesWith(CI, Res);
8554         }
8555           
8556         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8557         Value *In = ICI->getOperand(0);
8558         if (ShiftAmt) {
8559           // Perform a logical shr by shiftamt.
8560           // Insert the shift to put the result in the low bit.
8561           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8562                               Context->getConstantInt(In->getType(), ShiftAmt),
8563                                                    In->getName()+".lobit"), CI);
8564         }
8565           
8566         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8567           Constant *One = Context->getConstantInt(In->getType(), 1);
8568           In = BinaryOperator::CreateXor(In, One, "tmp");
8569           InsertNewInstBefore(cast<Instruction>(In), CI);
8570         }
8571           
8572         if (CI.getType() == In->getType())
8573           return ReplaceInstUsesWith(CI, In);
8574         else
8575           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8576       }
8577     }
8578   }
8579
8580   return 0;
8581 }
8582
8583 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8584   // If one of the common conversion will work ..
8585   if (Instruction *Result = commonIntCastTransforms(CI))
8586     return Result;
8587
8588   Value *Src = CI.getOperand(0);
8589
8590   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8591   // types and if the sizes are just right we can convert this into a logical
8592   // 'and' which will be much cheaper than the pair of casts.
8593   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8594     // Get the sizes of the types involved.  We know that the intermediate type
8595     // will be smaller than A or C, but don't know the relation between A and C.
8596     Value *A = CSrc->getOperand(0);
8597     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8598     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8599     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8600     // If we're actually extending zero bits, then if
8601     // SrcSize <  DstSize: zext(a & mask)
8602     // SrcSize == DstSize: a & mask
8603     // SrcSize  > DstSize: trunc(a) & mask
8604     if (SrcSize < DstSize) {
8605       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8606       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8607       Instruction *And =
8608         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8609       InsertNewInstBefore(And, CI);
8610       return new ZExtInst(And, CI.getType());
8611     } else if (SrcSize == DstSize) {
8612       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8613       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8614                                                            AndValue));
8615     } else if (SrcSize > DstSize) {
8616       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8617       InsertNewInstBefore(Trunc, CI);
8618       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8619       return BinaryOperator::CreateAnd(Trunc, 
8620                                        Context->getConstantInt(Trunc->getType(),
8621                                                                AndValue));
8622     }
8623   }
8624
8625   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8626     return transformZExtICmp(ICI, CI);
8627
8628   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8629   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8630     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8631     // of the (zext icmp) will be transformed.
8632     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8633     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8634     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8635         (transformZExtICmp(LHS, CI, false) ||
8636          transformZExtICmp(RHS, CI, false))) {
8637       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8638       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8639       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8640     }
8641   }
8642
8643   // zext(trunc(t) & C) -> (t & zext(C)).
8644   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8645     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8646       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8647         Value *TI0 = TI->getOperand(0);
8648         if (TI0->getType() == CI.getType())
8649           return
8650             BinaryOperator::CreateAnd(TI0,
8651                                 Context->getConstantExprZExt(C, CI.getType()));
8652       }
8653
8654   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8655   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8656     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8657       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8658         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8659             And->getOperand(1) == C)
8660           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8661             Value *TI0 = TI->getOperand(0);
8662             if (TI0->getType() == CI.getType()) {
8663               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8664               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8665               InsertNewInstBefore(NewAnd, *And);
8666               return BinaryOperator::CreateXor(NewAnd, ZC);
8667             }
8668           }
8669
8670   return 0;
8671 }
8672
8673 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8674   if (Instruction *I = commonIntCastTransforms(CI))
8675     return I;
8676   
8677   Value *Src = CI.getOperand(0);
8678   
8679   // Canonicalize sign-extend from i1 to a select.
8680   if (Src->getType() == Type::Int1Ty)
8681     return SelectInst::Create(Src,
8682                               Context->getAllOnesValue(CI.getType()),
8683                               Context->getNullValue(CI.getType()));
8684
8685   // See if the value being truncated is already sign extended.  If so, just
8686   // eliminate the trunc/sext pair.
8687   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8688     Value *Op = cast<User>(Src)->getOperand(0);
8689     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8690     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8691     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8692     unsigned NumSignBits = ComputeNumSignBits(Op);
8693
8694     if (OpBits == DestBits) {
8695       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8696       // bits, it is already ready.
8697       if (NumSignBits > DestBits-MidBits)
8698         return ReplaceInstUsesWith(CI, Op);
8699     } else if (OpBits < DestBits) {
8700       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8701       // bits, just sext from i32.
8702       if (NumSignBits > OpBits-MidBits)
8703         return new SExtInst(Op, CI.getType(), "tmp");
8704     } else {
8705       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8706       // bits, just truncate to i32.
8707       if (NumSignBits > OpBits-MidBits)
8708         return new TruncInst(Op, CI.getType(), "tmp");
8709     }
8710   }
8711
8712   // If the input is a shl/ashr pair of a same constant, then this is a sign
8713   // extension from a smaller value.  If we could trust arbitrary bitwidth
8714   // integers, we could turn this into a truncate to the smaller bit and then
8715   // use a sext for the whole extension.  Since we don't, look deeper and check
8716   // for a truncate.  If the source and dest are the same type, eliminate the
8717   // trunc and extend and just do shifts.  For example, turn:
8718   //   %a = trunc i32 %i to i8
8719   //   %b = shl i8 %a, 6
8720   //   %c = ashr i8 %b, 6
8721   //   %d = sext i8 %c to i32
8722   // into:
8723   //   %a = shl i32 %i, 30
8724   //   %d = ashr i32 %a, 30
8725   Value *A = 0;
8726   ConstantInt *BA = 0, *CA = 0;
8727   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8728                         m_ConstantInt(CA)), *Context) &&
8729       BA == CA && isa<TruncInst>(A)) {
8730     Value *I = cast<TruncInst>(A)->getOperand(0);
8731     if (I->getType() == CI.getType()) {
8732       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8733       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8734       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8735       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8736       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8737                                                         CI.getName()), CI);
8738       return BinaryOperator::CreateAShr(I, ShAmtV);
8739     }
8740   }
8741   
8742   return 0;
8743 }
8744
8745 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8746 /// in the specified FP type without changing its value.
8747 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8748                               LLVMContext *Context) {
8749   bool losesInfo;
8750   APFloat F = CFP->getValueAPF();
8751   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8752   if (!losesInfo)
8753     return Context->getConstantFP(F);
8754   return 0;
8755 }
8756
8757 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8758 /// through it until we get the source value.
8759 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8760   if (Instruction *I = dyn_cast<Instruction>(V))
8761     if (I->getOpcode() == Instruction::FPExt)
8762       return LookThroughFPExtensions(I->getOperand(0), Context);
8763   
8764   // If this value is a constant, return the constant in the smallest FP type
8765   // that can accurately represent it.  This allows us to turn
8766   // (float)((double)X+2.0) into x+2.0f.
8767   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8768     if (CFP->getType() == Type::PPC_FP128Ty)
8769       return V;  // No constant folding of this.
8770     // See if the value can be truncated to float and then reextended.
8771     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8772       return V;
8773     if (CFP->getType() == Type::DoubleTy)
8774       return V;  // Won't shrink.
8775     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8776       return V;
8777     // Don't try to shrink to various long double types.
8778   }
8779   
8780   return V;
8781 }
8782
8783 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8784   if (Instruction *I = commonCastTransforms(CI))
8785     return I;
8786   
8787   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8788   // smaller than the destination type, we can eliminate the truncate by doing
8789   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8790   // many builtins (sqrt, etc).
8791   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8792   if (OpI && OpI->hasOneUse()) {
8793     switch (OpI->getOpcode()) {
8794     default: break;
8795     case Instruction::FAdd:
8796     case Instruction::FSub:
8797     case Instruction::FMul:
8798     case Instruction::FDiv:
8799     case Instruction::FRem:
8800       const Type *SrcTy = OpI->getType();
8801       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8802       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8803       if (LHSTrunc->getType() != SrcTy && 
8804           RHSTrunc->getType() != SrcTy) {
8805         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8806         // If the source types were both smaller than the destination type of
8807         // the cast, do this xform.
8808         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8809             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8810           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8811                                       CI.getType(), CI);
8812           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8813                                       CI.getType(), CI);
8814           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8815         }
8816       }
8817       break;  
8818     }
8819   }
8820   return 0;
8821 }
8822
8823 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8824   return commonCastTransforms(CI);
8825 }
8826
8827 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8828   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8829   if (OpI == 0)
8830     return commonCastTransforms(FI);
8831
8832   // fptoui(uitofp(X)) --> X
8833   // fptoui(sitofp(X)) --> X
8834   // This is safe if the intermediate type has enough bits in its mantissa to
8835   // accurately represent all values of X.  For example, do not do this with
8836   // i64->float->i64.  This is also safe for sitofp case, because any negative
8837   // 'X' value would cause an undefined result for the fptoui. 
8838   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8839       OpI->getOperand(0)->getType() == FI.getType() &&
8840       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8841                     OpI->getType()->getFPMantissaWidth())
8842     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8843
8844   return commonCastTransforms(FI);
8845 }
8846
8847 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8848   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8849   if (OpI == 0)
8850     return commonCastTransforms(FI);
8851   
8852   // fptosi(sitofp(X)) --> X
8853   // fptosi(uitofp(X)) --> X
8854   // This is safe if the intermediate type has enough bits in its mantissa to
8855   // accurately represent all values of X.  For example, do not do this with
8856   // i64->float->i64.  This is also safe for sitofp case, because any negative
8857   // 'X' value would cause an undefined result for the fptoui. 
8858   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8859       OpI->getOperand(0)->getType() == FI.getType() &&
8860       (int)FI.getType()->getScalarSizeInBits() <=
8861                     OpI->getType()->getFPMantissaWidth())
8862     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8863   
8864   return commonCastTransforms(FI);
8865 }
8866
8867 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8868   return commonCastTransforms(CI);
8869 }
8870
8871 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8872   return commonCastTransforms(CI);
8873 }
8874
8875 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8876   // If the destination integer type is smaller than the intptr_t type for
8877   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8878   // trunc to be exposed to other transforms.  Don't do this for extending
8879   // ptrtoint's, because we don't know if the target sign or zero extends its
8880   // pointers.
8881   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8882     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8883                                                     TD->getIntPtrType(),
8884                                                     "tmp"), CI);
8885     return new TruncInst(P, CI.getType());
8886   }
8887   
8888   return commonPointerCastTransforms(CI);
8889 }
8890
8891 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8892   // If the source integer type is larger than the intptr_t type for
8893   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8894   // allows the trunc to be exposed to other transforms.  Don't do this for
8895   // extending inttoptr's, because we don't know if the target sign or zero
8896   // extends to pointers.
8897   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8898       TD->getPointerSizeInBits()) {
8899     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8900                                                  TD->getIntPtrType(),
8901                                                  "tmp"), CI);
8902     return new IntToPtrInst(P, CI.getType());
8903   }
8904   
8905   if (Instruction *I = commonCastTransforms(CI))
8906     return I;
8907   
8908   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8909   if (!DestPointee->isSized()) return 0;
8910
8911   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8912   ConstantInt *Cst;
8913   Value *X;
8914   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8915                                     m_ConstantInt(Cst)), *Context)) {
8916     // If the source and destination operands have the same type, see if this
8917     // is a single-index GEP.
8918     if (X->getType() == CI.getType()) {
8919       // Get the size of the pointee type.
8920       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8921
8922       // Convert the constant to intptr type.
8923       APInt Offset = Cst->getValue();
8924       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8925
8926       // If Offset is evenly divisible by Size, we can do this xform.
8927       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8928         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8929         GetElementPtrInst *GEP =
8930           GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8931         // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8932         // potentially overflow, in the absense of further analysis.
8933         cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8934         return GEP;
8935       }
8936     }
8937     // TODO: Could handle other cases, e.g. where add is indexing into field of
8938     // struct etc.
8939   } else if (CI.getOperand(0)->hasOneUse() &&
8940              match(CI.getOperand(0), m_Add(m_Value(X),
8941                    m_ConstantInt(Cst)), *Context)) {
8942     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8943     // "inttoptr+GEP" instead of "add+intptr".
8944     
8945     // Get the size of the pointee type.
8946     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8947     
8948     // Convert the constant to intptr type.
8949     APInt Offset = Cst->getValue();
8950     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8951     
8952     // If Offset is evenly divisible by Size, we can do this xform.
8953     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8954       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8955       
8956       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8957                                                             "tmp"), CI);
8958       GetElementPtrInst *GEP =
8959         GetElementPtrInst::Create(P, Context->getConstantInt(Offset), "tmp");
8960       // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8961       // potentially overflow, in the absense of further analysis.
8962       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8963       return GEP;
8964     }
8965   }
8966   return 0;
8967 }
8968
8969 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8970   // If the operands are integer typed then apply the integer transforms,
8971   // otherwise just apply the common ones.
8972   Value *Src = CI.getOperand(0);
8973   const Type *SrcTy = Src->getType();
8974   const Type *DestTy = CI.getType();
8975
8976   if (isa<PointerType>(SrcTy)) {
8977     if (Instruction *I = commonPointerCastTransforms(CI))
8978       return I;
8979   } else {
8980     if (Instruction *Result = commonCastTransforms(CI))
8981       return Result;
8982   }
8983
8984
8985   // Get rid of casts from one type to the same type. These are useless and can
8986   // be replaced by the operand.
8987   if (DestTy == Src->getType())
8988     return ReplaceInstUsesWith(CI, Src);
8989
8990   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8991     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8992     const Type *DstElTy = DstPTy->getElementType();
8993     const Type *SrcElTy = SrcPTy->getElementType();
8994     
8995     // If the address spaces don't match, don't eliminate the bitcast, which is
8996     // required for changing types.
8997     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8998       return 0;
8999     
9000     // If we are casting a malloc or alloca to a pointer to a type of the same
9001     // size, rewrite the allocation instruction to allocate the "right" type.
9002     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9003       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9004         return V;
9005     
9006     // If the source and destination are pointers, and this cast is equivalent
9007     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9008     // This can enhance SROA and other transforms that want type-safe pointers.
9009     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9010     unsigned NumZeros = 0;
9011     while (SrcElTy != DstElTy && 
9012            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9013            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9014       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9015       ++NumZeros;
9016     }
9017
9018     // If we found a path from the src to dest, create the getelementptr now.
9019     if (SrcElTy == DstElTy) {
9020       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9021       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9022                                        ((Instruction*) NULL));
9023     }
9024   }
9025
9026   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9027     if (SVI->hasOneUse()) {
9028       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9029       // a bitconvert to a vector with the same # elts.
9030       if (isa<VectorType>(DestTy) && 
9031           cast<VectorType>(DestTy)->getNumElements() ==
9032                 SVI->getType()->getNumElements() &&
9033           SVI->getType()->getNumElements() ==
9034             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9035         CastInst *Tmp;
9036         // If either of the operands is a cast from CI.getType(), then
9037         // evaluating the shuffle in the casted destination's type will allow
9038         // us to eliminate at least one cast.
9039         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9040              Tmp->getOperand(0)->getType() == DestTy) ||
9041             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9042              Tmp->getOperand(0)->getType() == DestTy)) {
9043           Value *LHS = InsertCastBefore(Instruction::BitCast,
9044                                         SVI->getOperand(0), DestTy, CI);
9045           Value *RHS = InsertCastBefore(Instruction::BitCast,
9046                                         SVI->getOperand(1), DestTy, CI);
9047           // Return a new shuffle vector.  Use the same element ID's, as we
9048           // know the vector types match #elts.
9049           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9050         }
9051       }
9052     }
9053   }
9054   return 0;
9055 }
9056
9057 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9058 ///   %C = or %A, %B
9059 ///   %D = select %cond, %C, %A
9060 /// into:
9061 ///   %C = select %cond, %B, 0
9062 ///   %D = or %A, %C
9063 ///
9064 /// Assuming that the specified instruction is an operand to the select, return
9065 /// a bitmask indicating which operands of this instruction are foldable if they
9066 /// equal the other incoming value of the select.
9067 ///
9068 static unsigned GetSelectFoldableOperands(Instruction *I) {
9069   switch (I->getOpcode()) {
9070   case Instruction::Add:
9071   case Instruction::Mul:
9072   case Instruction::And:
9073   case Instruction::Or:
9074   case Instruction::Xor:
9075     return 3;              // Can fold through either operand.
9076   case Instruction::Sub:   // Can only fold on the amount subtracted.
9077   case Instruction::Shl:   // Can only fold on the shift amount.
9078   case Instruction::LShr:
9079   case Instruction::AShr:
9080     return 1;
9081   default:
9082     return 0;              // Cannot fold
9083   }
9084 }
9085
9086 /// GetSelectFoldableConstant - For the same transformation as the previous
9087 /// function, return the identity constant that goes into the select.
9088 static Constant *GetSelectFoldableConstant(Instruction *I,
9089                                            LLVMContext *Context) {
9090   switch (I->getOpcode()) {
9091   default: llvm_unreachable("This cannot happen!");
9092   case Instruction::Add:
9093   case Instruction::Sub:
9094   case Instruction::Or:
9095   case Instruction::Xor:
9096   case Instruction::Shl:
9097   case Instruction::LShr:
9098   case Instruction::AShr:
9099     return Context->getNullValue(I->getType());
9100   case Instruction::And:
9101     return Context->getAllOnesValue(I->getType());
9102   case Instruction::Mul:
9103     return Context->getConstantInt(I->getType(), 1);
9104   }
9105 }
9106
9107 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9108 /// have the same opcode and only one use each.  Try to simplify this.
9109 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9110                                           Instruction *FI) {
9111   if (TI->getNumOperands() == 1) {
9112     // If this is a non-volatile load or a cast from the same type,
9113     // merge.
9114     if (TI->isCast()) {
9115       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9116         return 0;
9117     } else {
9118       return 0;  // unknown unary op.
9119     }
9120
9121     // Fold this by inserting a select from the input values.
9122     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9123                                            FI->getOperand(0), SI.getName()+".v");
9124     InsertNewInstBefore(NewSI, SI);
9125     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9126                             TI->getType());
9127   }
9128
9129   // Only handle binary operators here.
9130   if (!isa<BinaryOperator>(TI))
9131     return 0;
9132
9133   // Figure out if the operations have any operands in common.
9134   Value *MatchOp, *OtherOpT, *OtherOpF;
9135   bool MatchIsOpZero;
9136   if (TI->getOperand(0) == FI->getOperand(0)) {
9137     MatchOp  = TI->getOperand(0);
9138     OtherOpT = TI->getOperand(1);
9139     OtherOpF = FI->getOperand(1);
9140     MatchIsOpZero = true;
9141   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9142     MatchOp  = TI->getOperand(1);
9143     OtherOpT = TI->getOperand(0);
9144     OtherOpF = FI->getOperand(0);
9145     MatchIsOpZero = false;
9146   } else if (!TI->isCommutative()) {
9147     return 0;
9148   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9149     MatchOp  = TI->getOperand(0);
9150     OtherOpT = TI->getOperand(1);
9151     OtherOpF = FI->getOperand(0);
9152     MatchIsOpZero = true;
9153   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9154     MatchOp  = TI->getOperand(1);
9155     OtherOpT = TI->getOperand(0);
9156     OtherOpF = FI->getOperand(1);
9157     MatchIsOpZero = true;
9158   } else {
9159     return 0;
9160   }
9161
9162   // If we reach here, they do have operations in common.
9163   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9164                                          OtherOpF, SI.getName()+".v");
9165   InsertNewInstBefore(NewSI, SI);
9166
9167   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9168     if (MatchIsOpZero)
9169       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9170     else
9171       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9172   }
9173   llvm_unreachable("Shouldn't get here");
9174   return 0;
9175 }
9176
9177 static bool isSelect01(Constant *C1, Constant *C2) {
9178   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9179   if (!C1I)
9180     return false;
9181   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9182   if (!C2I)
9183     return false;
9184   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9185 }
9186
9187 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9188 /// facilitate further optimization.
9189 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9190                                             Value *FalseVal) {
9191   // See the comment above GetSelectFoldableOperands for a description of the
9192   // transformation we are doing here.
9193   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9194     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9195         !isa<Constant>(FalseVal)) {
9196       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9197         unsigned OpToFold = 0;
9198         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9199           OpToFold = 1;
9200         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9201           OpToFold = 2;
9202         }
9203
9204         if (OpToFold) {
9205           Constant *C = GetSelectFoldableConstant(TVI, Context);
9206           Value *OOp = TVI->getOperand(2-OpToFold);
9207           // Avoid creating select between 2 constants unless it's selecting
9208           // between 0 and 1.
9209           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9210             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9211             InsertNewInstBefore(NewSel, SI);
9212             NewSel->takeName(TVI);
9213             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9214               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9215             llvm_unreachable("Unknown instruction!!");
9216           }
9217         }
9218       }
9219     }
9220   }
9221
9222   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9223     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9224         !isa<Constant>(TrueVal)) {
9225       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9226         unsigned OpToFold = 0;
9227         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9228           OpToFold = 1;
9229         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9230           OpToFold = 2;
9231         }
9232
9233         if (OpToFold) {
9234           Constant *C = GetSelectFoldableConstant(FVI, Context);
9235           Value *OOp = FVI->getOperand(2-OpToFold);
9236           // Avoid creating select between 2 constants unless it's selecting
9237           // between 0 and 1.
9238           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9239             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9240             InsertNewInstBefore(NewSel, SI);
9241             NewSel->takeName(FVI);
9242             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9243               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9244             llvm_unreachable("Unknown instruction!!");
9245           }
9246         }
9247       }
9248     }
9249   }
9250
9251   return 0;
9252 }
9253
9254 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9255 /// ICmpInst as its first operand.
9256 ///
9257 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9258                                                    ICmpInst *ICI) {
9259   bool Changed = false;
9260   ICmpInst::Predicate Pred = ICI->getPredicate();
9261   Value *CmpLHS = ICI->getOperand(0);
9262   Value *CmpRHS = ICI->getOperand(1);
9263   Value *TrueVal = SI.getTrueValue();
9264   Value *FalseVal = SI.getFalseValue();
9265
9266   // Check cases where the comparison is with a constant that
9267   // can be adjusted to fit the min/max idiom. We may edit ICI in
9268   // place here, so make sure the select is the only user.
9269   if (ICI->hasOneUse())
9270     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9271       switch (Pred) {
9272       default: break;
9273       case ICmpInst::ICMP_ULT:
9274       case ICmpInst::ICMP_SLT: {
9275         // X < MIN ? T : F  -->  F
9276         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9277           return ReplaceInstUsesWith(SI, FalseVal);
9278         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9279         Constant *AdjustedRHS = SubOne(CI, Context);
9280         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9281             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9282           Pred = ICmpInst::getSwappedPredicate(Pred);
9283           CmpRHS = AdjustedRHS;
9284           std::swap(FalseVal, TrueVal);
9285           ICI->setPredicate(Pred);
9286           ICI->setOperand(1, CmpRHS);
9287           SI.setOperand(1, TrueVal);
9288           SI.setOperand(2, FalseVal);
9289           Changed = true;
9290         }
9291         break;
9292       }
9293       case ICmpInst::ICMP_UGT:
9294       case ICmpInst::ICMP_SGT: {
9295         // X > MAX ? T : F  -->  F
9296         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9297           return ReplaceInstUsesWith(SI, FalseVal);
9298         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9299         Constant *AdjustedRHS = AddOne(CI, Context);
9300         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9301             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9302           Pred = ICmpInst::getSwappedPredicate(Pred);
9303           CmpRHS = AdjustedRHS;
9304           std::swap(FalseVal, TrueVal);
9305           ICI->setPredicate(Pred);
9306           ICI->setOperand(1, CmpRHS);
9307           SI.setOperand(1, TrueVal);
9308           SI.setOperand(2, FalseVal);
9309           Changed = true;
9310         }
9311         break;
9312       }
9313       }
9314
9315       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9316       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9317       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9318       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9319           match(FalseVal, m_ConstantInt<0>(), *Context))
9320         Pred = ICI->getPredicate();
9321       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9322                match(FalseVal, m_ConstantInt<-1>(), *Context))
9323         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9324       
9325       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9326         // If we are just checking for a icmp eq of a single bit and zext'ing it
9327         // to an integer, then shift the bit to the appropriate place and then
9328         // cast to integer to avoid the comparison.
9329         const APInt &Op1CV = CI->getValue();
9330     
9331         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9332         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9333         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9334             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9335           Value *In = ICI->getOperand(0);
9336           Value *Sh = Context->getConstantInt(In->getType(),
9337                                        In->getType()->getScalarSizeInBits()-1);
9338           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9339                                                           In->getName()+".lobit"),
9340                                    *ICI);
9341           if (In->getType() != SI.getType())
9342             In = CastInst::CreateIntegerCast(In, SI.getType(),
9343                                              true/*SExt*/, "tmp", ICI);
9344     
9345           if (Pred == ICmpInst::ICMP_SGT)
9346             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9347                                        In->getName()+".not"), *ICI);
9348     
9349           return ReplaceInstUsesWith(SI, In);
9350         }
9351       }
9352     }
9353
9354   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9355     // Transform (X == Y) ? X : Y  -> Y
9356     if (Pred == ICmpInst::ICMP_EQ)
9357       return ReplaceInstUsesWith(SI, FalseVal);
9358     // Transform (X != Y) ? X : Y  -> X
9359     if (Pred == ICmpInst::ICMP_NE)
9360       return ReplaceInstUsesWith(SI, TrueVal);
9361     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9362
9363   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9364     // Transform (X == Y) ? Y : X  -> X
9365     if (Pred == ICmpInst::ICMP_EQ)
9366       return ReplaceInstUsesWith(SI, FalseVal);
9367     // Transform (X != Y) ? Y : X  -> Y
9368     if (Pred == ICmpInst::ICMP_NE)
9369       return ReplaceInstUsesWith(SI, TrueVal);
9370     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9371   }
9372
9373   /// NOTE: if we wanted to, this is where to detect integer ABS
9374
9375   return Changed ? &SI : 0;
9376 }
9377
9378 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9379   Value *CondVal = SI.getCondition();
9380   Value *TrueVal = SI.getTrueValue();
9381   Value *FalseVal = SI.getFalseValue();
9382
9383   // select true, X, Y  -> X
9384   // select false, X, Y -> Y
9385   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9386     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9387
9388   // select C, X, X -> X
9389   if (TrueVal == FalseVal)
9390     return ReplaceInstUsesWith(SI, TrueVal);
9391
9392   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9393     return ReplaceInstUsesWith(SI, FalseVal);
9394   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9395     return ReplaceInstUsesWith(SI, TrueVal);
9396   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9397     if (isa<Constant>(TrueVal))
9398       return ReplaceInstUsesWith(SI, TrueVal);
9399     else
9400       return ReplaceInstUsesWith(SI, FalseVal);
9401   }
9402
9403   if (SI.getType() == Type::Int1Ty) {
9404     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9405       if (C->getZExtValue()) {
9406         // Change: A = select B, true, C --> A = or B, C
9407         return BinaryOperator::CreateOr(CondVal, FalseVal);
9408       } else {
9409         // Change: A = select B, false, C --> A = and !B, C
9410         Value *NotCond =
9411           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9412                                              "not."+CondVal->getName()), SI);
9413         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9414       }
9415     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9416       if (C->getZExtValue() == false) {
9417         // Change: A = select B, C, false --> A = and B, C
9418         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9419       } else {
9420         // Change: A = select B, C, true --> A = or !B, C
9421         Value *NotCond =
9422           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9423                                              "not."+CondVal->getName()), SI);
9424         return BinaryOperator::CreateOr(NotCond, TrueVal);
9425       }
9426     }
9427     
9428     // select a, b, a  -> a&b
9429     // select a, a, b  -> a|b
9430     if (CondVal == TrueVal)
9431       return BinaryOperator::CreateOr(CondVal, FalseVal);
9432     else if (CondVal == FalseVal)
9433       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9434   }
9435
9436   // Selecting between two integer constants?
9437   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9438     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9439       // select C, 1, 0 -> zext C to int
9440       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9441         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9442       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9443         // select C, 0, 1 -> zext !C to int
9444         Value *NotCond =
9445           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9446                                                "not."+CondVal->getName()), SI);
9447         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9448       }
9449
9450       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9451         // If one of the constants is zero (we know they can't both be) and we
9452         // have an icmp instruction with zero, and we have an 'and' with the
9453         // non-constant value, eliminate this whole mess.  This corresponds to
9454         // cases like this: ((X & 27) ? 27 : 0)
9455         if (TrueValC->isZero() || FalseValC->isZero())
9456           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9457               cast<Constant>(IC->getOperand(1))->isNullValue())
9458             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9459               if (ICA->getOpcode() == Instruction::And &&
9460                   isa<ConstantInt>(ICA->getOperand(1)) &&
9461                   (ICA->getOperand(1) == TrueValC ||
9462                    ICA->getOperand(1) == FalseValC) &&
9463                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9464                 // Okay, now we know that everything is set up, we just don't
9465                 // know whether we have a icmp_ne or icmp_eq and whether the 
9466                 // true or false val is the zero.
9467                 bool ShouldNotVal = !TrueValC->isZero();
9468                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9469                 Value *V = ICA;
9470                 if (ShouldNotVal)
9471                   V = InsertNewInstBefore(BinaryOperator::Create(
9472                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9473                 return ReplaceInstUsesWith(SI, V);
9474               }
9475       }
9476     }
9477
9478   // See if we are selecting two values based on a comparison of the two values.
9479   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9480     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9481       // Transform (X == Y) ? X : Y  -> Y
9482       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9483         // This is not safe in general for floating point:  
9484         // consider X== -0, Y== +0.
9485         // It becomes safe if either operand is a nonzero constant.
9486         ConstantFP *CFPt, *CFPf;
9487         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9488               !CFPt->getValueAPF().isZero()) ||
9489             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9490              !CFPf->getValueAPF().isZero()))
9491         return ReplaceInstUsesWith(SI, FalseVal);
9492       }
9493       // Transform (X != Y) ? X : Y  -> X
9494       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9495         return ReplaceInstUsesWith(SI, TrueVal);
9496       // NOTE: if we wanted to, this is where to detect MIN/MAX
9497
9498     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9499       // Transform (X == Y) ? Y : X  -> X
9500       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9501         // This is not safe in general for floating point:  
9502         // consider X== -0, Y== +0.
9503         // It becomes safe if either operand is a nonzero constant.
9504         ConstantFP *CFPt, *CFPf;
9505         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9506               !CFPt->getValueAPF().isZero()) ||
9507             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9508              !CFPf->getValueAPF().isZero()))
9509           return ReplaceInstUsesWith(SI, FalseVal);
9510       }
9511       // Transform (X != Y) ? Y : X  -> Y
9512       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9513         return ReplaceInstUsesWith(SI, TrueVal);
9514       // NOTE: if we wanted to, this is where to detect MIN/MAX
9515     }
9516     // NOTE: if we wanted to, this is where to detect ABS
9517   }
9518
9519   // See if we are selecting two values based on a comparison of the two values.
9520   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9521     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9522       return Result;
9523
9524   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9525     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9526       if (TI->hasOneUse() && FI->hasOneUse()) {
9527         Instruction *AddOp = 0, *SubOp = 0;
9528
9529         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9530         if (TI->getOpcode() == FI->getOpcode())
9531           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9532             return IV;
9533
9534         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9535         // even legal for FP.
9536         if ((TI->getOpcode() == Instruction::Sub &&
9537              FI->getOpcode() == Instruction::Add) ||
9538             (TI->getOpcode() == Instruction::FSub &&
9539              FI->getOpcode() == Instruction::FAdd)) {
9540           AddOp = FI; SubOp = TI;
9541         } else if ((FI->getOpcode() == Instruction::Sub &&
9542                     TI->getOpcode() == Instruction::Add) ||
9543                    (FI->getOpcode() == Instruction::FSub &&
9544                     TI->getOpcode() == Instruction::FAdd)) {
9545           AddOp = TI; SubOp = FI;
9546         }
9547
9548         if (AddOp) {
9549           Value *OtherAddOp = 0;
9550           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9551             OtherAddOp = AddOp->getOperand(1);
9552           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9553             OtherAddOp = AddOp->getOperand(0);
9554           }
9555
9556           if (OtherAddOp) {
9557             // So at this point we know we have (Y -> OtherAddOp):
9558             //        select C, (add X, Y), (sub X, Z)
9559             Value *NegVal;  // Compute -Z
9560             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9561               NegVal = Context->getConstantExprNeg(C);
9562             } else {
9563               NegVal = InsertNewInstBefore(
9564                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9565                                               "tmp"), SI);
9566             }
9567
9568             Value *NewTrueOp = OtherAddOp;
9569             Value *NewFalseOp = NegVal;
9570             if (AddOp != TI)
9571               std::swap(NewTrueOp, NewFalseOp);
9572             Instruction *NewSel =
9573               SelectInst::Create(CondVal, NewTrueOp,
9574                                  NewFalseOp, SI.getName() + ".p");
9575
9576             NewSel = InsertNewInstBefore(NewSel, SI);
9577             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9578           }
9579         }
9580       }
9581
9582   // See if we can fold the select into one of our operands.
9583   if (SI.getType()->isInteger()) {
9584     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9585     if (FoldI)
9586       return FoldI;
9587   }
9588
9589   if (BinaryOperator::isNot(CondVal)) {
9590     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9591     SI.setOperand(1, FalseVal);
9592     SI.setOperand(2, TrueVal);
9593     return &SI;
9594   }
9595
9596   return 0;
9597 }
9598
9599 /// EnforceKnownAlignment - If the specified pointer points to an object that
9600 /// we control, modify the object's alignment to PrefAlign. This isn't
9601 /// often possible though. If alignment is important, a more reliable approach
9602 /// is to simply align all global variables and allocation instructions to
9603 /// their preferred alignment from the beginning.
9604 ///
9605 static unsigned EnforceKnownAlignment(Value *V,
9606                                       unsigned Align, unsigned PrefAlign) {
9607
9608   User *U = dyn_cast<User>(V);
9609   if (!U) return Align;
9610
9611   switch (Operator::getOpcode(U)) {
9612   default: break;
9613   case Instruction::BitCast:
9614     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9615   case Instruction::GetElementPtr: {
9616     // If all indexes are zero, it is just the alignment of the base pointer.
9617     bool AllZeroOperands = true;
9618     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9619       if (!isa<Constant>(*i) ||
9620           !cast<Constant>(*i)->isNullValue()) {
9621         AllZeroOperands = false;
9622         break;
9623       }
9624
9625     if (AllZeroOperands) {
9626       // Treat this like a bitcast.
9627       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9628     }
9629     break;
9630   }
9631   }
9632
9633   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9634     // If there is a large requested alignment and we can, bump up the alignment
9635     // of the global.
9636     if (!GV->isDeclaration()) {
9637       if (GV->getAlignment() >= PrefAlign)
9638         Align = GV->getAlignment();
9639       else {
9640         GV->setAlignment(PrefAlign);
9641         Align = PrefAlign;
9642       }
9643     }
9644   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9645     // If there is a requested alignment and if this is an alloca, round up.  We
9646     // don't do this for malloc, because some systems can't respect the request.
9647     if (isa<AllocaInst>(AI)) {
9648       if (AI->getAlignment() >= PrefAlign)
9649         Align = AI->getAlignment();
9650       else {
9651         AI->setAlignment(PrefAlign);
9652         Align = PrefAlign;
9653       }
9654     }
9655   }
9656
9657   return Align;
9658 }
9659
9660 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9661 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9662 /// and it is more than the alignment of the ultimate object, see if we can
9663 /// increase the alignment of the ultimate object, making this check succeed.
9664 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9665                                                   unsigned PrefAlign) {
9666   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9667                       sizeof(PrefAlign) * CHAR_BIT;
9668   APInt Mask = APInt::getAllOnesValue(BitWidth);
9669   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9670   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9671   unsigned TrailZ = KnownZero.countTrailingOnes();
9672   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9673
9674   if (PrefAlign > Align)
9675     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9676   
9677     // We don't need to make any adjustment.
9678   return Align;
9679 }
9680
9681 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9682   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9683   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9684   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9685   unsigned CopyAlign = MI->getAlignment();
9686
9687   if (CopyAlign < MinAlign) {
9688     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9689                                              MinAlign, false));
9690     return MI;
9691   }
9692   
9693   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9694   // load/store.
9695   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9696   if (MemOpLength == 0) return 0;
9697   
9698   // Source and destination pointer types are always "i8*" for intrinsic.  See
9699   // if the size is something we can handle with a single primitive load/store.
9700   // A single load+store correctly handles overlapping memory in the memmove
9701   // case.
9702   unsigned Size = MemOpLength->getZExtValue();
9703   if (Size == 0) return MI;  // Delete this mem transfer.
9704   
9705   if (Size > 8 || (Size&(Size-1)))
9706     return 0;  // If not 1/2/4/8 bytes, exit.
9707   
9708   // Use an integer load+store unless we can find something better.
9709   Type *NewPtrTy =
9710                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9711   
9712   // Memcpy forces the use of i8* for the source and destination.  That means
9713   // that if you're using memcpy to move one double around, you'll get a cast
9714   // from double* to i8*.  We'd much rather use a double load+store rather than
9715   // an i64 load+store, here because this improves the odds that the source or
9716   // dest address will be promotable.  See if we can find a better type than the
9717   // integer datatype.
9718   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9719     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9720     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9721       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9722       // down through these levels if so.
9723       while (!SrcETy->isSingleValueType()) {
9724         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9725           if (STy->getNumElements() == 1)
9726             SrcETy = STy->getElementType(0);
9727           else
9728             break;
9729         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9730           if (ATy->getNumElements() == 1)
9731             SrcETy = ATy->getElementType();
9732           else
9733             break;
9734         } else
9735           break;
9736       }
9737       
9738       if (SrcETy->isSingleValueType())
9739         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9740     }
9741   }
9742   
9743   
9744   // If the memcpy/memmove provides better alignment info than we can
9745   // infer, use it.
9746   SrcAlign = std::max(SrcAlign, CopyAlign);
9747   DstAlign = std::max(DstAlign, CopyAlign);
9748   
9749   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9750   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9751   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9752   InsertNewInstBefore(L, *MI);
9753   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9754
9755   // Set the size of the copy to 0, it will be deleted on the next iteration.
9756   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9757   return MI;
9758 }
9759
9760 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9761   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9762   if (MI->getAlignment() < Alignment) {
9763     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9764                                              Alignment, false));
9765     return MI;
9766   }
9767   
9768   // Extract the length and alignment and fill if they are constant.
9769   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9770   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9771   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9772     return 0;
9773   uint64_t Len = LenC->getZExtValue();
9774   Alignment = MI->getAlignment();
9775   
9776   // If the length is zero, this is a no-op
9777   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9778   
9779   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9780   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9781     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9782     
9783     Value *Dest = MI->getDest();
9784     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9785
9786     // Alignment 0 is identity for alignment 1 for memset, but not store.
9787     if (Alignment == 0) Alignment = 1;
9788     
9789     // Extract the fill value and store.
9790     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9791     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9792                                       Dest, false, Alignment), *MI);
9793     
9794     // Set the size of the copy to 0, it will be deleted on the next iteration.
9795     MI->setLength(Context->getNullValue(LenC->getType()));
9796     return MI;
9797   }
9798
9799   return 0;
9800 }
9801
9802
9803 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9804 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9805 /// the heavy lifting.
9806 ///
9807 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9808   // If the caller function is nounwind, mark the call as nounwind, even if the
9809   // callee isn't.
9810   if (CI.getParent()->getParent()->doesNotThrow() &&
9811       !CI.doesNotThrow()) {
9812     CI.setDoesNotThrow();
9813     return &CI;
9814   }
9815   
9816   
9817   
9818   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9819   if (!II) return visitCallSite(&CI);
9820   
9821   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9822   // visitCallSite.
9823   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9824     bool Changed = false;
9825
9826     // memmove/cpy/set of zero bytes is a noop.
9827     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9828       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9829
9830       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9831         if (CI->getZExtValue() == 1) {
9832           // Replace the instruction with just byte operations.  We would
9833           // transform other cases to loads/stores, but we don't know if
9834           // alignment is sufficient.
9835         }
9836     }
9837
9838     // If we have a memmove and the source operation is a constant global,
9839     // then the source and dest pointers can't alias, so we can change this
9840     // into a call to memcpy.
9841     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9842       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9843         if (GVSrc->isConstant()) {
9844           Module *M = CI.getParent()->getParent()->getParent();
9845           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9846           const Type *Tys[1];
9847           Tys[0] = CI.getOperand(3)->getType();
9848           CI.setOperand(0, 
9849                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9850           Changed = true;
9851         }
9852
9853       // memmove(x,x,size) -> noop.
9854       if (MMI->getSource() == MMI->getDest())
9855         return EraseInstFromFunction(CI);
9856     }
9857
9858     // If we can determine a pointer alignment that is bigger than currently
9859     // set, update the alignment.
9860     if (isa<MemTransferInst>(MI)) {
9861       if (Instruction *I = SimplifyMemTransfer(MI))
9862         return I;
9863     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9864       if (Instruction *I = SimplifyMemSet(MSI))
9865         return I;
9866     }
9867           
9868     if (Changed) return II;
9869   }
9870   
9871   switch (II->getIntrinsicID()) {
9872   default: break;
9873   case Intrinsic::bswap:
9874     // bswap(bswap(x)) -> x
9875     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9876       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9877         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9878     break;
9879   case Intrinsic::ppc_altivec_lvx:
9880   case Intrinsic::ppc_altivec_lvxl:
9881   case Intrinsic::x86_sse_loadu_ps:
9882   case Intrinsic::x86_sse2_loadu_pd:
9883   case Intrinsic::x86_sse2_loadu_dq:
9884     // Turn PPC lvx     -> load if the pointer is known aligned.
9885     // Turn X86 loadups -> load if the pointer is known aligned.
9886     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9887       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9888                                    Context->getPointerTypeUnqual(II->getType()),
9889                                        CI);
9890       return new LoadInst(Ptr);
9891     }
9892     break;
9893   case Intrinsic::ppc_altivec_stvx:
9894   case Intrinsic::ppc_altivec_stvxl:
9895     // Turn stvx -> store if the pointer is known aligned.
9896     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9897       const Type *OpPtrTy = 
9898         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9899       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9900       return new StoreInst(II->getOperand(1), Ptr);
9901     }
9902     break;
9903   case Intrinsic::x86_sse_storeu_ps:
9904   case Intrinsic::x86_sse2_storeu_pd:
9905   case Intrinsic::x86_sse2_storeu_dq:
9906     // Turn X86 storeu -> store if the pointer is known aligned.
9907     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9908       const Type *OpPtrTy = 
9909         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9910       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9911       return new StoreInst(II->getOperand(2), Ptr);
9912     }
9913     break;
9914     
9915   case Intrinsic::x86_sse_cvttss2si: {
9916     // These intrinsics only demands the 0th element of its input vector.  If
9917     // we can simplify the input based on that, do so now.
9918     unsigned VWidth =
9919       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9920     APInt DemandedElts(VWidth, 1);
9921     APInt UndefElts(VWidth, 0);
9922     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9923                                               UndefElts)) {
9924       II->setOperand(1, V);
9925       return II;
9926     }
9927     break;
9928   }
9929     
9930   case Intrinsic::ppc_altivec_vperm:
9931     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9932     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9933       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9934       
9935       // Check that all of the elements are integer constants or undefs.
9936       bool AllEltsOk = true;
9937       for (unsigned i = 0; i != 16; ++i) {
9938         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9939             !isa<UndefValue>(Mask->getOperand(i))) {
9940           AllEltsOk = false;
9941           break;
9942         }
9943       }
9944       
9945       if (AllEltsOk) {
9946         // Cast the input vectors to byte vectors.
9947         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9948         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9949         Value *Result = Context->getUndef(Op0->getType());
9950         
9951         // Only extract each element once.
9952         Value *ExtractedElts[32];
9953         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9954         
9955         for (unsigned i = 0; i != 16; ++i) {
9956           if (isa<UndefValue>(Mask->getOperand(i)))
9957             continue;
9958           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9959           Idx &= 31;  // Match the hardware behavior.
9960           
9961           if (ExtractedElts[Idx] == 0) {
9962             Instruction *Elt = 
9963               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9964                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9965             InsertNewInstBefore(Elt, CI);
9966             ExtractedElts[Idx] = Elt;
9967           }
9968         
9969           // Insert this value into the result vector.
9970           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9971                                Context->getConstantInt(Type::Int32Ty, i, false), 
9972                                "tmp");
9973           InsertNewInstBefore(cast<Instruction>(Result), CI);
9974         }
9975         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9976       }
9977     }
9978     break;
9979
9980   case Intrinsic::stackrestore: {
9981     // If the save is right next to the restore, remove the restore.  This can
9982     // happen when variable allocas are DCE'd.
9983     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9984       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9985         BasicBlock::iterator BI = SS;
9986         if (&*++BI == II)
9987           return EraseInstFromFunction(CI);
9988       }
9989     }
9990     
9991     // Scan down this block to see if there is another stack restore in the
9992     // same block without an intervening call/alloca.
9993     BasicBlock::iterator BI = II;
9994     TerminatorInst *TI = II->getParent()->getTerminator();
9995     bool CannotRemove = false;
9996     for (++BI; &*BI != TI; ++BI) {
9997       if (isa<AllocaInst>(BI)) {
9998         CannotRemove = true;
9999         break;
10000       }
10001       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10002         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10003           // If there is a stackrestore below this one, remove this one.
10004           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10005             return EraseInstFromFunction(CI);
10006           // Otherwise, ignore the intrinsic.
10007         } else {
10008           // If we found a non-intrinsic call, we can't remove the stack
10009           // restore.
10010           CannotRemove = true;
10011           break;
10012         }
10013       }
10014     }
10015     
10016     // If the stack restore is in a return/unwind block and if there are no
10017     // allocas or calls between the restore and the return, nuke the restore.
10018     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10019       return EraseInstFromFunction(CI);
10020     break;
10021   }
10022   }
10023
10024   return visitCallSite(II);
10025 }
10026
10027 // InvokeInst simplification
10028 //
10029 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10030   return visitCallSite(&II);
10031 }
10032
10033 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10034 /// passed through the varargs area, we can eliminate the use of the cast.
10035 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10036                                          const CastInst * const CI,
10037                                          const TargetData * const TD,
10038                                          const int ix) {
10039   if (!CI->isLosslessCast())
10040     return false;
10041
10042   // The size of ByVal arguments is derived from the type, so we
10043   // can't change to a type with a different size.  If the size were
10044   // passed explicitly we could avoid this check.
10045   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10046     return true;
10047
10048   const Type* SrcTy = 
10049             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10050   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10051   if (!SrcTy->isSized() || !DstTy->isSized())
10052     return false;
10053   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10054     return false;
10055   return true;
10056 }
10057
10058 // visitCallSite - Improvements for call and invoke instructions.
10059 //
10060 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10061   bool Changed = false;
10062
10063   // If the callee is a constexpr cast of a function, attempt to move the cast
10064   // to the arguments of the call/invoke.
10065   if (transformConstExprCastCall(CS)) return 0;
10066
10067   Value *Callee = CS.getCalledValue();
10068
10069   if (Function *CalleeF = dyn_cast<Function>(Callee))
10070     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10071       Instruction *OldCall = CS.getInstruction();
10072       // If the call and callee calling conventions don't match, this call must
10073       // be unreachable, as the call is undefined.
10074       new StoreInst(Context->getConstantIntTrue(),
10075                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10076                                   OldCall);
10077       if (!OldCall->use_empty())
10078         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10079       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10080         return EraseInstFromFunction(*OldCall);
10081       return 0;
10082     }
10083
10084   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10085     // This instruction is not reachable, just remove it.  We insert a store to
10086     // undef so that we know that this code is not reachable, despite the fact
10087     // that we can't modify the CFG here.
10088     new StoreInst(Context->getConstantIntTrue(),
10089                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10090                   CS.getInstruction());
10091
10092     if (!CS.getInstruction()->use_empty())
10093       CS.getInstruction()->
10094         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10095
10096     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10097       // Don't break the CFG, insert a dummy cond branch.
10098       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10099                          Context->getConstantIntTrue(), II);
10100     }
10101     return EraseInstFromFunction(*CS.getInstruction());
10102   }
10103
10104   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10105     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10106       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10107         return transformCallThroughTrampoline(CS);
10108
10109   const PointerType *PTy = cast<PointerType>(Callee->getType());
10110   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10111   if (FTy->isVarArg()) {
10112     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10113     // See if we can optimize any arguments passed through the varargs area of
10114     // the call.
10115     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10116            E = CS.arg_end(); I != E; ++I, ++ix) {
10117       CastInst *CI = dyn_cast<CastInst>(*I);
10118       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10119         *I = CI->getOperand(0);
10120         Changed = true;
10121       }
10122     }
10123   }
10124
10125   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10126     // Inline asm calls cannot throw - mark them 'nounwind'.
10127     CS.setDoesNotThrow();
10128     Changed = true;
10129   }
10130
10131   return Changed ? CS.getInstruction() : 0;
10132 }
10133
10134 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10135 // attempt to move the cast to the arguments of the call/invoke.
10136 //
10137 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10138   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10139   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10140   if (CE->getOpcode() != Instruction::BitCast || 
10141       !isa<Function>(CE->getOperand(0)))
10142     return false;
10143   Function *Callee = cast<Function>(CE->getOperand(0));
10144   Instruction *Caller = CS.getInstruction();
10145   const AttrListPtr &CallerPAL = CS.getAttributes();
10146
10147   // Okay, this is a cast from a function to a different type.  Unless doing so
10148   // would cause a type conversion of one of our arguments, change this call to
10149   // be a direct call with arguments casted to the appropriate types.
10150   //
10151   const FunctionType *FT = Callee->getFunctionType();
10152   const Type *OldRetTy = Caller->getType();
10153   const Type *NewRetTy = FT->getReturnType();
10154
10155   if (isa<StructType>(NewRetTy))
10156     return false; // TODO: Handle multiple return values.
10157
10158   // Check to see if we are changing the return type...
10159   if (OldRetTy != NewRetTy) {
10160     if (Callee->isDeclaration() &&
10161         // Conversion is ok if changing from one pointer type to another or from
10162         // a pointer to an integer of the same size.
10163         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10164           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10165       return false;   // Cannot transform this return value.
10166
10167     if (!Caller->use_empty() &&
10168         // void -> non-void is handled specially
10169         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10170       return false;   // Cannot transform this return value.
10171
10172     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10173       Attributes RAttrs = CallerPAL.getRetAttributes();
10174       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10175         return false;   // Attribute not compatible with transformed value.
10176     }
10177
10178     // If the callsite is an invoke instruction, and the return value is used by
10179     // a PHI node in a successor, we cannot change the return type of the call
10180     // because there is no place to put the cast instruction (without breaking
10181     // the critical edge).  Bail out in this case.
10182     if (!Caller->use_empty())
10183       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10184         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10185              UI != E; ++UI)
10186           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10187             if (PN->getParent() == II->getNormalDest() ||
10188                 PN->getParent() == II->getUnwindDest())
10189               return false;
10190   }
10191
10192   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10193   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10194
10195   CallSite::arg_iterator AI = CS.arg_begin();
10196   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10197     const Type *ParamTy = FT->getParamType(i);
10198     const Type *ActTy = (*AI)->getType();
10199
10200     if (!CastInst::isCastable(ActTy, ParamTy))
10201       return false;   // Cannot transform this parameter value.
10202
10203     if (CallerPAL.getParamAttributes(i + 1) 
10204         & Attribute::typeIncompatible(ParamTy))
10205       return false;   // Attribute not compatible with transformed value.
10206
10207     // Converting from one pointer type to another or between a pointer and an
10208     // integer of the same size is safe even if we do not have a body.
10209     bool isConvertible = ActTy == ParamTy ||
10210       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10211        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10212     if (Callee->isDeclaration() && !isConvertible) return false;
10213   }
10214
10215   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10216       Callee->isDeclaration())
10217     return false;   // Do not delete arguments unless we have a function body.
10218
10219   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10220       !CallerPAL.isEmpty())
10221     // In this case we have more arguments than the new function type, but we
10222     // won't be dropping them.  Check that these extra arguments have attributes
10223     // that are compatible with being a vararg call argument.
10224     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10225       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10226         break;
10227       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10228       if (PAttrs & Attribute::VarArgsIncompatible)
10229         return false;
10230     }
10231
10232   // Okay, we decided that this is a safe thing to do: go ahead and start
10233   // inserting cast instructions as necessary...
10234   std::vector<Value*> Args;
10235   Args.reserve(NumActualArgs);
10236   SmallVector<AttributeWithIndex, 8> attrVec;
10237   attrVec.reserve(NumCommonArgs);
10238
10239   // Get any return attributes.
10240   Attributes RAttrs = CallerPAL.getRetAttributes();
10241
10242   // If the return value is not being used, the type may not be compatible
10243   // with the existing attributes.  Wipe out any problematic attributes.
10244   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10245
10246   // Add the new return attributes.
10247   if (RAttrs)
10248     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10249
10250   AI = CS.arg_begin();
10251   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10252     const Type *ParamTy = FT->getParamType(i);
10253     if ((*AI)->getType() == ParamTy) {
10254       Args.push_back(*AI);
10255     } else {
10256       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10257           false, ParamTy, false);
10258       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10259       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10260     }
10261
10262     // Add any parameter attributes.
10263     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10264       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10265   }
10266
10267   // If the function takes more arguments than the call was taking, add them
10268   // now...
10269   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10270     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10271
10272   // If we are removing arguments to the function, emit an obnoxious warning...
10273   if (FT->getNumParams() < NumActualArgs) {
10274     if (!FT->isVarArg()) {
10275       cerr << "WARNING: While resolving call to function '"
10276            << Callee->getName() << "' arguments were dropped!\n";
10277     } else {
10278       // Add all of the arguments in their promoted form to the arg list...
10279       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10280         const Type *PTy = getPromotedType((*AI)->getType());
10281         if (PTy != (*AI)->getType()) {
10282           // Must promote to pass through va_arg area!
10283           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10284                                                                 PTy, false);
10285           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10286           InsertNewInstBefore(Cast, *Caller);
10287           Args.push_back(Cast);
10288         } else {
10289           Args.push_back(*AI);
10290         }
10291
10292         // Add any parameter attributes.
10293         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10294           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10295       }
10296     }
10297   }
10298
10299   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10300     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10301
10302   if (NewRetTy == Type::VoidTy)
10303     Caller->setName("");   // Void type should not have a name.
10304
10305   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10306
10307   Instruction *NC;
10308   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10309     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10310                             Args.begin(), Args.end(),
10311                             Caller->getName(), Caller);
10312     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10313     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10314   } else {
10315     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10316                           Caller->getName(), Caller);
10317     CallInst *CI = cast<CallInst>(Caller);
10318     if (CI->isTailCall())
10319       cast<CallInst>(NC)->setTailCall();
10320     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10321     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10322   }
10323
10324   // Insert a cast of the return type as necessary.
10325   Value *NV = NC;
10326   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10327     if (NV->getType() != Type::VoidTy) {
10328       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10329                                                             OldRetTy, false);
10330       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10331
10332       // If this is an invoke instruction, we should insert it after the first
10333       // non-phi, instruction in the normal successor block.
10334       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10335         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10336         InsertNewInstBefore(NC, *I);
10337       } else {
10338         // Otherwise, it's a call, just insert cast right after the call instr
10339         InsertNewInstBefore(NC, *Caller);
10340       }
10341       AddUsersToWorkList(*Caller);
10342     } else {
10343       NV = Context->getUndef(Caller->getType());
10344     }
10345   }
10346
10347   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10348     Caller->replaceAllUsesWith(NV);
10349   Caller->eraseFromParent();
10350   RemoveFromWorkList(Caller);
10351   return true;
10352 }
10353
10354 // transformCallThroughTrampoline - Turn a call to a function created by the
10355 // init_trampoline intrinsic into a direct call to the underlying function.
10356 //
10357 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10358   Value *Callee = CS.getCalledValue();
10359   const PointerType *PTy = cast<PointerType>(Callee->getType());
10360   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10361   const AttrListPtr &Attrs = CS.getAttributes();
10362
10363   // If the call already has the 'nest' attribute somewhere then give up -
10364   // otherwise 'nest' would occur twice after splicing in the chain.
10365   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10366     return 0;
10367
10368   IntrinsicInst *Tramp =
10369     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10370
10371   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10372   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10373   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10374
10375   const AttrListPtr &NestAttrs = NestF->getAttributes();
10376   if (!NestAttrs.isEmpty()) {
10377     unsigned NestIdx = 1;
10378     const Type *NestTy = 0;
10379     Attributes NestAttr = Attribute::None;
10380
10381     // Look for a parameter marked with the 'nest' attribute.
10382     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10383          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10384       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10385         // Record the parameter type and any other attributes.
10386         NestTy = *I;
10387         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10388         break;
10389       }
10390
10391     if (NestTy) {
10392       Instruction *Caller = CS.getInstruction();
10393       std::vector<Value*> NewArgs;
10394       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10395
10396       SmallVector<AttributeWithIndex, 8> NewAttrs;
10397       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10398
10399       // Insert the nest argument into the call argument list, which may
10400       // mean appending it.  Likewise for attributes.
10401
10402       // Add any result attributes.
10403       if (Attributes Attr = Attrs.getRetAttributes())
10404         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10405
10406       {
10407         unsigned Idx = 1;
10408         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10409         do {
10410           if (Idx == NestIdx) {
10411             // Add the chain argument and attributes.
10412             Value *NestVal = Tramp->getOperand(3);
10413             if (NestVal->getType() != NestTy)
10414               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10415             NewArgs.push_back(NestVal);
10416             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10417           }
10418
10419           if (I == E)
10420             break;
10421
10422           // Add the original argument and attributes.
10423           NewArgs.push_back(*I);
10424           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10425             NewAttrs.push_back
10426               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10427
10428           ++Idx, ++I;
10429         } while (1);
10430       }
10431
10432       // Add any function attributes.
10433       if (Attributes Attr = Attrs.getFnAttributes())
10434         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10435
10436       // The trampoline may have been bitcast to a bogus type (FTy).
10437       // Handle this by synthesizing a new function type, equal to FTy
10438       // with the chain parameter inserted.
10439
10440       std::vector<const Type*> NewTypes;
10441       NewTypes.reserve(FTy->getNumParams()+1);
10442
10443       // Insert the chain's type into the list of parameter types, which may
10444       // mean appending it.
10445       {
10446         unsigned Idx = 1;
10447         FunctionType::param_iterator I = FTy->param_begin(),
10448           E = FTy->param_end();
10449
10450         do {
10451           if (Idx == NestIdx)
10452             // Add the chain's type.
10453             NewTypes.push_back(NestTy);
10454
10455           if (I == E)
10456             break;
10457
10458           // Add the original type.
10459           NewTypes.push_back(*I);
10460
10461           ++Idx, ++I;
10462         } while (1);
10463       }
10464
10465       // Replace the trampoline call with a direct call.  Let the generic
10466       // code sort out any function type mismatches.
10467       FunctionType *NewFTy =
10468                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10469                                                 FTy->isVarArg());
10470       Constant *NewCallee =
10471         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10472         NestF : Context->getConstantExprBitCast(NestF, 
10473                                          Context->getPointerTypeUnqual(NewFTy));
10474       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10475
10476       Instruction *NewCaller;
10477       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10478         NewCaller = InvokeInst::Create(NewCallee,
10479                                        II->getNormalDest(), II->getUnwindDest(),
10480                                        NewArgs.begin(), NewArgs.end(),
10481                                        Caller->getName(), Caller);
10482         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10483         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10484       } else {
10485         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10486                                      Caller->getName(), Caller);
10487         if (cast<CallInst>(Caller)->isTailCall())
10488           cast<CallInst>(NewCaller)->setTailCall();
10489         cast<CallInst>(NewCaller)->
10490           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10491         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10492       }
10493       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10494         Caller->replaceAllUsesWith(NewCaller);
10495       Caller->eraseFromParent();
10496       RemoveFromWorkList(Caller);
10497       return 0;
10498     }
10499   }
10500
10501   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10502   // parameter, there is no need to adjust the argument list.  Let the generic
10503   // code sort out any function type mismatches.
10504   Constant *NewCallee =
10505     NestF->getType() == PTy ? NestF : 
10506                               Context->getConstantExprBitCast(NestF, PTy);
10507   CS.setCalledFunction(NewCallee);
10508   return CS.getInstruction();
10509 }
10510
10511 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10512 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10513 /// and a single binop.
10514 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10515   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10516   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10517   unsigned Opc = FirstInst->getOpcode();
10518   Value *LHSVal = FirstInst->getOperand(0);
10519   Value *RHSVal = FirstInst->getOperand(1);
10520     
10521   const Type *LHSType = LHSVal->getType();
10522   const Type *RHSType = RHSVal->getType();
10523   
10524   // Scan to see if all operands are the same opcode, all have one use, and all
10525   // kill their operands (i.e. the operands have one use).
10526   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10527     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10528     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10529         // Verify type of the LHS matches so we don't fold cmp's of different
10530         // types or GEP's with different index types.
10531         I->getOperand(0)->getType() != LHSType ||
10532         I->getOperand(1)->getType() != RHSType)
10533       return 0;
10534
10535     // If they are CmpInst instructions, check their predicates
10536     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10537       if (cast<CmpInst>(I)->getPredicate() !=
10538           cast<CmpInst>(FirstInst)->getPredicate())
10539         return 0;
10540     
10541     // Keep track of which operand needs a phi node.
10542     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10543     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10544   }
10545   
10546   // Otherwise, this is safe to transform!
10547   
10548   Value *InLHS = FirstInst->getOperand(0);
10549   Value *InRHS = FirstInst->getOperand(1);
10550   PHINode *NewLHS = 0, *NewRHS = 0;
10551   if (LHSVal == 0) {
10552     NewLHS = PHINode::Create(LHSType,
10553                              FirstInst->getOperand(0)->getName() + ".pn");
10554     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10555     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10556     InsertNewInstBefore(NewLHS, PN);
10557     LHSVal = NewLHS;
10558   }
10559   
10560   if (RHSVal == 0) {
10561     NewRHS = PHINode::Create(RHSType,
10562                              FirstInst->getOperand(1)->getName() + ".pn");
10563     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10564     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10565     InsertNewInstBefore(NewRHS, PN);
10566     RHSVal = NewRHS;
10567   }
10568   
10569   // Add all operands to the new PHIs.
10570   if (NewLHS || NewRHS) {
10571     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10572       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10573       if (NewLHS) {
10574         Value *NewInLHS = InInst->getOperand(0);
10575         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10576       }
10577       if (NewRHS) {
10578         Value *NewInRHS = InInst->getOperand(1);
10579         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10580       }
10581     }
10582   }
10583     
10584   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10585     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10586   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10587   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10588                          LHSVal, RHSVal);
10589 }
10590
10591 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10592   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10593   
10594   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10595                                         FirstInst->op_end());
10596   // This is true if all GEP bases are allocas and if all indices into them are
10597   // constants.
10598   bool AllBasePointersAreAllocas = true;
10599   
10600   // Scan to see if all operands are the same opcode, all have one use, and all
10601   // kill their operands (i.e. the operands have one use).
10602   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10603     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10604     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10605       GEP->getNumOperands() != FirstInst->getNumOperands())
10606       return 0;
10607
10608     // Keep track of whether or not all GEPs are of alloca pointers.
10609     if (AllBasePointersAreAllocas &&
10610         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10611          !GEP->hasAllConstantIndices()))
10612       AllBasePointersAreAllocas = false;
10613     
10614     // Compare the operand lists.
10615     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10616       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10617         continue;
10618       
10619       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10620       // if one of the PHIs has a constant for the index.  The index may be
10621       // substantially cheaper to compute for the constants, so making it a
10622       // variable index could pessimize the path.  This also handles the case
10623       // for struct indices, which must always be constant.
10624       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10625           isa<ConstantInt>(GEP->getOperand(op)))
10626         return 0;
10627       
10628       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10629         return 0;
10630       FixedOperands[op] = 0;  // Needs a PHI.
10631     }
10632   }
10633   
10634   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10635   // bother doing this transformation.  At best, this will just save a bit of
10636   // offset calculation, but all the predecessors will have to materialize the
10637   // stack address into a register anyway.  We'd actually rather *clone* the
10638   // load up into the predecessors so that we have a load of a gep of an alloca,
10639   // which can usually all be folded into the load.
10640   if (AllBasePointersAreAllocas)
10641     return 0;
10642   
10643   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10644   // that is variable.
10645   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10646   
10647   bool HasAnyPHIs = false;
10648   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10649     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10650     Value *FirstOp = FirstInst->getOperand(i);
10651     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10652                                      FirstOp->getName()+".pn");
10653     InsertNewInstBefore(NewPN, PN);
10654     
10655     NewPN->reserveOperandSpace(e);
10656     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10657     OperandPhis[i] = NewPN;
10658     FixedOperands[i] = NewPN;
10659     HasAnyPHIs = true;
10660   }
10661
10662   
10663   // Add all operands to the new PHIs.
10664   if (HasAnyPHIs) {
10665     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10666       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10667       BasicBlock *InBB = PN.getIncomingBlock(i);
10668       
10669       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10670         if (PHINode *OpPhi = OperandPhis[op])
10671           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10672     }
10673   }
10674   
10675   Value *Base = FixedOperands[0];
10676   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10677                                    FixedOperands.end());
10678 }
10679
10680
10681 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10682 /// sink the load out of the block that defines it.  This means that it must be
10683 /// obvious the value of the load is not changed from the point of the load to
10684 /// the end of the block it is in.
10685 ///
10686 /// Finally, it is safe, but not profitable, to sink a load targetting a
10687 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10688 /// to a register.
10689 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10690   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10691   
10692   for (++BBI; BBI != E; ++BBI)
10693     if (BBI->mayWriteToMemory())
10694       return false;
10695   
10696   // Check for non-address taken alloca.  If not address-taken already, it isn't
10697   // profitable to do this xform.
10698   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10699     bool isAddressTaken = false;
10700     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10701          UI != E; ++UI) {
10702       if (isa<LoadInst>(UI)) continue;
10703       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10704         // If storing TO the alloca, then the address isn't taken.
10705         if (SI->getOperand(1) == AI) continue;
10706       }
10707       isAddressTaken = true;
10708       break;
10709     }
10710     
10711     if (!isAddressTaken && AI->isStaticAlloca())
10712       return false;
10713   }
10714   
10715   // If this load is a load from a GEP with a constant offset from an alloca,
10716   // then we don't want to sink it.  In its present form, it will be
10717   // load [constant stack offset].  Sinking it will cause us to have to
10718   // materialize the stack addresses in each predecessor in a register only to
10719   // do a shared load from register in the successor.
10720   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10721     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10722       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10723         return false;
10724   
10725   return true;
10726 }
10727
10728
10729 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10730 // operator and they all are only used by the PHI, PHI together their
10731 // inputs, and do the operation once, to the result of the PHI.
10732 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10733   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10734
10735   // Scan the instruction, looking for input operations that can be folded away.
10736   // If all input operands to the phi are the same instruction (e.g. a cast from
10737   // the same type or "+42") we can pull the operation through the PHI, reducing
10738   // code size and simplifying code.
10739   Constant *ConstantOp = 0;
10740   const Type *CastSrcTy = 0;
10741   bool isVolatile = false;
10742   if (isa<CastInst>(FirstInst)) {
10743     CastSrcTy = FirstInst->getOperand(0)->getType();
10744   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10745     // Can fold binop, compare or shift here if the RHS is a constant, 
10746     // otherwise call FoldPHIArgBinOpIntoPHI.
10747     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10748     if (ConstantOp == 0)
10749       return FoldPHIArgBinOpIntoPHI(PN);
10750   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10751     isVolatile = LI->isVolatile();
10752     // We can't sink the load if the loaded value could be modified between the
10753     // load and the PHI.
10754     if (LI->getParent() != PN.getIncomingBlock(0) ||
10755         !isSafeAndProfitableToSinkLoad(LI))
10756       return 0;
10757     
10758     // If the PHI is of volatile loads and the load block has multiple
10759     // successors, sinking it would remove a load of the volatile value from
10760     // the path through the other successor.
10761     if (isVolatile &&
10762         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10763       return 0;
10764     
10765   } else if (isa<GetElementPtrInst>(FirstInst)) {
10766     return FoldPHIArgGEPIntoPHI(PN);
10767   } else {
10768     return 0;  // Cannot fold this operation.
10769   }
10770
10771   // Check to see if all arguments are the same operation.
10772   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10773     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10774     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10775     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10776       return 0;
10777     if (CastSrcTy) {
10778       if (I->getOperand(0)->getType() != CastSrcTy)
10779         return 0;  // Cast operation must match.
10780     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10781       // We can't sink the load if the loaded value could be modified between 
10782       // the load and the PHI.
10783       if (LI->isVolatile() != isVolatile ||
10784           LI->getParent() != PN.getIncomingBlock(i) ||
10785           !isSafeAndProfitableToSinkLoad(LI))
10786         return 0;
10787       
10788       // If the PHI is of volatile loads and the load block has multiple
10789       // successors, sinking it would remove a load of the volatile value from
10790       // the path through the other successor.
10791       if (isVolatile &&
10792           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10793         return 0;
10794       
10795     } else if (I->getOperand(1) != ConstantOp) {
10796       return 0;
10797     }
10798   }
10799
10800   // Okay, they are all the same operation.  Create a new PHI node of the
10801   // correct type, and PHI together all of the LHS's of the instructions.
10802   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10803                                    PN.getName()+".in");
10804   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10805
10806   Value *InVal = FirstInst->getOperand(0);
10807   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10808
10809   // Add all operands to the new PHI.
10810   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10811     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10812     if (NewInVal != InVal)
10813       InVal = 0;
10814     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10815   }
10816
10817   Value *PhiVal;
10818   if (InVal) {
10819     // The new PHI unions all of the same values together.  This is really
10820     // common, so we handle it intelligently here for compile-time speed.
10821     PhiVal = InVal;
10822     delete NewPN;
10823   } else {
10824     InsertNewInstBefore(NewPN, PN);
10825     PhiVal = NewPN;
10826   }
10827
10828   // Insert and return the new operation.
10829   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10830     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10831   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10832     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10833   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10834     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10835                            PhiVal, ConstantOp);
10836   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10837   
10838   // If this was a volatile load that we are merging, make sure to loop through
10839   // and mark all the input loads as non-volatile.  If we don't do this, we will
10840   // insert a new volatile load and the old ones will not be deletable.
10841   if (isVolatile)
10842     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10843       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10844   
10845   return new LoadInst(PhiVal, "", isVolatile);
10846 }
10847
10848 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10849 /// that is dead.
10850 static bool DeadPHICycle(PHINode *PN,
10851                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10852   if (PN->use_empty()) return true;
10853   if (!PN->hasOneUse()) return false;
10854
10855   // Remember this node, and if we find the cycle, return.
10856   if (!PotentiallyDeadPHIs.insert(PN))
10857     return true;
10858   
10859   // Don't scan crazily complex things.
10860   if (PotentiallyDeadPHIs.size() == 16)
10861     return false;
10862
10863   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10864     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10865
10866   return false;
10867 }
10868
10869 /// PHIsEqualValue - Return true if this phi node is always equal to
10870 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10871 ///   z = some value; x = phi (y, z); y = phi (x, z)
10872 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10873                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10874   // See if we already saw this PHI node.
10875   if (!ValueEqualPHIs.insert(PN))
10876     return true;
10877   
10878   // Don't scan crazily complex things.
10879   if (ValueEqualPHIs.size() == 16)
10880     return false;
10881  
10882   // Scan the operands to see if they are either phi nodes or are equal to
10883   // the value.
10884   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10885     Value *Op = PN->getIncomingValue(i);
10886     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10887       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10888         return false;
10889     } else if (Op != NonPhiInVal)
10890       return false;
10891   }
10892   
10893   return true;
10894 }
10895
10896
10897 // PHINode simplification
10898 //
10899 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10900   // If LCSSA is around, don't mess with Phi nodes
10901   if (MustPreserveLCSSA) return 0;
10902   
10903   if (Value *V = PN.hasConstantValue())
10904     return ReplaceInstUsesWith(PN, V);
10905
10906   // If all PHI operands are the same operation, pull them through the PHI,
10907   // reducing code size.
10908   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10909       isa<Instruction>(PN.getIncomingValue(1)) &&
10910       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10911       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10912       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10913       // than themselves more than once.
10914       PN.getIncomingValue(0)->hasOneUse())
10915     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10916       return Result;
10917
10918   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10919   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10920   // PHI)... break the cycle.
10921   if (PN.hasOneUse()) {
10922     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10923     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10924       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10925       PotentiallyDeadPHIs.insert(&PN);
10926       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10927         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10928     }
10929    
10930     // If this phi has a single use, and if that use just computes a value for
10931     // the next iteration of a loop, delete the phi.  This occurs with unused
10932     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10933     // common case here is good because the only other things that catch this
10934     // are induction variable analysis (sometimes) and ADCE, which is only run
10935     // late.
10936     if (PHIUser->hasOneUse() &&
10937         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10938         PHIUser->use_back() == &PN) {
10939       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10940     }
10941   }
10942
10943   // We sometimes end up with phi cycles that non-obviously end up being the
10944   // same value, for example:
10945   //   z = some value; x = phi (y, z); y = phi (x, z)
10946   // where the phi nodes don't necessarily need to be in the same block.  Do a
10947   // quick check to see if the PHI node only contains a single non-phi value, if
10948   // so, scan to see if the phi cycle is actually equal to that value.
10949   {
10950     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10951     // Scan for the first non-phi operand.
10952     while (InValNo != NumOperandVals && 
10953            isa<PHINode>(PN.getIncomingValue(InValNo)))
10954       ++InValNo;
10955
10956     if (InValNo != NumOperandVals) {
10957       Value *NonPhiInVal = PN.getOperand(InValNo);
10958       
10959       // Scan the rest of the operands to see if there are any conflicts, if so
10960       // there is no need to recursively scan other phis.
10961       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10962         Value *OpVal = PN.getIncomingValue(InValNo);
10963         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10964           break;
10965       }
10966       
10967       // If we scanned over all operands, then we have one unique value plus
10968       // phi values.  Scan PHI nodes to see if they all merge in each other or
10969       // the value.
10970       if (InValNo == NumOperandVals) {
10971         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10972         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10973           return ReplaceInstUsesWith(PN, NonPhiInVal);
10974       }
10975     }
10976   }
10977   return 0;
10978 }
10979
10980 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10981                                    Instruction *InsertPoint,
10982                                    InstCombiner *IC) {
10983   unsigned PtrSize = DTy->getScalarSizeInBits();
10984   unsigned VTySize = V->getType()->getScalarSizeInBits();
10985   // We must cast correctly to the pointer type. Ensure that we
10986   // sign extend the integer value if it is smaller as this is
10987   // used for address computation.
10988   Instruction::CastOps opcode = 
10989      (VTySize < PtrSize ? Instruction::SExt :
10990       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10991   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10992 }
10993
10994
10995 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10996   Value *PtrOp = GEP.getOperand(0);
10997   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10998   // If so, eliminate the noop.
10999   if (GEP.getNumOperands() == 1)
11000     return ReplaceInstUsesWith(GEP, PtrOp);
11001
11002   if (isa<UndefValue>(GEP.getOperand(0)))
11003     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11004
11005   bool HasZeroPointerIndex = false;
11006   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11007     HasZeroPointerIndex = C->isNullValue();
11008
11009   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11010     return ReplaceInstUsesWith(GEP, PtrOp);
11011
11012   // Eliminate unneeded casts for indices.
11013   bool MadeChange = false;
11014   
11015   gep_type_iterator GTI = gep_type_begin(GEP);
11016   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11017        i != e; ++i, ++GTI) {
11018     if (isa<SequentialType>(*GTI)) {
11019       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11020         if (CI->getOpcode() == Instruction::ZExt ||
11021             CI->getOpcode() == Instruction::SExt) {
11022           const Type *SrcTy = CI->getOperand(0)->getType();
11023           // We can eliminate a cast from i32 to i64 iff the target 
11024           // is a 32-bit pointer target.
11025           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11026             MadeChange = true;
11027             *i = CI->getOperand(0);
11028           }
11029         }
11030       }
11031       // If we are using a wider index than needed for this platform, shrink it
11032       // to what we need.  If narrower, sign-extend it to what we need.
11033       // If the incoming value needs a cast instruction,
11034       // insert it.  This explicit cast can make subsequent optimizations more
11035       // obvious.
11036       Value *Op = *i;
11037       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11038         if (Constant *C = dyn_cast<Constant>(Op)) {
11039           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11040           MadeChange = true;
11041         } else {
11042           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11043                                 GEP);
11044           *i = Op;
11045           MadeChange = true;
11046         }
11047       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11048         if (Constant *C = dyn_cast<Constant>(Op)) {
11049           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11050           MadeChange = true;
11051         } else {
11052           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11053                                 GEP);
11054           *i = Op;
11055           MadeChange = true;
11056         }
11057       }
11058     }
11059   }
11060   if (MadeChange) return &GEP;
11061
11062   // Combine Indices - If the source pointer to this getelementptr instruction
11063   // is a getelementptr instruction, combine the indices of the two
11064   // getelementptr instructions into a single instruction.
11065   //
11066   SmallVector<Value*, 8> SrcGEPOperands;
11067   if (User *Src = dyn_castGetElementPtr(PtrOp))
11068     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11069
11070   if (!SrcGEPOperands.empty()) {
11071     // Note that if our source is a gep chain itself that we wait for that
11072     // chain to be resolved before we perform this transformation.  This
11073     // avoids us creating a TON of code in some cases.
11074     //
11075     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11076         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11077       return 0;   // Wait until our source is folded to completion.
11078
11079     SmallVector<Value*, 8> Indices;
11080
11081     // Find out whether the last index in the source GEP is a sequential idx.
11082     bool EndsWithSequential = false;
11083     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11084            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11085       EndsWithSequential = !isa<StructType>(*I);
11086
11087     // Can we combine the two pointer arithmetics offsets?
11088     if (EndsWithSequential) {
11089       // Replace: gep (gep %P, long B), long A, ...
11090       // With:    T = long A+B; gep %P, T, ...
11091       //
11092       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11093       if (SO1 == Context->getNullValue(SO1->getType())) {
11094         Sum = GO1;
11095       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11096         Sum = SO1;
11097       } else {
11098         // If they aren't the same type, convert both to an integer of the
11099         // target's pointer size.
11100         if (SO1->getType() != GO1->getType()) {
11101           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11102             SO1 =
11103                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11104           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11105             GO1 =
11106                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11107           } else {
11108             unsigned PS = TD->getPointerSizeInBits();
11109             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11110               // Convert GO1 to SO1's type.
11111               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11112
11113             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11114               // Convert SO1 to GO1's type.
11115               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11116             } else {
11117               const Type *PT = TD->getIntPtrType();
11118               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11119               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11120             }
11121           }
11122         }
11123         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11124           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11125                                             cast<Constant>(GO1));
11126         else {
11127           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11128           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11129         }
11130       }
11131
11132       // Recycle the GEP we already have if possible.
11133       if (SrcGEPOperands.size() == 2) {
11134         GEP.setOperand(0, SrcGEPOperands[0]);
11135         GEP.setOperand(1, Sum);
11136         return &GEP;
11137       } else {
11138         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11139                        SrcGEPOperands.end()-1);
11140         Indices.push_back(Sum);
11141         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11142       }
11143     } else if (isa<Constant>(*GEP.idx_begin()) &&
11144                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11145                SrcGEPOperands.size() != 1) {
11146       // Otherwise we can do the fold if the first index of the GEP is a zero
11147       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11148                      SrcGEPOperands.end());
11149       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11150     }
11151
11152     if (!Indices.empty())
11153       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11154                                        Indices.end(), GEP.getName());
11155
11156   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11157     // GEP of global variable.  If all of the indices for this GEP are
11158     // constants, we can promote this to a constexpr instead of an instruction.
11159
11160     // Scan for nonconstants...
11161     SmallVector<Constant*, 8> Indices;
11162     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11163     for (; I != E && isa<Constant>(*I); ++I)
11164       Indices.push_back(cast<Constant>(*I));
11165
11166     if (I == E) {  // If they are all constants...
11167       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11168                                                     &Indices[0],Indices.size());
11169
11170       // Replace all uses of the GEP with the new constexpr...
11171       return ReplaceInstUsesWith(GEP, CE);
11172     }
11173   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11174     if (!isa<PointerType>(X->getType())) {
11175       // Not interesting.  Source pointer must be a cast from pointer.
11176     } else if (HasZeroPointerIndex) {
11177       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11178       // into     : GEP [10 x i8]* X, i32 0, ...
11179       //
11180       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11181       //           into     : GEP i8* X, ...
11182       // 
11183       // This occurs when the program declares an array extern like "int X[];"
11184       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11185       const PointerType *XTy = cast<PointerType>(X->getType());
11186       if (const ArrayType *CATy =
11187           dyn_cast<ArrayType>(CPTy->getElementType())) {
11188         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11189         if (CATy->getElementType() == XTy->getElementType()) {
11190           // -> GEP i8* X, ...
11191           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11192           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11193                                            GEP.getName());
11194         } else if (const ArrayType *XATy =
11195                  dyn_cast<ArrayType>(XTy->getElementType())) {
11196           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11197           if (CATy->getElementType() == XATy->getElementType()) {
11198             // -> GEP [10 x i8]* X, i32 0, ...
11199             // At this point, we know that the cast source type is a pointer
11200             // to an array of the same type as the destination pointer
11201             // array.  Because the array type is never stepped over (there
11202             // is a leading zero) we can fold the cast into this GEP.
11203             GEP.setOperand(0, X);
11204             return &GEP;
11205           }
11206         }
11207       }
11208     } else if (GEP.getNumOperands() == 2) {
11209       // Transform things like:
11210       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11211       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11212       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11213       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11214       if (isa<ArrayType>(SrcElTy) &&
11215           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11216           TD->getTypeAllocSize(ResElTy)) {
11217         Value *Idx[2];
11218         Idx[0] = Context->getNullValue(Type::Int32Ty);
11219         Idx[1] = GEP.getOperand(1);
11220         Value *V = InsertNewInstBefore(
11221                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11222         // V and GEP are both pointer types --> BitCast
11223         return new BitCastInst(V, GEP.getType());
11224       }
11225       
11226       // Transform things like:
11227       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11228       //   (where tmp = 8*tmp2) into:
11229       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11230       
11231       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11232         uint64_t ArrayEltSize =
11233             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11234         
11235         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11236         // allow either a mul, shift, or constant here.
11237         Value *NewIdx = 0;
11238         ConstantInt *Scale = 0;
11239         if (ArrayEltSize == 1) {
11240           NewIdx = GEP.getOperand(1);
11241           Scale = 
11242                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11243         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11244           NewIdx = Context->getConstantInt(CI->getType(), 1);
11245           Scale = CI;
11246         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11247           if (Inst->getOpcode() == Instruction::Shl &&
11248               isa<ConstantInt>(Inst->getOperand(1))) {
11249             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11250             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11251             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11252                                      1ULL << ShAmtVal);
11253             NewIdx = Inst->getOperand(0);
11254           } else if (Inst->getOpcode() == Instruction::Mul &&
11255                      isa<ConstantInt>(Inst->getOperand(1))) {
11256             Scale = cast<ConstantInt>(Inst->getOperand(1));
11257             NewIdx = Inst->getOperand(0);
11258           }
11259         }
11260         
11261         // If the index will be to exactly the right offset with the scale taken
11262         // out, perform the transformation. Note, we don't know whether Scale is
11263         // signed or not. We'll use unsigned version of division/modulo
11264         // operation after making sure Scale doesn't have the sign bit set.
11265         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11266             Scale->getZExtValue() % ArrayEltSize == 0) {
11267           Scale = Context->getConstantInt(Scale->getType(),
11268                                    Scale->getZExtValue() / ArrayEltSize);
11269           if (Scale->getZExtValue() != 1) {
11270             Constant *C =
11271                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11272                                                        false /*ZExt*/);
11273             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11274             NewIdx = InsertNewInstBefore(Sc, GEP);
11275           }
11276
11277           // Insert the new GEP instruction.
11278           Value *Idx[2];
11279           Idx[0] = Context->getNullValue(Type::Int32Ty);
11280           Idx[1] = NewIdx;
11281           Instruction *NewGEP =
11282             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11283           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11284           // The NewGEP must be pointer typed, so must the old one -> BitCast
11285           return new BitCastInst(NewGEP, GEP.getType());
11286         }
11287       }
11288     }
11289   }
11290   
11291   /// See if we can simplify:
11292   ///   X = bitcast A to B*
11293   ///   Y = gep X, <...constant indices...>
11294   /// into a gep of the original struct.  This is important for SROA and alias
11295   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11296   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11297     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11298       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11299       // a constant back from EmitGEPOffset.
11300       ConstantInt *OffsetV =
11301                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11302       int64_t Offset = OffsetV->getSExtValue();
11303       
11304       // If this GEP instruction doesn't move the pointer, just replace the GEP
11305       // with a bitcast of the real input to the dest type.
11306       if (Offset == 0) {
11307         // If the bitcast is of an allocation, and the allocation will be
11308         // converted to match the type of the cast, don't touch this.
11309         if (isa<AllocationInst>(BCI->getOperand(0))) {
11310           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11311           if (Instruction *I = visitBitCast(*BCI)) {
11312             if (I != BCI) {
11313               I->takeName(BCI);
11314               BCI->getParent()->getInstList().insert(BCI, I);
11315               ReplaceInstUsesWith(*BCI, I);
11316             }
11317             return &GEP;
11318           }
11319         }
11320         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11321       }
11322       
11323       // Otherwise, if the offset is non-zero, we need to find out if there is a
11324       // field at Offset in 'A's type.  If so, we can pull the cast through the
11325       // GEP.
11326       SmallVector<Value*, 8> NewIndices;
11327       const Type *InTy =
11328         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11329       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11330         Instruction *NGEP =
11331            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11332                                      NewIndices.end());
11333         if (NGEP->getType() == GEP.getType()) return NGEP;
11334         InsertNewInstBefore(NGEP, GEP);
11335         NGEP->takeName(&GEP);
11336         return new BitCastInst(NGEP, GEP.getType());
11337       }
11338     }
11339   }    
11340     
11341   return 0;
11342 }
11343
11344 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11345   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11346   if (AI.isArrayAllocation()) {  // Check C != 1
11347     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11348       const Type *NewTy = 
11349         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11350       AllocationInst *New = 0;
11351
11352       // Create and insert the replacement instruction...
11353       if (isa<MallocInst>(AI))
11354         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11355       else {
11356         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11357         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11358       }
11359
11360       InsertNewInstBefore(New, AI);
11361
11362       // Scan to the end of the allocation instructions, to skip over a block of
11363       // allocas if possible...also skip interleaved debug info
11364       //
11365       BasicBlock::iterator It = New;
11366       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11367
11368       // Now that I is pointing to the first non-allocation-inst in the block,
11369       // insert our getelementptr instruction...
11370       //
11371       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11372       Value *Idx[2];
11373       Idx[0] = NullIdx;
11374       Idx[1] = NullIdx;
11375       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11376                                            New->getName()+".sub", It);
11377
11378       // Now make everything use the getelementptr instead of the original
11379       // allocation.
11380       return ReplaceInstUsesWith(AI, V);
11381     } else if (isa<UndefValue>(AI.getArraySize())) {
11382       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11383     }
11384   }
11385
11386   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11387     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11388     // Note that we only do this for alloca's, because malloc should allocate
11389     // and return a unique pointer, even for a zero byte allocation.
11390     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11391       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11392
11393     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11394     if (AI.getAlignment() == 0)
11395       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11396   }
11397
11398   return 0;
11399 }
11400
11401 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11402   Value *Op = FI.getOperand(0);
11403
11404   // free undef -> unreachable.
11405   if (isa<UndefValue>(Op)) {
11406     // Insert a new store to null because we cannot modify the CFG here.
11407     new StoreInst(Context->getConstantIntTrue(),
11408            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11409     return EraseInstFromFunction(FI);
11410   }
11411   
11412   // If we have 'free null' delete the instruction.  This can happen in stl code
11413   // when lots of inlining happens.
11414   if (isa<ConstantPointerNull>(Op))
11415     return EraseInstFromFunction(FI);
11416   
11417   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11418   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11419     FI.setOperand(0, CI->getOperand(0));
11420     return &FI;
11421   }
11422   
11423   // Change free (gep X, 0,0,0,0) into free(X)
11424   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11425     if (GEPI->hasAllZeroIndices()) {
11426       AddToWorkList(GEPI);
11427       FI.setOperand(0, GEPI->getOperand(0));
11428       return &FI;
11429     }
11430   }
11431   
11432   // Change free(malloc) into nothing, if the malloc has a single use.
11433   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11434     if (MI->hasOneUse()) {
11435       EraseInstFromFunction(FI);
11436       return EraseInstFromFunction(*MI);
11437     }
11438
11439   return 0;
11440 }
11441
11442
11443 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11444 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11445                                         const TargetData *TD) {
11446   User *CI = cast<User>(LI.getOperand(0));
11447   Value *CastOp = CI->getOperand(0);
11448   LLVMContext *Context = IC.getContext();
11449
11450   if (TD) {
11451     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11452       // Instead of loading constant c string, use corresponding integer value
11453       // directly if string length is small enough.
11454       std::string Str;
11455       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11456         unsigned len = Str.length();
11457         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11458         unsigned numBits = Ty->getPrimitiveSizeInBits();
11459         // Replace LI with immediate integer store.
11460         if ((numBits >> 3) == len + 1) {
11461           APInt StrVal(numBits, 0);
11462           APInt SingleChar(numBits, 0);
11463           if (TD->isLittleEndian()) {
11464             for (signed i = len-1; i >= 0; i--) {
11465               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11466               StrVal = (StrVal << 8) | SingleChar;
11467             }
11468           } else {
11469             for (unsigned i = 0; i < len; i++) {
11470               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11471               StrVal = (StrVal << 8) | SingleChar;
11472             }
11473             // Append NULL at the end.
11474             SingleChar = 0;
11475             StrVal = (StrVal << 8) | SingleChar;
11476           }
11477           Value *NL = Context->getConstantInt(StrVal);
11478           return IC.ReplaceInstUsesWith(LI, NL);
11479         }
11480       }
11481     }
11482   }
11483
11484   const PointerType *DestTy = cast<PointerType>(CI->getType());
11485   const Type *DestPTy = DestTy->getElementType();
11486   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11487
11488     // If the address spaces don't match, don't eliminate the cast.
11489     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11490       return 0;
11491
11492     const Type *SrcPTy = SrcTy->getElementType();
11493
11494     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11495          isa<VectorType>(DestPTy)) {
11496       // If the source is an array, the code below will not succeed.  Check to
11497       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11498       // constants.
11499       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11500         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11501           if (ASrcTy->getNumElements() != 0) {
11502             Value *Idxs[2];
11503             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11504             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11505             SrcTy = cast<PointerType>(CastOp->getType());
11506             SrcPTy = SrcTy->getElementType();
11507           }
11508
11509       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11510             isa<VectorType>(SrcPTy)) &&
11511           // Do not allow turning this into a load of an integer, which is then
11512           // casted to a pointer, this pessimizes pointer analysis a lot.
11513           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11514           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11515                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11516
11517         // Okay, we are casting from one integer or pointer type to another of
11518         // the same size.  Instead of casting the pointer before the load, cast
11519         // the result of the loaded value.
11520         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11521                                                              CI->getName(),
11522                                                          LI.isVolatile()),LI);
11523         // Now cast the result of the load.
11524         return new BitCastInst(NewLoad, LI.getType());
11525       }
11526     }
11527   }
11528   return 0;
11529 }
11530
11531 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11532   Value *Op = LI.getOperand(0);
11533
11534   // Attempt to improve the alignment.
11535   unsigned KnownAlign =
11536     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11537   if (KnownAlign >
11538       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11539                                 LI.getAlignment()))
11540     LI.setAlignment(KnownAlign);
11541
11542   // load (cast X) --> cast (load X) iff safe
11543   if (isa<CastInst>(Op))
11544     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11545       return Res;
11546
11547   // None of the following transforms are legal for volatile loads.
11548   if (LI.isVolatile()) return 0;
11549   
11550   // Do really simple store-to-load forwarding and load CSE, to catch cases
11551   // where there are several consequtive memory accesses to the same location,
11552   // separated by a few arithmetic operations.
11553   BasicBlock::iterator BBI = &LI;
11554   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11555     return ReplaceInstUsesWith(LI, AvailableVal);
11556
11557   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11558     const Value *GEPI0 = GEPI->getOperand(0);
11559     // TODO: Consider a target hook for valid address spaces for this xform.
11560     if (isa<ConstantPointerNull>(GEPI0) &&
11561         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11562       // Insert a new store to null instruction before the load to indicate
11563       // that this code is not reachable.  We do this instead of inserting
11564       // an unreachable instruction directly because we cannot modify the
11565       // CFG.
11566       new StoreInst(Context->getUndef(LI.getType()),
11567                     Context->getNullValue(Op->getType()), &LI);
11568       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11569     }
11570   } 
11571
11572   if (Constant *C = dyn_cast<Constant>(Op)) {
11573     // load null/undef -> undef
11574     // TODO: Consider a target hook for valid address spaces for this xform.
11575     if (isa<UndefValue>(C) || (C->isNullValue() && 
11576         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11577       // Insert a new store to null instruction before the load to indicate that
11578       // this code is not reachable.  We do this instead of inserting an
11579       // unreachable instruction directly because we cannot modify the CFG.
11580       new StoreInst(Context->getUndef(LI.getType()),
11581                     Context->getNullValue(Op->getType()), &LI);
11582       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11583     }
11584
11585     // Instcombine load (constant global) into the value loaded.
11586     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11587       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11588         return ReplaceInstUsesWith(LI, GV->getInitializer());
11589
11590     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11591     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11592       if (CE->getOpcode() == Instruction::GetElementPtr) {
11593         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11594           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11595             if (Constant *V = 
11596                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11597                                                       Context))
11598               return ReplaceInstUsesWith(LI, V);
11599         if (CE->getOperand(0)->isNullValue()) {
11600           // Insert a new store to null instruction before the load to indicate
11601           // that this code is not reachable.  We do this instead of inserting
11602           // an unreachable instruction directly because we cannot modify the
11603           // CFG.
11604           new StoreInst(Context->getUndef(LI.getType()),
11605                         Context->getNullValue(Op->getType()), &LI);
11606           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11607         }
11608
11609       } else if (CE->isCast()) {
11610         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11611           return Res;
11612       }
11613     }
11614   }
11615     
11616   // If this load comes from anywhere in a constant global, and if the global
11617   // is all undef or zero, we know what it loads.
11618   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11619     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11620       if (GV->getInitializer()->isNullValue())
11621         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11622       else if (isa<UndefValue>(GV->getInitializer()))
11623         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11624     }
11625   }
11626
11627   if (Op->hasOneUse()) {
11628     // Change select and PHI nodes to select values instead of addresses: this
11629     // helps alias analysis out a lot, allows many others simplifications, and
11630     // exposes redundancy in the code.
11631     //
11632     // Note that we cannot do the transformation unless we know that the
11633     // introduced loads cannot trap!  Something like this is valid as long as
11634     // the condition is always false: load (select bool %C, int* null, int* %G),
11635     // but it would not be valid if we transformed it to load from null
11636     // unconditionally.
11637     //
11638     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11639       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11640       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11641           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11642         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11643                                      SI->getOperand(1)->getName()+".val"), LI);
11644         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11645                                      SI->getOperand(2)->getName()+".val"), LI);
11646         return SelectInst::Create(SI->getCondition(), V1, V2);
11647       }
11648
11649       // load (select (cond, null, P)) -> load P
11650       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11651         if (C->isNullValue()) {
11652           LI.setOperand(0, SI->getOperand(2));
11653           return &LI;
11654         }
11655
11656       // load (select (cond, P, null)) -> load P
11657       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11658         if (C->isNullValue()) {
11659           LI.setOperand(0, SI->getOperand(1));
11660           return &LI;
11661         }
11662     }
11663   }
11664   return 0;
11665 }
11666
11667 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11668 /// when possible.  This makes it generally easy to do alias analysis and/or
11669 /// SROA/mem2reg of the memory object.
11670 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11671   User *CI = cast<User>(SI.getOperand(1));
11672   Value *CastOp = CI->getOperand(0);
11673   LLVMContext *Context = IC.getContext();
11674
11675   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11676   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11677   if (SrcTy == 0) return 0;
11678   
11679   const Type *SrcPTy = SrcTy->getElementType();
11680
11681   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11682     return 0;
11683   
11684   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11685   /// to its first element.  This allows us to handle things like:
11686   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11687   /// on 32-bit hosts.
11688   SmallVector<Value*, 4> NewGEPIndices;
11689   
11690   // If the source is an array, the code below will not succeed.  Check to
11691   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11692   // constants.
11693   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11694     // Index through pointer.
11695     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11696     NewGEPIndices.push_back(Zero);
11697     
11698     while (1) {
11699       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11700         if (!STy->getNumElements()) /* Struct can be empty {} */
11701           break;
11702         NewGEPIndices.push_back(Zero);
11703         SrcPTy = STy->getElementType(0);
11704       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11705         NewGEPIndices.push_back(Zero);
11706         SrcPTy = ATy->getElementType();
11707       } else {
11708         break;
11709       }
11710     }
11711     
11712     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11713   }
11714
11715   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11716     return 0;
11717   
11718   // If the pointers point into different address spaces or if they point to
11719   // values with different sizes, we can't do the transformation.
11720   if (SrcTy->getAddressSpace() != 
11721         cast<PointerType>(CI->getType())->getAddressSpace() ||
11722       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11723       IC.getTargetData().getTypeSizeInBits(DestPTy))
11724     return 0;
11725
11726   // Okay, we are casting from one integer or pointer type to another of
11727   // the same size.  Instead of casting the pointer before 
11728   // the store, cast the value to be stored.
11729   Value *NewCast;
11730   Value *SIOp0 = SI.getOperand(0);
11731   Instruction::CastOps opcode = Instruction::BitCast;
11732   const Type* CastSrcTy = SIOp0->getType();
11733   const Type* CastDstTy = SrcPTy;
11734   if (isa<PointerType>(CastDstTy)) {
11735     if (CastSrcTy->isInteger())
11736       opcode = Instruction::IntToPtr;
11737   } else if (isa<IntegerType>(CastDstTy)) {
11738     if (isa<PointerType>(SIOp0->getType()))
11739       opcode = Instruction::PtrToInt;
11740   }
11741   
11742   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11743   // emit a GEP to index into its first field.
11744   if (!NewGEPIndices.empty()) {
11745     if (Constant *C = dyn_cast<Constant>(CastOp))
11746       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11747                                               NewGEPIndices.size());
11748     else
11749       CastOp = IC.InsertNewInstBefore(
11750               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11751                                         NewGEPIndices.end()), SI);
11752   }
11753   
11754   if (Constant *C = dyn_cast<Constant>(SIOp0))
11755     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11756   else
11757     NewCast = IC.InsertNewInstBefore(
11758       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11759       SI);
11760   return new StoreInst(NewCast, CastOp);
11761 }
11762
11763 /// equivalentAddressValues - Test if A and B will obviously have the same
11764 /// value. This includes recognizing that %t0 and %t1 will have the same
11765 /// value in code like this:
11766 ///   %t0 = getelementptr \@a, 0, 3
11767 ///   store i32 0, i32* %t0
11768 ///   %t1 = getelementptr \@a, 0, 3
11769 ///   %t2 = load i32* %t1
11770 ///
11771 static bool equivalentAddressValues(Value *A, Value *B) {
11772   // Test if the values are trivially equivalent.
11773   if (A == B) return true;
11774   
11775   // Test if the values come form identical arithmetic instructions.
11776   if (isa<BinaryOperator>(A) ||
11777       isa<CastInst>(A) ||
11778       isa<PHINode>(A) ||
11779       isa<GetElementPtrInst>(A))
11780     if (Instruction *BI = dyn_cast<Instruction>(B))
11781       if (cast<Instruction>(A)->isIdenticalTo(BI))
11782         return true;
11783   
11784   // Otherwise they may not be equivalent.
11785   return false;
11786 }
11787
11788 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11789 // return the llvm.dbg.declare.
11790 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11791   if (!V->hasNUses(2))
11792     return 0;
11793   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11794        UI != E; ++UI) {
11795     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11796       return DI;
11797     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11798       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11799         return DI;
11800       }
11801   }
11802   return 0;
11803 }
11804
11805 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11806   Value *Val = SI.getOperand(0);
11807   Value *Ptr = SI.getOperand(1);
11808
11809   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11810     EraseInstFromFunction(SI);
11811     ++NumCombined;
11812     return 0;
11813   }
11814   
11815   // If the RHS is an alloca with a single use, zapify the store, making the
11816   // alloca dead.
11817   // If the RHS is an alloca with a two uses, the other one being a 
11818   // llvm.dbg.declare, zapify the store and the declare, making the
11819   // alloca dead.  We must do this to prevent declare's from affecting
11820   // codegen.
11821   if (!SI.isVolatile()) {
11822     if (Ptr->hasOneUse()) {
11823       if (isa<AllocaInst>(Ptr)) {
11824         EraseInstFromFunction(SI);
11825         ++NumCombined;
11826         return 0;
11827       }
11828       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11829         if (isa<AllocaInst>(GEP->getOperand(0))) {
11830           if (GEP->getOperand(0)->hasOneUse()) {
11831             EraseInstFromFunction(SI);
11832             ++NumCombined;
11833             return 0;
11834           }
11835           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11836             EraseInstFromFunction(*DI);
11837             EraseInstFromFunction(SI);
11838             ++NumCombined;
11839             return 0;
11840           }
11841         }
11842       }
11843     }
11844     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11845       EraseInstFromFunction(*DI);
11846       EraseInstFromFunction(SI);
11847       ++NumCombined;
11848       return 0;
11849     }
11850   }
11851
11852   // Attempt to improve the alignment.
11853   unsigned KnownAlign =
11854     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11855   if (KnownAlign >
11856       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11857                                 SI.getAlignment()))
11858     SI.setAlignment(KnownAlign);
11859
11860   // Do really simple DSE, to catch cases where there are several consecutive
11861   // stores to the same location, separated by a few arithmetic operations. This
11862   // situation often occurs with bitfield accesses.
11863   BasicBlock::iterator BBI = &SI;
11864   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11865        --ScanInsts) {
11866     --BBI;
11867     // Don't count debug info directives, lest they affect codegen,
11868     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11869     // It is necessary for correctness to skip those that feed into a
11870     // llvm.dbg.declare, as these are not present when debugging is off.
11871     if (isa<DbgInfoIntrinsic>(BBI) ||
11872         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11873       ScanInsts++;
11874       continue;
11875     }    
11876     
11877     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11878       // Prev store isn't volatile, and stores to the same location?
11879       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11880                                                           SI.getOperand(1))) {
11881         ++NumDeadStore;
11882         ++BBI;
11883         EraseInstFromFunction(*PrevSI);
11884         continue;
11885       }
11886       break;
11887     }
11888     
11889     // If this is a load, we have to stop.  However, if the loaded value is from
11890     // the pointer we're loading and is producing the pointer we're storing,
11891     // then *this* store is dead (X = load P; store X -> P).
11892     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11893       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11894           !SI.isVolatile()) {
11895         EraseInstFromFunction(SI);
11896         ++NumCombined;
11897         return 0;
11898       }
11899       // Otherwise, this is a load from some other location.  Stores before it
11900       // may not be dead.
11901       break;
11902     }
11903     
11904     // Don't skip over loads or things that can modify memory.
11905     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11906       break;
11907   }
11908   
11909   
11910   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11911
11912   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11913   if (isa<ConstantPointerNull>(Ptr) &&
11914       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11915     if (!isa<UndefValue>(Val)) {
11916       SI.setOperand(0, Context->getUndef(Val->getType()));
11917       if (Instruction *U = dyn_cast<Instruction>(Val))
11918         AddToWorkList(U);  // Dropped a use.
11919       ++NumCombined;
11920     }
11921     return 0;  // Do not modify these!
11922   }
11923
11924   // store undef, Ptr -> noop
11925   if (isa<UndefValue>(Val)) {
11926     EraseInstFromFunction(SI);
11927     ++NumCombined;
11928     return 0;
11929   }
11930
11931   // If the pointer destination is a cast, see if we can fold the cast into the
11932   // source instead.
11933   if (isa<CastInst>(Ptr))
11934     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11935       return Res;
11936   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11937     if (CE->isCast())
11938       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11939         return Res;
11940
11941   
11942   // If this store is the last instruction in the basic block (possibly
11943   // excepting debug info instructions and the pointer bitcasts that feed
11944   // into them), and if the block ends with an unconditional branch, try
11945   // to move it to the successor block.
11946   BBI = &SI; 
11947   do {
11948     ++BBI;
11949   } while (isa<DbgInfoIntrinsic>(BBI) ||
11950            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11951   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11952     if (BI->isUnconditional())
11953       if (SimplifyStoreAtEndOfBlock(SI))
11954         return 0;  // xform done!
11955   
11956   return 0;
11957 }
11958
11959 /// SimplifyStoreAtEndOfBlock - Turn things like:
11960 ///   if () { *P = v1; } else { *P = v2 }
11961 /// into a phi node with a store in the successor.
11962 ///
11963 /// Simplify things like:
11964 ///   *P = v1; if () { *P = v2; }
11965 /// into a phi node with a store in the successor.
11966 ///
11967 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11968   BasicBlock *StoreBB = SI.getParent();
11969   
11970   // Check to see if the successor block has exactly two incoming edges.  If
11971   // so, see if the other predecessor contains a store to the same location.
11972   // if so, insert a PHI node (if needed) and move the stores down.
11973   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11974   
11975   // Determine whether Dest has exactly two predecessors and, if so, compute
11976   // the other predecessor.
11977   pred_iterator PI = pred_begin(DestBB);
11978   BasicBlock *OtherBB = 0;
11979   if (*PI != StoreBB)
11980     OtherBB = *PI;
11981   ++PI;
11982   if (PI == pred_end(DestBB))
11983     return false;
11984   
11985   if (*PI != StoreBB) {
11986     if (OtherBB)
11987       return false;
11988     OtherBB = *PI;
11989   }
11990   if (++PI != pred_end(DestBB))
11991     return false;
11992
11993   // Bail out if all the relevant blocks aren't distinct (this can happen,
11994   // for example, if SI is in an infinite loop)
11995   if (StoreBB == DestBB || OtherBB == DestBB)
11996     return false;
11997
11998   // Verify that the other block ends in a branch and is not otherwise empty.
11999   BasicBlock::iterator BBI = OtherBB->getTerminator();
12000   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12001   if (!OtherBr || BBI == OtherBB->begin())
12002     return false;
12003   
12004   // If the other block ends in an unconditional branch, check for the 'if then
12005   // else' case.  there is an instruction before the branch.
12006   StoreInst *OtherStore = 0;
12007   if (OtherBr->isUnconditional()) {
12008     --BBI;
12009     // Skip over debugging info.
12010     while (isa<DbgInfoIntrinsic>(BBI) ||
12011            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12012       if (BBI==OtherBB->begin())
12013         return false;
12014       --BBI;
12015     }
12016     // If this isn't a store, or isn't a store to the same location, bail out.
12017     OtherStore = dyn_cast<StoreInst>(BBI);
12018     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12019       return false;
12020   } else {
12021     // Otherwise, the other block ended with a conditional branch. If one of the
12022     // destinations is StoreBB, then we have the if/then case.
12023     if (OtherBr->getSuccessor(0) != StoreBB && 
12024         OtherBr->getSuccessor(1) != StoreBB)
12025       return false;
12026     
12027     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12028     // if/then triangle.  See if there is a store to the same ptr as SI that
12029     // lives in OtherBB.
12030     for (;; --BBI) {
12031       // Check to see if we find the matching store.
12032       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12033         if (OtherStore->getOperand(1) != SI.getOperand(1))
12034           return false;
12035         break;
12036       }
12037       // If we find something that may be using or overwriting the stored
12038       // value, or if we run out of instructions, we can't do the xform.
12039       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12040           BBI == OtherBB->begin())
12041         return false;
12042     }
12043     
12044     // In order to eliminate the store in OtherBr, we have to
12045     // make sure nothing reads or overwrites the stored value in
12046     // StoreBB.
12047     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12048       // FIXME: This should really be AA driven.
12049       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12050         return false;
12051     }
12052   }
12053   
12054   // Insert a PHI node now if we need it.
12055   Value *MergedVal = OtherStore->getOperand(0);
12056   if (MergedVal != SI.getOperand(0)) {
12057     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12058     PN->reserveOperandSpace(2);
12059     PN->addIncoming(SI.getOperand(0), SI.getParent());
12060     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12061     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12062   }
12063   
12064   // Advance to a place where it is safe to insert the new store and
12065   // insert it.
12066   BBI = DestBB->getFirstNonPHI();
12067   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12068                                     OtherStore->isVolatile()), *BBI);
12069   
12070   // Nuke the old stores.
12071   EraseInstFromFunction(SI);
12072   EraseInstFromFunction(*OtherStore);
12073   ++NumCombined;
12074   return true;
12075 }
12076
12077
12078 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12079   // Change br (not X), label True, label False to: br X, label False, True
12080   Value *X = 0;
12081   BasicBlock *TrueDest;
12082   BasicBlock *FalseDest;
12083   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12084       !isa<Constant>(X)) {
12085     // Swap Destinations and condition...
12086     BI.setCondition(X);
12087     BI.setSuccessor(0, FalseDest);
12088     BI.setSuccessor(1, TrueDest);
12089     return &BI;
12090   }
12091
12092   // Cannonicalize fcmp_one -> fcmp_oeq
12093   FCmpInst::Predicate FPred; Value *Y;
12094   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12095                              TrueDest, FalseDest), *Context))
12096     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12097          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12098       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12099       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12100       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12101       NewSCC->takeName(I);
12102       // Swap Destinations and condition...
12103       BI.setCondition(NewSCC);
12104       BI.setSuccessor(0, FalseDest);
12105       BI.setSuccessor(1, TrueDest);
12106       RemoveFromWorkList(I);
12107       I->eraseFromParent();
12108       AddToWorkList(NewSCC);
12109       return &BI;
12110     }
12111
12112   // Cannonicalize icmp_ne -> icmp_eq
12113   ICmpInst::Predicate IPred;
12114   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12115                       TrueDest, FalseDest), *Context))
12116     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12117          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12118          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12119       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12120       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12121       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12122       NewSCC->takeName(I);
12123       // Swap Destinations and condition...
12124       BI.setCondition(NewSCC);
12125       BI.setSuccessor(0, FalseDest);
12126       BI.setSuccessor(1, TrueDest);
12127       RemoveFromWorkList(I);
12128       I->eraseFromParent();;
12129       AddToWorkList(NewSCC);
12130       return &BI;
12131     }
12132
12133   return 0;
12134 }
12135
12136 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12137   Value *Cond = SI.getCondition();
12138   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12139     if (I->getOpcode() == Instruction::Add)
12140       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12141         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12142         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12143           SI.setOperand(i,
12144                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12145                                                 AddRHS));
12146         SI.setOperand(0, I->getOperand(0));
12147         AddToWorkList(I);
12148         return &SI;
12149       }
12150   }
12151   return 0;
12152 }
12153
12154 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12155   Value *Agg = EV.getAggregateOperand();
12156
12157   if (!EV.hasIndices())
12158     return ReplaceInstUsesWith(EV, Agg);
12159
12160   if (Constant *C = dyn_cast<Constant>(Agg)) {
12161     if (isa<UndefValue>(C))
12162       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12163       
12164     if (isa<ConstantAggregateZero>(C))
12165       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12166
12167     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12168       // Extract the element indexed by the first index out of the constant
12169       Value *V = C->getOperand(*EV.idx_begin());
12170       if (EV.getNumIndices() > 1)
12171         // Extract the remaining indices out of the constant indexed by the
12172         // first index
12173         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12174       else
12175         return ReplaceInstUsesWith(EV, V);
12176     }
12177     return 0; // Can't handle other constants
12178   } 
12179   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12180     // We're extracting from an insertvalue instruction, compare the indices
12181     const unsigned *exti, *exte, *insi, *inse;
12182     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12183          exte = EV.idx_end(), inse = IV->idx_end();
12184          exti != exte && insi != inse;
12185          ++exti, ++insi) {
12186       if (*insi != *exti)
12187         // The insert and extract both reference distinctly different elements.
12188         // This means the extract is not influenced by the insert, and we can
12189         // replace the aggregate operand of the extract with the aggregate
12190         // operand of the insert. i.e., replace
12191         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12192         // %E = extractvalue { i32, { i32 } } %I, 0
12193         // with
12194         // %E = extractvalue { i32, { i32 } } %A, 0
12195         return ExtractValueInst::Create(IV->getAggregateOperand(),
12196                                         EV.idx_begin(), EV.idx_end());
12197     }
12198     if (exti == exte && insi == inse)
12199       // Both iterators are at the end: Index lists are identical. Replace
12200       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12201       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12202       // with "i32 42"
12203       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12204     if (exti == exte) {
12205       // The extract list is a prefix of the insert list. i.e. replace
12206       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12207       // %E = extractvalue { i32, { i32 } } %I, 1
12208       // with
12209       // %X = extractvalue { i32, { i32 } } %A, 1
12210       // %E = insertvalue { i32 } %X, i32 42, 0
12211       // by switching the order of the insert and extract (though the
12212       // insertvalue should be left in, since it may have other uses).
12213       Value *NewEV = InsertNewInstBefore(
12214         ExtractValueInst::Create(IV->getAggregateOperand(),
12215                                  EV.idx_begin(), EV.idx_end()),
12216         EV);
12217       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12218                                      insi, inse);
12219     }
12220     if (insi == inse)
12221       // The insert list is a prefix of the extract list
12222       // We can simply remove the common indices from the extract and make it
12223       // operate on the inserted value instead of the insertvalue result.
12224       // i.e., replace
12225       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12226       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12227       // with
12228       // %E extractvalue { i32 } { i32 42 }, 0
12229       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12230                                       exti, exte);
12231   }
12232   // Can't simplify extracts from other values. Note that nested extracts are
12233   // already simplified implicitely by the above (extract ( extract (insert) )
12234   // will be translated into extract ( insert ( extract ) ) first and then just
12235   // the value inserted, if appropriate).
12236   return 0;
12237 }
12238
12239 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12240 /// is to leave as a vector operation.
12241 static bool CheapToScalarize(Value *V, bool isConstant) {
12242   if (isa<ConstantAggregateZero>(V)) 
12243     return true;
12244   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12245     if (isConstant) return true;
12246     // If all elts are the same, we can extract.
12247     Constant *Op0 = C->getOperand(0);
12248     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12249       if (C->getOperand(i) != Op0)
12250         return false;
12251     return true;
12252   }
12253   Instruction *I = dyn_cast<Instruction>(V);
12254   if (!I) return false;
12255   
12256   // Insert element gets simplified to the inserted element or is deleted if
12257   // this is constant idx extract element and its a constant idx insertelt.
12258   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12259       isa<ConstantInt>(I->getOperand(2)))
12260     return true;
12261   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12262     return true;
12263   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12264     if (BO->hasOneUse() &&
12265         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12266          CheapToScalarize(BO->getOperand(1), isConstant)))
12267       return true;
12268   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12269     if (CI->hasOneUse() &&
12270         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12271          CheapToScalarize(CI->getOperand(1), isConstant)))
12272       return true;
12273   
12274   return false;
12275 }
12276
12277 /// Read and decode a shufflevector mask.
12278 ///
12279 /// It turns undef elements into values that are larger than the number of
12280 /// elements in the input.
12281 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12282   unsigned NElts = SVI->getType()->getNumElements();
12283   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12284     return std::vector<unsigned>(NElts, 0);
12285   if (isa<UndefValue>(SVI->getOperand(2)))
12286     return std::vector<unsigned>(NElts, 2*NElts);
12287
12288   std::vector<unsigned> Result;
12289   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12290   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12291     if (isa<UndefValue>(*i))
12292       Result.push_back(NElts*2);  // undef -> 8
12293     else
12294       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12295   return Result;
12296 }
12297
12298 /// FindScalarElement - Given a vector and an element number, see if the scalar
12299 /// value is already around as a register, for example if it were inserted then
12300 /// extracted from the vector.
12301 static Value *FindScalarElement(Value *V, unsigned EltNo,
12302                                 LLVMContext *Context) {
12303   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12304   const VectorType *PTy = cast<VectorType>(V->getType());
12305   unsigned Width = PTy->getNumElements();
12306   if (EltNo >= Width)  // Out of range access.
12307     return Context->getUndef(PTy->getElementType());
12308   
12309   if (isa<UndefValue>(V))
12310     return Context->getUndef(PTy->getElementType());
12311   else if (isa<ConstantAggregateZero>(V))
12312     return Context->getNullValue(PTy->getElementType());
12313   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12314     return CP->getOperand(EltNo);
12315   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12316     // If this is an insert to a variable element, we don't know what it is.
12317     if (!isa<ConstantInt>(III->getOperand(2))) 
12318       return 0;
12319     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12320     
12321     // If this is an insert to the element we are looking for, return the
12322     // inserted value.
12323     if (EltNo == IIElt) 
12324       return III->getOperand(1);
12325     
12326     // Otherwise, the insertelement doesn't modify the value, recurse on its
12327     // vector input.
12328     return FindScalarElement(III->getOperand(0), EltNo, Context);
12329   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12330     unsigned LHSWidth =
12331       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12332     unsigned InEl = getShuffleMask(SVI)[EltNo];
12333     if (InEl < LHSWidth)
12334       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12335     else if (InEl < LHSWidth*2)
12336       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12337     else
12338       return Context->getUndef(PTy->getElementType());
12339   }
12340   
12341   // Otherwise, we don't know.
12342   return 0;
12343 }
12344
12345 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12346   // If vector val is undef, replace extract with scalar undef.
12347   if (isa<UndefValue>(EI.getOperand(0)))
12348     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12349
12350   // If vector val is constant 0, replace extract with scalar 0.
12351   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12352     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12353   
12354   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12355     // If vector val is constant with all elements the same, replace EI with
12356     // that element. When the elements are not identical, we cannot replace yet
12357     // (we do that below, but only when the index is constant).
12358     Constant *op0 = C->getOperand(0);
12359     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12360       if (C->getOperand(i) != op0) {
12361         op0 = 0; 
12362         break;
12363       }
12364     if (op0)
12365       return ReplaceInstUsesWith(EI, op0);
12366   }
12367
12368   unsigned VectorWidth = 
12369      cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12370
12371   // Canonicalize extractelement from a vector of width 1 to a bitcast
12372   if (VectorWidth == 1)
12373     return new BitCastInst(EI.getOperand(0), EI.getType());
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       
12380     // If this is extracting an invalid index, turn this into undef, to avoid
12381     // crashing the code below.
12382     if (IndexVal >= VectorWidth)
12383       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12384     
12385     // This instruction only demands the single element from the input vector.
12386     // If the input vector has a single use, simplify it based on this use
12387     // property.
12388     if (EI.getOperand(0)->hasOneUse()) {
12389       APInt UndefElts(VectorWidth, 0);
12390       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12391       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12392                                                 DemandedMask, UndefElts)) {
12393         EI.setOperand(0, V);
12394         return &EI;
12395       }
12396     }
12397     
12398     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12399       return ReplaceInstUsesWith(EI, Elt);
12400     
12401     // If the this extractelement is directly using a bitcast from a vector of
12402     // the same number of elements, see if we can find the source element from
12403     // it.  In this case, we will end up needing to bitcast the scalars.
12404     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12405       if (const VectorType *VT = 
12406               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12407         if (VT->getNumElements() == VectorWidth)
12408           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12409                                              IndexVal, Context))
12410             return new BitCastInst(Elt, EI.getType());
12411     }
12412   }
12413   
12414   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12415     if (I->hasOneUse()) {
12416       // Push extractelement into predecessor operation if legal and
12417       // profitable to do so
12418       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12419         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12420         if (CheapToScalarize(BO, isConstantElt)) {
12421           ExtractElementInst *newEI0 = 
12422             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12423                                    EI.getName()+".lhs");
12424           ExtractElementInst *newEI1 =
12425             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12426                                    EI.getName()+".rhs");
12427           InsertNewInstBefore(newEI0, EI);
12428           InsertNewInstBefore(newEI1, EI);
12429           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12430         }
12431       } else if (isa<LoadInst>(I)) {
12432         unsigned AS = 
12433           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12434         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12435                                   Context->getPointerType(EI.getType(), AS),EI);
12436         GetElementPtrInst *GEP =
12437           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12438         InsertNewInstBefore(GEP, EI);
12439         return new LoadInst(GEP);
12440       }
12441     }
12442     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12443       // Extracting the inserted element?
12444       if (IE->getOperand(2) == EI.getOperand(1))
12445         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12446       // If the inserted and extracted elements are constants, they must not
12447       // be the same value, extract from the pre-inserted value instead.
12448       if (isa<Constant>(IE->getOperand(2)) &&
12449           isa<Constant>(EI.getOperand(1))) {
12450         AddUsesToWorkList(EI);
12451         EI.setOperand(0, IE->getOperand(0));
12452         return &EI;
12453       }
12454     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12455       // If this is extracting an element from a shufflevector, figure out where
12456       // it came from and extract from the appropriate input element instead.
12457       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12458         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12459         Value *Src;
12460         unsigned LHSWidth =
12461           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12462
12463         if (SrcIdx < LHSWidth)
12464           Src = SVI->getOperand(0);
12465         else if (SrcIdx < LHSWidth*2) {
12466           SrcIdx -= LHSWidth;
12467           Src = SVI->getOperand(1);
12468         } else {
12469           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12470         }
12471         return new ExtractElementInst(Src,
12472                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12473       }
12474     }
12475   }
12476   return 0;
12477 }
12478
12479 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12480 /// elements from either LHS or RHS, return the shuffle mask and true. 
12481 /// Otherwise, return false.
12482 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12483                                          std::vector<Constant*> &Mask,
12484                                          LLVMContext *Context) {
12485   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12486          "Invalid CollectSingleShuffleElements");
12487   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12488
12489   if (isa<UndefValue>(V)) {
12490     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12491     return true;
12492   } else if (V == LHS) {
12493     for (unsigned i = 0; i != NumElts; ++i)
12494       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12495     return true;
12496   } else if (V == RHS) {
12497     for (unsigned i = 0; i != NumElts; ++i)
12498       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12499     return true;
12500   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12501     // If this is an insert of an extract from some other vector, include it.
12502     Value *VecOp    = IEI->getOperand(0);
12503     Value *ScalarOp = IEI->getOperand(1);
12504     Value *IdxOp    = IEI->getOperand(2);
12505     
12506     if (!isa<ConstantInt>(IdxOp))
12507       return false;
12508     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12509     
12510     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12511       // Okay, we can handle this if the vector we are insertinting into is
12512       // transitively ok.
12513       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12514         // If so, update the mask to reflect the inserted undef.
12515         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12516         return true;
12517       }      
12518     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12519       if (isa<ConstantInt>(EI->getOperand(1)) &&
12520           EI->getOperand(0)->getType() == V->getType()) {
12521         unsigned ExtractedIdx =
12522           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12523         
12524         // This must be extracting from either LHS or RHS.
12525         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12526           // Okay, we can handle this if the vector we are insertinting into is
12527           // transitively ok.
12528           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12529             // If so, update the mask to reflect the inserted value.
12530             if (EI->getOperand(0) == LHS) {
12531               Mask[InsertedIdx % NumElts] = 
12532                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12533             } else {
12534               assert(EI->getOperand(0) == RHS);
12535               Mask[InsertedIdx % NumElts] = 
12536                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12537               
12538             }
12539             return true;
12540           }
12541         }
12542       }
12543     }
12544   }
12545   // TODO: Handle shufflevector here!
12546   
12547   return false;
12548 }
12549
12550 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12551 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12552 /// that computes V and the LHS value of the shuffle.
12553 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12554                                      Value *&RHS, LLVMContext *Context) {
12555   assert(isa<VectorType>(V->getType()) && 
12556          (RHS == 0 || V->getType() == RHS->getType()) &&
12557          "Invalid shuffle!");
12558   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12559
12560   if (isa<UndefValue>(V)) {
12561     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12562     return V;
12563   } else if (isa<ConstantAggregateZero>(V)) {
12564     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12565     return V;
12566   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12567     // If this is an insert of an extract from some other vector, include it.
12568     Value *VecOp    = IEI->getOperand(0);
12569     Value *ScalarOp = IEI->getOperand(1);
12570     Value *IdxOp    = IEI->getOperand(2);
12571     
12572     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12573       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12574           EI->getOperand(0)->getType() == V->getType()) {
12575         unsigned ExtractedIdx =
12576           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12577         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12578         
12579         // Either the extracted from or inserted into vector must be RHSVec,
12580         // otherwise we'd end up with a shuffle of three inputs.
12581         if (EI->getOperand(0) == RHS || RHS == 0) {
12582           RHS = EI->getOperand(0);
12583           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12584           Mask[InsertedIdx % NumElts] = 
12585             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12586           return V;
12587         }
12588         
12589         if (VecOp == RHS) {
12590           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12591                                             RHS, Context);
12592           // Everything but the extracted element is replaced with the RHS.
12593           for (unsigned i = 0; i != NumElts; ++i) {
12594             if (i != InsertedIdx)
12595               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12596           }
12597           return V;
12598         }
12599         
12600         // If this insertelement is a chain that comes from exactly these two
12601         // vectors, return the vector and the effective shuffle.
12602         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12603                                          Context))
12604           return EI->getOperand(0);
12605         
12606       }
12607     }
12608   }
12609   // TODO: Handle shufflevector here!
12610   
12611   // Otherwise, can't do anything fancy.  Return an identity vector.
12612   for (unsigned i = 0; i != NumElts; ++i)
12613     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12614   return V;
12615 }
12616
12617 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12618   Value *VecOp    = IE.getOperand(0);
12619   Value *ScalarOp = IE.getOperand(1);
12620   Value *IdxOp    = IE.getOperand(2);
12621   
12622   // Inserting an undef or into an undefined place, remove this.
12623   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12624     ReplaceInstUsesWith(IE, VecOp);
12625
12626   unsigned NumVectorElts = IE.getType()->getNumElements();
12627
12628   // Canonicalize insertelement into vector of width 1 to a bitcast
12629   if (NumVectorElts == 1)
12630     return new BitCastInst(IE.getOperand(1), IE.getType());
12631
12632   // If the inserted element was extracted from some other vector, and if the 
12633   // indexes are constant, try to turn this into a shufflevector operation.
12634   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12635     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12636         EI->getOperand(0)->getType() == IE.getType()) {
12637       unsigned ExtractedIdx =
12638         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12639       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12640       
12641       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12642         return ReplaceInstUsesWith(IE, VecOp);
12643       
12644       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12645         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12646       
12647       // If we are extracting a value from a vector, then inserting it right
12648       // back into the same place, just use the input vector.
12649       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12650         return ReplaceInstUsesWith(IE, VecOp);      
12651       
12652       // We could theoretically do this for ANY input.  However, doing so could
12653       // turn chains of insertelement instructions into a chain of shufflevector
12654       // instructions, and right now we do not merge shufflevectors.  As such,
12655       // only do this in a situation where it is clear that there is benefit.
12656       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12657         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12658         // the values of VecOp, except then one read from EIOp0.
12659         // Build a new shuffle mask.
12660         std::vector<Constant*> Mask;
12661         if (isa<UndefValue>(VecOp))
12662           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12663         else {
12664           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12665           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12666                                                        NumVectorElts));
12667         } 
12668         Mask[InsertedIdx] = 
12669                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12670         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12671                                      Context->getConstantVector(Mask));
12672       }
12673       
12674       // If this insertelement isn't used by some other insertelement, turn it
12675       // (and any insertelements it points to), into one big shuffle.
12676       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12677         std::vector<Constant*> Mask;
12678         Value *RHS = 0;
12679         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12680         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12681         // We now have a shuffle of LHS, RHS, Mask.
12682         return new ShuffleVectorInst(LHS, RHS,
12683                                      Context->getConstantVector(Mask));
12684       }
12685     }
12686   }
12687
12688   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12689   APInt UndefElts(VWidth, 0);
12690   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12691   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12692     return &IE;
12693
12694   return 0;
12695 }
12696
12697
12698 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12699   Value *LHS = SVI.getOperand(0);
12700   Value *RHS = SVI.getOperand(1);
12701   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12702
12703   bool MadeChange = false;
12704
12705   // Undefined shuffle mask -> undefined value.
12706   if (isa<UndefValue>(SVI.getOperand(2)))
12707     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12708
12709   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12710
12711   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12712     return 0;
12713
12714   APInt UndefElts(VWidth, 0);
12715   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12716   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12717     LHS = SVI.getOperand(0);
12718     RHS = SVI.getOperand(1);
12719     MadeChange = true;
12720   }
12721   
12722   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12723   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12724   if (LHS == RHS || isa<UndefValue>(LHS)) {
12725     if (isa<UndefValue>(LHS) && LHS == RHS) {
12726       // shuffle(undef,undef,mask) -> undef.
12727       return ReplaceInstUsesWith(SVI, LHS);
12728     }
12729     
12730     // Remap any references to RHS to use LHS.
12731     std::vector<Constant*> Elts;
12732     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12733       if (Mask[i] >= 2*e)
12734         Elts.push_back(Context->getUndef(Type::Int32Ty));
12735       else {
12736         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12737             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12738           Mask[i] = 2*e;     // Turn into undef.
12739           Elts.push_back(Context->getUndef(Type::Int32Ty));
12740         } else {
12741           Mask[i] = Mask[i] % e;  // Force to LHS.
12742           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12743         }
12744       }
12745     }
12746     SVI.setOperand(0, SVI.getOperand(1));
12747     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12748     SVI.setOperand(2, Context->getConstantVector(Elts));
12749     LHS = SVI.getOperand(0);
12750     RHS = SVI.getOperand(1);
12751     MadeChange = true;
12752   }
12753   
12754   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12755   bool isLHSID = true, isRHSID = true;
12756     
12757   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12758     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12759     // Is this an identity shuffle of the LHS value?
12760     isLHSID &= (Mask[i] == i);
12761       
12762     // Is this an identity shuffle of the RHS value?
12763     isRHSID &= (Mask[i]-e == i);
12764   }
12765
12766   // Eliminate identity shuffles.
12767   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12768   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12769   
12770   // If the LHS is a shufflevector itself, see if we can combine it with this
12771   // one without producing an unusual shuffle.  Here we are really conservative:
12772   // we are absolutely afraid of producing a shuffle mask not in the input
12773   // program, because the code gen may not be smart enough to turn a merged
12774   // shuffle into two specific shuffles: it may produce worse code.  As such,
12775   // we only merge two shuffles if the result is one of the two input shuffle
12776   // masks.  In this case, merging the shuffles just removes one instruction,
12777   // which we know is safe.  This is good for things like turning:
12778   // (splat(splat)) -> splat.
12779   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12780     if (isa<UndefValue>(RHS)) {
12781       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12782
12783       std::vector<unsigned> NewMask;
12784       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12785         if (Mask[i] >= 2*e)
12786           NewMask.push_back(2*e);
12787         else
12788           NewMask.push_back(LHSMask[Mask[i]]);
12789       
12790       // If the result mask is equal to the src shuffle or this shuffle mask, do
12791       // the replacement.
12792       if (NewMask == LHSMask || NewMask == Mask) {
12793         unsigned LHSInNElts =
12794           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12795         std::vector<Constant*> Elts;
12796         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12797           if (NewMask[i] >= LHSInNElts*2) {
12798             Elts.push_back(Context->getUndef(Type::Int32Ty));
12799           } else {
12800             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12801           }
12802         }
12803         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12804                                      LHSSVI->getOperand(1),
12805                                      Context->getConstantVector(Elts));
12806       }
12807     }
12808   }
12809
12810   return MadeChange ? &SVI : 0;
12811 }
12812
12813
12814
12815
12816 /// TryToSinkInstruction - Try to move the specified instruction from its
12817 /// current block into the beginning of DestBlock, which can only happen if it's
12818 /// safe to move the instruction past all of the instructions between it and the
12819 /// end of its block.
12820 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12821   assert(I->hasOneUse() && "Invariants didn't hold!");
12822
12823   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12824   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12825     return false;
12826
12827   // Do not sink alloca instructions out of the entry block.
12828   if (isa<AllocaInst>(I) && I->getParent() ==
12829         &DestBlock->getParent()->getEntryBlock())
12830     return false;
12831
12832   // We can only sink load instructions if there is nothing between the load and
12833   // the end of block that could change the value.
12834   if (I->mayReadFromMemory()) {
12835     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12836          Scan != E; ++Scan)
12837       if (Scan->mayWriteToMemory())
12838         return false;
12839   }
12840
12841   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12842
12843   CopyPrecedingStopPoint(I, InsertPos);
12844   I->moveBefore(InsertPos);
12845   ++NumSunkInst;
12846   return true;
12847 }
12848
12849
12850 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12851 /// all reachable code to the worklist.
12852 ///
12853 /// This has a couple of tricks to make the code faster and more powerful.  In
12854 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12855 /// them to the worklist (this significantly speeds up instcombine on code where
12856 /// many instructions are dead or constant).  Additionally, if we find a branch
12857 /// whose condition is a known constant, we only visit the reachable successors.
12858 ///
12859 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12860                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12861                                        InstCombiner &IC,
12862                                        const TargetData *TD) {
12863   SmallVector<BasicBlock*, 256> Worklist;
12864   Worklist.push_back(BB);
12865
12866   while (!Worklist.empty()) {
12867     BB = Worklist.back();
12868     Worklist.pop_back();
12869     
12870     // We have now visited this block!  If we've already been here, ignore it.
12871     if (!Visited.insert(BB)) continue;
12872
12873     DbgInfoIntrinsic *DBI_Prev = NULL;
12874     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12875       Instruction *Inst = BBI++;
12876       
12877       // DCE instruction if trivially dead.
12878       if (isInstructionTriviallyDead(Inst)) {
12879         ++NumDeadInst;
12880         DOUT << "IC: DCE: " << *Inst;
12881         Inst->eraseFromParent();
12882         continue;
12883       }
12884       
12885       // ConstantProp instruction if trivially constant.
12886       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12887         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12888         Inst->replaceAllUsesWith(C);
12889         ++NumConstProp;
12890         Inst->eraseFromParent();
12891         continue;
12892       }
12893      
12894       // If there are two consecutive llvm.dbg.stoppoint calls then
12895       // it is likely that the optimizer deleted code in between these
12896       // two intrinsics. 
12897       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12898       if (DBI_Next) {
12899         if (DBI_Prev
12900             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12901             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12902           IC.RemoveFromWorkList(DBI_Prev);
12903           DBI_Prev->eraseFromParent();
12904         }
12905         DBI_Prev = DBI_Next;
12906       } else {
12907         DBI_Prev = 0;
12908       }
12909
12910       IC.AddToWorkList(Inst);
12911     }
12912
12913     // Recursively visit successors.  If this is a branch or switch on a
12914     // constant, only visit the reachable successor.
12915     TerminatorInst *TI = BB->getTerminator();
12916     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12917       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12918         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12919         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12920         Worklist.push_back(ReachableBB);
12921         continue;
12922       }
12923     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12924       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12925         // See if this is an explicit destination.
12926         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12927           if (SI->getCaseValue(i) == Cond) {
12928             BasicBlock *ReachableBB = SI->getSuccessor(i);
12929             Worklist.push_back(ReachableBB);
12930             continue;
12931           }
12932         
12933         // Otherwise it is the default destination.
12934         Worklist.push_back(SI->getSuccessor(0));
12935         continue;
12936       }
12937     }
12938     
12939     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12940       Worklist.push_back(TI->getSuccessor(i));
12941   }
12942 }
12943
12944 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12945   bool Changed = false;
12946   TD = &getAnalysis<TargetData>();
12947   
12948   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12949              << F.getNameStr() << "\n");
12950
12951   {
12952     // Do a depth-first traversal of the function, populate the worklist with
12953     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12954     // track of which blocks we visit.
12955     SmallPtrSet<BasicBlock*, 64> Visited;
12956     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12957
12958     // Do a quick scan over the function.  If we find any blocks that are
12959     // unreachable, remove any instructions inside of them.  This prevents
12960     // the instcombine code from having to deal with some bad special cases.
12961     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12962       if (!Visited.count(BB)) {
12963         Instruction *Term = BB->getTerminator();
12964         while (Term != BB->begin()) {   // Remove instrs bottom-up
12965           BasicBlock::iterator I = Term; --I;
12966
12967           DOUT << "IC: DCE: " << *I;
12968           // A debug intrinsic shouldn't force another iteration if we weren't
12969           // going to do one without it.
12970           if (!isa<DbgInfoIntrinsic>(I)) {
12971             ++NumDeadInst;
12972             Changed = true;
12973           }
12974           if (!I->use_empty())
12975             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12976           I->eraseFromParent();
12977         }
12978       }
12979   }
12980
12981   while (!Worklist.empty()) {
12982     Instruction *I = RemoveOneFromWorkList();
12983     if (I == 0) continue;  // skip null values.
12984
12985     // Check to see if we can DCE the instruction.
12986     if (isInstructionTriviallyDead(I)) {
12987       // Add operands to the worklist.
12988       if (I->getNumOperands() < 4)
12989         AddUsesToWorkList(*I);
12990       ++NumDeadInst;
12991
12992       DOUT << "IC: DCE: " << *I;
12993
12994       I->eraseFromParent();
12995       RemoveFromWorkList(I);
12996       Changed = true;
12997       continue;
12998     }
12999
13000     // Instruction isn't dead, see if we can constant propagate it.
13001     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13002       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13003
13004       // Add operands to the worklist.
13005       AddUsesToWorkList(*I);
13006       ReplaceInstUsesWith(*I, C);
13007
13008       ++NumConstProp;
13009       I->eraseFromParent();
13010       RemoveFromWorkList(I);
13011       Changed = true;
13012       continue;
13013     }
13014
13015     if (TD) {
13016       // See if we can constant fold its operands.
13017       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13018         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13019           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13020                                   F.getContext(), TD))
13021             if (NewC != CE) {
13022               i->set(NewC);
13023               Changed = true;
13024             }
13025     }
13026
13027     // See if we can trivially sink this instruction to a successor basic block.
13028     if (I->hasOneUse()) {
13029       BasicBlock *BB = I->getParent();
13030       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13031       if (UserParent != BB) {
13032         bool UserIsSuccessor = false;
13033         // See if the user is one of our successors.
13034         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13035           if (*SI == UserParent) {
13036             UserIsSuccessor = true;
13037             break;
13038           }
13039
13040         // If the user is one of our immediate successors, and if that successor
13041         // only has us as a predecessors (we'd have to split the critical edge
13042         // otherwise), we can keep going.
13043         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13044             next(pred_begin(UserParent)) == pred_end(UserParent))
13045           // Okay, the CFG is simple enough, try to sink this instruction.
13046           Changed |= TryToSinkInstruction(I, UserParent);
13047       }
13048     }
13049
13050     // Now that we have an instruction, try combining it to simplify it...
13051 #ifndef NDEBUG
13052     std::string OrigI;
13053 #endif
13054     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13055     if (Instruction *Result = visit(*I)) {
13056       ++NumCombined;
13057       // Should we replace the old instruction with a new one?
13058       if (Result != I) {
13059         DOUT << "IC: Old = " << *I
13060              << "    New = " << *Result;
13061
13062         // Everything uses the new instruction now.
13063         I->replaceAllUsesWith(Result);
13064
13065         // Push the new instruction and any users onto the worklist.
13066         AddToWorkList(Result);
13067         AddUsersToWorkList(*Result);
13068
13069         // Move the name to the new instruction first.
13070         Result->takeName(I);
13071
13072         // Insert the new instruction into the basic block...
13073         BasicBlock *InstParent = I->getParent();
13074         BasicBlock::iterator InsertPos = I;
13075
13076         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13077           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13078             ++InsertPos;
13079
13080         InstParent->getInstList().insert(InsertPos, Result);
13081
13082         // Make sure that we reprocess all operands now that we reduced their
13083         // use counts.
13084         AddUsesToWorkList(*I);
13085
13086         // Instructions can end up on the worklist more than once.  Make sure
13087         // we do not process an instruction that has been deleted.
13088         RemoveFromWorkList(I);
13089
13090         // Erase the old instruction.
13091         InstParent->getInstList().erase(I);
13092       } else {
13093 #ifndef NDEBUG
13094         DOUT << "IC: Mod = " << OrigI
13095              << "    New = " << *I;
13096 #endif
13097
13098         // If the instruction was modified, it's possible that it is now dead.
13099         // if so, remove it.
13100         if (isInstructionTriviallyDead(I)) {
13101           // Make sure we process all operands now that we are reducing their
13102           // use counts.
13103           AddUsesToWorkList(*I);
13104
13105           // Instructions may end up in the worklist more than once.  Erase all
13106           // occurrences of this instruction.
13107           RemoveFromWorkList(I);
13108           I->eraseFromParent();
13109         } else {
13110           AddToWorkList(I);
13111           AddUsersToWorkList(*I);
13112         }
13113       }
13114       Changed = true;
13115     }
13116   }
13117
13118   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13119     
13120   // Do an explicit clear, this shrinks the map if needed.
13121   WorklistMap.clear();
13122   return Changed;
13123 }
13124
13125
13126 bool InstCombiner::runOnFunction(Function &F) {
13127   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13128   
13129   bool EverMadeChange = false;
13130
13131   // Iterate while there is work to do.
13132   unsigned Iteration = 0;
13133   while (DoOneIteration(F, Iteration++))
13134     EverMadeChange = true;
13135   return EverMadeChange;
13136 }
13137
13138 FunctionPass *llvm::createInstructionCombiningPass() {
13139   return new InstCombiner();
13140 }