Make BasicAliasAnalysis and Value::getUnderlyingObject use
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/SmallPtrSet.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include <algorithm>
64 #include <climits>
65 #include <sstream>
66 using namespace llvm;
67 using namespace llvm::PatternMatch;
68
69 STATISTIC(NumCombined , "Number of insts combined");
70 STATISTIC(NumConstProp, "Number of constant folds");
71 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73 STATISTIC(NumSunkInst , "Number of instructions sunk");
74
75 namespace {
76   class VISIBILITY_HIDDEN InstCombiner
77     : public FunctionPass,
78       public InstVisitor<InstCombiner, Instruction*> {
79     // Worklist of all of the instructions that need to be simplified.
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     TargetData *TD;
83     bool MustPreserveLCSSA;
84   public:
85     static char ID; // Pass identification, replacement for typeid
86     InstCombiner() : FunctionPass(&ID) {}
87
88     LLVMContext *getContext() { return Context; }
89
90     /// AddToWorkList - Add the specified instruction to the worklist if it
91     /// isn't already in it.
92     void AddToWorkList(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     // RemoveFromWorkList - remove I from the worklist if it exists.
98     void RemoveFromWorkList(Instruction *I) {
99       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100       if (It == WorklistMap.end()) return; // Not in worklist.
101       
102       // Don't bother moving everything down, just null out the slot.
103       Worklist[It->second] = 0;
104       
105       WorklistMap.erase(It);
106     }
107     
108     Instruction *RemoveOneFromWorkList() {
109       Instruction *I = Worklist.back();
110       Worklist.pop_back();
111       WorklistMap.erase(I);
112       return I;
113     }
114
115     
116     /// AddUsersToWorkList - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorkList(Value &I) {
121       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
122            UI != UE; ++UI)
123         AddToWorkList(cast<Instruction>(*UI));
124     }
125
126     /// AddUsesToWorkList - When an instruction is simplified, add operands to
127     /// the work lists because they might get more simplified now.
128     ///
129     void AddUsesToWorkList(Instruction &I) {
130       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
131         if (Instruction *Op = dyn_cast<Instruction>(*i))
132           AddToWorkList(Op);
133     }
134     
135     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
136     /// dead.  Add all of its operands to the worklist, turning them into
137     /// undef's to reduce the number of uses of those instructions.
138     ///
139     /// Return the specified operand before it is turned into an undef.
140     ///
141     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
142       Value *R = I.getOperand(op);
143       
144       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
145         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
146           AddToWorkList(Op);
147           // Set the operand to undef to drop the use.
148           *i = Context->getUndef(Op->getType());
149         }
150       
151       return R;
152     }
153
154   public:
155     virtual bool runOnFunction(Function &F);
156     
157     bool DoOneIteration(Function &F, unsigned ItNum);
158
159     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
160       AU.addRequired<TargetData>();
161       AU.addPreservedID(LCSSAID);
162       AU.setPreservesCFG();
163     }
164
165     TargetData &getTargetData() const { return *TD; }
166
167     // Visitation implementation - Implement instruction combining for different
168     // instruction types.  The semantics are as follows:
169     // Return Value:
170     //    null        - No change was made
171     //     I          - Change was made, I is still valid, I may be dead though
172     //   otherwise    - Change was made, replace I with returned instruction
173     //
174     Instruction *visitAdd(BinaryOperator &I);
175     Instruction *visitFAdd(BinaryOperator &I);
176     Instruction *visitSub(BinaryOperator &I);
177     Instruction *visitFSub(BinaryOperator &I);
178     Instruction *visitMul(BinaryOperator &I);
179     Instruction *visitFMul(BinaryOperator &I);
180     Instruction *visitURem(BinaryOperator &I);
181     Instruction *visitSRem(BinaryOperator &I);
182     Instruction *visitFRem(BinaryOperator &I);
183     bool SimplifyDivRemOfSelect(BinaryOperator &I);
184     Instruction *commonRemTransforms(BinaryOperator &I);
185     Instruction *commonIRemTransforms(BinaryOperator &I);
186     Instruction *commonDivTransforms(BinaryOperator &I);
187     Instruction *commonIDivTransforms(BinaryOperator &I);
188     Instruction *visitUDiv(BinaryOperator &I);
189     Instruction *visitSDiv(BinaryOperator &I);
190     Instruction *visitFDiv(BinaryOperator &I);
191     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
192     Instruction *visitAnd(BinaryOperator &I);
193     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
194     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
195                                      Value *A, Value *B, Value *C);
196     Instruction *visitOr (BinaryOperator &I);
197     Instruction *visitXor(BinaryOperator &I);
198     Instruction *visitShl(BinaryOperator &I);
199     Instruction *visitAShr(BinaryOperator &I);
200     Instruction *visitLShr(BinaryOperator &I);
201     Instruction *commonShiftTransforms(BinaryOperator &I);
202     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203                                       Constant *RHSC);
204     Instruction *visitFCmpInst(FCmpInst &I);
205     Instruction *visitICmpInst(ICmpInst &I);
206     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
207     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208                                                 Instruction *LHS,
209                                                 ConstantInt *RHS);
210     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211                                 ConstantInt *DivRHS);
212
213     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214                              ICmpInst::Predicate Cond, Instruction &I);
215     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
216                                      BinaryOperator &I);
217     Instruction *commonCastTransforms(CastInst &CI);
218     Instruction *commonIntCastTransforms(CastInst &CI);
219     Instruction *commonPointerCastTransforms(CastInst &CI);
220     Instruction *visitTrunc(TruncInst &CI);
221     Instruction *visitZExt(ZExtInst &CI);
222     Instruction *visitSExt(SExtInst &CI);
223     Instruction *visitFPTrunc(FPTruncInst &CI);
224     Instruction *visitFPExt(CastInst &CI);
225     Instruction *visitFPToUI(FPToUIInst &FI);
226     Instruction *visitFPToSI(FPToSIInst &FI);
227     Instruction *visitUIToFP(CastInst &CI);
228     Instruction *visitSIToFP(CastInst &CI);
229     Instruction *visitPtrToInt(PtrToIntInst &CI);
230     Instruction *visitIntToPtr(IntToPtrInst &CI);
231     Instruction *visitBitCast(BitCastInst &CI);
232     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233                                 Instruction *FI);
234     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
235     Instruction *visitSelectInst(SelectInst &SI);
236     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
237     Instruction *visitCallInst(CallInst &CI);
238     Instruction *visitInvokeInst(InvokeInst &II);
239     Instruction *visitPHINode(PHINode &PN);
240     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
241     Instruction *visitAllocationInst(AllocationInst &AI);
242     Instruction *visitFreeInst(FreeInst &FI);
243     Instruction *visitLoadInst(LoadInst &LI);
244     Instruction *visitStoreInst(StoreInst &SI);
245     Instruction *visitBranchInst(BranchInst &BI);
246     Instruction *visitSwitchInst(SwitchInst &SI);
247     Instruction *visitInsertElementInst(InsertElementInst &IE);
248     Instruction *visitExtractElementInst(ExtractElementInst &EI);
249     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
250     Instruction *visitExtractValueInst(ExtractValueInst &EV);
251
252     // visitInstruction - Specify what to return for unhandled instructions...
253     Instruction *visitInstruction(Instruction &I) { return 0; }
254
255   private:
256     Instruction *visitCallSite(CallSite CS);
257     bool transformConstExprCastCall(CallSite CS);
258     Instruction *transformCallThroughTrampoline(CallSite CS);
259     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260                                    bool DoXform = true);
261     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
262     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
264
265   public:
266     // InsertNewInstBefore - insert an instruction New before instruction Old
267     // in the program.  Add the new instruction to the worklist.
268     //
269     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
270       assert(New && New->getParent() == 0 &&
271              "New instruction already inserted into a basic block!");
272       BasicBlock *BB = Old.getParent();
273       BB->getInstList().insert(&Old, New);  // Insert inst
274       AddToWorkList(New);
275       return New;
276     }
277
278     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279     /// This also adds the cast to the worklist.  Finally, this returns the
280     /// cast.
281     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282                             Instruction &Pos) {
283       if (V->getType() == Ty) return V;
284
285       if (Constant *CV = dyn_cast<Constant>(V))
286         return Context->getConstantExprCast(opc, CV, Ty);
287       
288       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
289       AddToWorkList(C);
290       return C;
291     }
292         
293     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295     }
296
297
298     // ReplaceInstUsesWith - This method is to be used when an instruction is
299     // found to be dead, replacable with another preexisting expression.  Here
300     // we add all uses of I to the worklist, replace all uses of I with the new
301     // value, then return I, so that the inst combiner will know that I was
302     // modified.
303     //
304     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
305       AddUsersToWorkList(I);         // Add all modified instrs to worklist
306       if (&I != V) {
307         I.replaceAllUsesWith(V);
308         return &I;
309       } else {
310         // If we are replacing the instruction with itself, this must be in a
311         // segment of unreachable code, so just clobber the instruction.
312         I.replaceAllUsesWith(Context->getUndef(I.getType()));
313         return &I;
314       }
315     }
316
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343
344     /// SimplifyCommutative - This performs a few simplifications for 
345     /// commutative operators.
346     bool SimplifyCommutative(BinaryOperator &I);
347
348     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349     /// most-complex to least-complex order.
350     bool SimplifyCompare(CmpInst &I);
351
352     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353     /// based on the demanded bits.
354     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
355                                    APInt& KnownZero, APInt& KnownOne,
356                                    unsigned Depth);
357     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
358                               APInt& KnownZero, APInt& KnownOne,
359                               unsigned Depth=0);
360         
361     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362     /// SimplifyDemandedBits knows about.  See if the instruction has any
363     /// properties that allow us to simplify its operands.
364     bool SimplifyDemandedInstructionBits(Instruction &Inst);
365         
366     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367                                       APInt& UndefElts, unsigned Depth = 0);
368       
369     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370     // PHI node as operand #0, see if we can fold the instruction into the PHI
371     // (which is only possible if all operands to the PHI are constants).
372     Instruction *FoldOpIntoPhi(Instruction &I);
373
374     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375     // operator and they all are only used by the PHI, PHI together their
376     // inputs, and do the operation once, to the result of the PHI.
377     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
381     
382     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
384     
385     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
386                               bool isSub, Instruction &I);
387     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
388                                  bool isSigned, bool Inside, Instruction &IB);
389     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
390     Instruction *MatchBSwap(BinaryOperator &I);
391     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
392     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
393     Instruction *SimplifyMemSet(MemSetInst *MI);
394
395
396     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397
398     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
399                                     unsigned CastOpc, int &NumCastsRemoved);
400     unsigned GetOrEnforceKnownAlignment(Value *V,
401                                         unsigned PrefAlign = 0);
402
403   };
404 }
405
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
409
410 // getComplexity:  Assign a complexity or rank value to LLVM Values...
411 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(LLVMContext *Context, Value *V) {
413   if (isa<Instruction>(V)) {
414     if (BinaryOperator::isNeg(V) ||
415         BinaryOperator::isFNeg(V) ||
416         BinaryOperator::isNot(V))
417       return 3;
418     return 4;
419   }
420   if (isa<Argument>(V)) return 3;
421   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
422 }
423
424 // isOnlyUse - Return true if this instruction will be deleted if we stop using
425 // it.
426 static bool isOnlyUse(Value *V) {
427   return V->hasOneUse() || isa<Constant>(V);
428 }
429
430 // getPromotedType - Return the specified type promoted as it would be to pass
431 // though a va_arg area...
432 static const Type *getPromotedType(const Type *Ty) {
433   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434     if (ITy->getBitWidth() < 32)
435       return Type::Int32Ty;
436   }
437   return Ty;
438 }
439
440 /// getBitCastOperand - If the specified operand is a CastInst, a constant
441 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442 /// operand value, otherwise return null.
443 static Value *getBitCastOperand(Value *V) {
444   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
445     // BitCastInst?
446     return I->getOperand(0);
447   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
448     // GetElementPtrInst?
449     if (GEP->hasAllZeroIndices())
450       return GEP->getOperand(0);
451   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
452     if (CE->getOpcode() == Instruction::BitCast)
453       // BitCast ConstantExp?
454       return CE->getOperand(0);
455     else if (CE->getOpcode() == Instruction::GetElementPtr) {
456       // GetElementPtr ConstantExp?
457       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
458            I != E; ++I) {
459         ConstantInt *CI = dyn_cast<ConstantInt>(I);
460         if (!CI || !CI->isZero())
461           // Any non-zero indices? Not cast-like.
462           return 0;
463       }
464       // All-zero indices? This is just like casting.
465       return CE->getOperand(0);
466     }
467   }
468   return 0;
469 }
470
471 /// This function is a wrapper around CastInst::isEliminableCastPair. It
472 /// simply extracts arguments and returns what that function returns.
473 static Instruction::CastOps 
474 isEliminableCastPair(
475   const CastInst *CI, ///< The first cast instruction
476   unsigned opcode,       ///< The opcode of the second cast instruction
477   const Type *DstTy,     ///< The target type for the second cast instruction
478   TargetData *TD         ///< The target data for pointer size
479 ) {
480   
481   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
482   const Type *MidTy = CI->getType();                  // B from above
483
484   // Get the opcodes of the two Cast instructions
485   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
486   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
487
488   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
489                                                 DstTy, TD->getIntPtrType());
490   
491   // We don't want to form an inttoptr or ptrtoint that converts to an integer
492   // type that differs from the pointer size.
493   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
494       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
495     Res = 0;
496   
497   return Instruction::CastOps(Res);
498 }
499
500 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501 /// in any code being generated.  It does not require codegen if V is simple
502 /// enough or if the cast can be folded into other casts.
503 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
504                               const Type *Ty, TargetData *TD) {
505   if (V->getType() == Ty || isa<Constant>(V)) return false;
506   
507   // If this is another cast that can be eliminated, it isn't codegen either.
508   if (const CastInst *CI = dyn_cast<CastInst>(V))
509     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
510       return false;
511   return true;
512 }
513
514 // SimplifyCommutative - This performs a few simplifications for commutative
515 // operators:
516 //
517 //  1. Order operands such that they are listed from right (least complex) to
518 //     left (most complex).  This puts constants before unary operators before
519 //     binary operators.
520 //
521 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
523 //
524 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
525   bool Changed = false;
526   if (getComplexity(Context, I.getOperand(0)) < 
527       getComplexity(Context, I.getOperand(1)))
528     Changed = !I.swapOperands();
529
530   if (!I.isAssociative()) return Changed;
531   Instruction::BinaryOps Opcode = I.getOpcode();
532   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
533     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
534       if (isa<Constant>(I.getOperand(1))) {
535         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
536                                              cast<Constant>(I.getOperand(1)),
537                                              cast<Constant>(Op->getOperand(1)));
538         I.setOperand(0, Op->getOperand(0));
539         I.setOperand(1, Folded);
540         return true;
541       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
542         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
543             isOnlyUse(Op) && isOnlyUse(Op1)) {
544           Constant *C1 = cast<Constant>(Op->getOperand(1));
545           Constant *C2 = cast<Constant>(Op1->getOperand(1));
546
547           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
548           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
549           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
550                                                     Op1->getOperand(0),
551                                                     Op1->getName(), &I);
552           AddToWorkList(New);
553           I.setOperand(0, New);
554           I.setOperand(1, Folded);
555           return true;
556         }
557     }
558   return Changed;
559 }
560
561 /// SimplifyCompare - For a CmpInst this function just orders the operands
562 /// so that theyare listed from right (least complex) to left (most complex).
563 /// This puts constants before unary operators before binary operators.
564 bool InstCombiner::SimplifyCompare(CmpInst &I) {
565   if (getComplexity(Context, I.getOperand(0)) >=
566       getComplexity(Context, I.getOperand(1)))
567     return false;
568   I.swapOperands();
569   // Compare instructions are not associative so there's nothing else we can do.
570   return true;
571 }
572
573 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
574 // if the LHS is a constant zero (which is the 'negate' form).
575 //
576 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
577   if (BinaryOperator::isNeg(V))
578     return BinaryOperator::getNegArgument(V);
579
580   // Constants can be considered to be negated values if they can be folded.
581   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
582     return Context->getConstantExprNeg(C);
583
584   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
585     if (C->getType()->getElementType()->isInteger())
586       return Context->getConstantExprNeg(C);
587
588   return 0;
589 }
590
591 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
592 // instruction if the LHS is a constant negative zero (which is the 'negate'
593 // form).
594 //
595 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
596   if (BinaryOperator::isFNeg(V))
597     return BinaryOperator::getFNegArgument(V);
598
599   // Constants can be considered to be negated values if they can be folded.
600   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
601     return Context->getConstantExprFNeg(C);
602
603   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
604     if (C->getType()->getElementType()->isFloatingPoint())
605       return Context->getConstantExprFNeg(C);
606
607   return 0;
608 }
609
610 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
611   if (BinaryOperator::isNot(V))
612     return BinaryOperator::getNotArgument(V);
613
614   // Constants can be considered to be not'ed values...
615   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
616     return Context->getConstantInt(~C->getValue());
617   return 0;
618 }
619
620 // dyn_castFoldableMul - If this value is a multiply that can be folded into
621 // other computations (because it has a constant operand), return the
622 // non-constant operand of the multiply, and set CST to point to the multiplier.
623 // Otherwise, return null.
624 //
625 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
626                                          LLVMContext *Context) {
627   if (V->hasOneUse() && V->getType()->isInteger())
628     if (Instruction *I = dyn_cast<Instruction>(V)) {
629       if (I->getOpcode() == Instruction::Mul)
630         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
631           return I->getOperand(0);
632       if (I->getOpcode() == Instruction::Shl)
633         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
634           // The multiplier is really 1 << CST.
635           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
636           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
637           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
638           return I->getOperand(0);
639         }
640     }
641   return 0;
642 }
643
644 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
645 /// expression, return it.
646 static User *dyn_castGetElementPtr(Value *V) {
647   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
648   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
649     if (CE->getOpcode() == Instruction::GetElementPtr)
650       return cast<User>(V);
651   return false;
652 }
653
654 /// AddOne - Add one to a ConstantInt
655 static Constant *AddOne(Constant *C, LLVMContext *Context) {
656   return Context->getConstantExprAdd(C, 
657     Context->getConstantInt(C->getType(), 1));
658 }
659 /// SubOne - Subtract one from a ConstantInt
660 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
661   return Context->getConstantExprSub(C, 
662     Context->getConstantInt(C->getType(), 1));
663 }
664 /// MultiplyOverflows - True if the multiply can not be expressed in an int
665 /// this size.
666 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
667                               LLVMContext *Context) {
668   uint32_t W = C1->getBitWidth();
669   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
670   if (sign) {
671     LHSExt.sext(W * 2);
672     RHSExt.sext(W * 2);
673   } else {
674     LHSExt.zext(W * 2);
675     RHSExt.zext(W * 2);
676   }
677
678   APInt MulExt = LHSExt * RHSExt;
679
680   if (sign) {
681     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
682     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
683     return MulExt.slt(Min) || MulExt.sgt(Max);
684   } else 
685     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
686 }
687
688
689 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
690 /// specified instruction is a constant integer.  If so, check to see if there
691 /// are any bits set in the constant that are not demanded.  If so, shrink the
692 /// constant and return true.
693 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
694                                    APInt Demanded, LLVMContext *Context) {
695   assert(I && "No instruction?");
696   assert(OpNo < I->getNumOperands() && "Operand index too large");
697
698   // If the operand is not a constant integer, nothing to do.
699   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
700   if (!OpC) return false;
701
702   // If there are no bits set that aren't demanded, nothing to do.
703   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
704   if ((~Demanded & OpC->getValue()) == 0)
705     return false;
706
707   // This instruction is producing bits that are not demanded. Shrink the RHS.
708   Demanded &= OpC->getValue();
709   I->setOperand(OpNo, Context->getConstantInt(Demanded));
710   return true;
711 }
712
713 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
714 // set of known zero and one bits, compute the maximum and minimum values that
715 // could have the specified known zero and known one bits, returning them in
716 // min/max.
717 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
718                                                    const APInt& KnownOne,
719                                                    APInt& Min, APInt& Max) {
720   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721          KnownZero.getBitWidth() == Min.getBitWidth() &&
722          KnownZero.getBitWidth() == Max.getBitWidth() &&
723          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
724   APInt UnknownBits = ~(KnownZero|KnownOne);
725
726   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
727   // bit if it is unknown.
728   Min = KnownOne;
729   Max = KnownOne|UnknownBits;
730   
731   if (UnknownBits.isNegative()) { // Sign bit is unknown
732     Min.set(Min.getBitWidth()-1);
733     Max.clear(Max.getBitWidth()-1);
734   }
735 }
736
737 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
738 // a set of known zero and one bits, compute the maximum and minimum values that
739 // could have the specified known zero and known one bits, returning them in
740 // min/max.
741 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
742                                                      const APInt &KnownOne,
743                                                      APInt &Min, APInt &Max) {
744   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
745          KnownZero.getBitWidth() == Min.getBitWidth() &&
746          KnownZero.getBitWidth() == Max.getBitWidth() &&
747          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
748   APInt UnknownBits = ~(KnownZero|KnownOne);
749   
750   // The minimum value is when the unknown bits are all zeros.
751   Min = KnownOne;
752   // The maximum value is when the unknown bits are all ones.
753   Max = KnownOne|UnknownBits;
754 }
755
756 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
757 /// SimplifyDemandedBits knows about.  See if the instruction has any
758 /// properties that allow us to simplify its operands.
759 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
760   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
761   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
762   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
763   
764   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
765                                      KnownZero, KnownOne, 0);
766   if (V == 0) return false;
767   if (V == &Inst) return true;
768   ReplaceInstUsesWith(Inst, V);
769   return true;
770 }
771
772 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
773 /// specified instruction operand if possible, updating it in place.  It returns
774 /// true if it made any change and false otherwise.
775 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
776                                         APInt &KnownZero, APInt &KnownOne,
777                                         unsigned Depth) {
778   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
779                                           KnownZero, KnownOne, Depth);
780   if (NewVal == 0) return false;
781   U.set(NewVal);
782   return true;
783 }
784
785
786 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
787 /// value based on the demanded bits.  When this function is called, it is known
788 /// that only the bits set in DemandedMask of the result of V are ever used
789 /// downstream. Consequently, depending on the mask and V, it may be possible
790 /// to replace V with a constant or one of its operands. In such cases, this
791 /// function does the replacement and returns true. In all other cases, it
792 /// returns false after analyzing the expression and setting KnownOne and known
793 /// to be one in the expression.  KnownZero contains all the bits that are known
794 /// to be zero in the expression. These are provided to potentially allow the
795 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
796 /// the expression. KnownOne and KnownZero always follow the invariant that 
797 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
798 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
799 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
800 /// and KnownOne must all be the same.
801 ///
802 /// This returns null if it did not change anything and it permits no
803 /// simplification.  This returns V itself if it did some simplification of V's
804 /// operands based on the information about what bits are demanded. This returns
805 /// some other non-null value if it found out that V is equal to another value
806 /// in the context where the specified bits are demanded, but not for all users.
807 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
808                                              APInt &KnownZero, APInt &KnownOne,
809                                              unsigned Depth) {
810   assert(V != 0 && "Null pointer of Value???");
811   assert(Depth <= 6 && "Limit Search Depth");
812   uint32_t BitWidth = DemandedMask.getBitWidth();
813   const Type *VTy = V->getType();
814   assert((TD || !isa<PointerType>(VTy)) &&
815          "SimplifyDemandedBits needs to know bit widths!");
816   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
817          (!VTy->isIntOrIntVector() ||
818           VTy->getScalarSizeInBits() == BitWidth) &&
819          KnownZero.getBitWidth() == BitWidth &&
820          KnownOne.getBitWidth() == BitWidth &&
821          "Value *V, DemandedMask, KnownZero and KnownOne "
822          "must have same BitWidth");
823   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
824     // We know all of the bits for a constant!
825     KnownOne = CI->getValue() & DemandedMask;
826     KnownZero = ~KnownOne & DemandedMask;
827     return 0;
828   }
829   if (isa<ConstantPointerNull>(V)) {
830     // We know all of the bits for a constant!
831     KnownOne.clear();
832     KnownZero = DemandedMask;
833     return 0;
834   }
835
836   KnownZero.clear();
837   KnownOne.clear();
838   if (DemandedMask == 0) {   // Not demanding any bits from V.
839     if (isa<UndefValue>(V))
840       return 0;
841     return Context->getUndef(VTy);
842   }
843   
844   if (Depth == 6)        // Limit search depth.
845     return 0;
846   
847   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
848   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
849
850   Instruction *I = dyn_cast<Instruction>(V);
851   if (!I) {
852     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
853     return 0;        // Only analyze instructions.
854   }
855
856   // If there are multiple uses of this value and we aren't at the root, then
857   // we can't do any simplifications of the operands, because DemandedMask
858   // only reflects the bits demanded by *one* of the users.
859   if (Depth != 0 && !I->hasOneUse()) {
860     // Despite the fact that we can't simplify this instruction in all User's
861     // context, we can at least compute the knownzero/knownone bits, and we can
862     // do simplifications that apply to *just* the one user if we know that
863     // this instruction has a simpler value in that context.
864     if (I->getOpcode() == Instruction::And) {
865       // If either the LHS or the RHS are Zero, the result is zero.
866       ComputeMaskedBits(I->getOperand(1), DemandedMask,
867                         RHSKnownZero, RHSKnownOne, Depth+1);
868       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
869                         LHSKnownZero, LHSKnownOne, Depth+1);
870       
871       // If all of the demanded bits are known 1 on one side, return the other.
872       // These bits cannot contribute to the result of the 'and' in this
873       // context.
874       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
875           (DemandedMask & ~LHSKnownZero))
876         return I->getOperand(0);
877       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
878           (DemandedMask & ~RHSKnownZero))
879         return I->getOperand(1);
880       
881       // If all of the demanded bits in the inputs are known zeros, return zero.
882       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
883         return Context->getNullValue(VTy);
884       
885     } else if (I->getOpcode() == Instruction::Or) {
886       // We can simplify (X|Y) -> X or Y in the user's context if we know that
887       // only bits from X or Y are demanded.
888       
889       // If either the LHS or the RHS are One, the result is One.
890       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
891                         RHSKnownZero, RHSKnownOne, Depth+1);
892       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
893                         LHSKnownZero, LHSKnownOne, Depth+1);
894       
895       // If all of the demanded bits are known zero on one side, return the
896       // other.  These bits cannot contribute to the result of the 'or' in this
897       // context.
898       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
899           (DemandedMask & ~LHSKnownOne))
900         return I->getOperand(0);
901       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
902           (DemandedMask & ~RHSKnownOne))
903         return I->getOperand(1);
904       
905       // If all of the potentially set bits on one side are known to be set on
906       // the other side, just use the 'other' side.
907       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
908           (DemandedMask & (~RHSKnownZero)))
909         return I->getOperand(0);
910       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
911           (DemandedMask & (~LHSKnownZero)))
912         return I->getOperand(1);
913     }
914     
915     // Compute the KnownZero/KnownOne bits to simplify things downstream.
916     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
917     return 0;
918   }
919   
920   // If this is the root being simplified, allow it to have multiple uses,
921   // just set the DemandedMask to all bits so that we can try to simplify the
922   // operands.  This allows visitTruncInst (for example) to simplify the
923   // operand of a trunc without duplicating all the logic below.
924   if (Depth == 0 && !V->hasOneUse())
925     DemandedMask = APInt::getAllOnesValue(BitWidth);
926   
927   switch (I->getOpcode()) {
928   default:
929     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
930     break;
931   case Instruction::And:
932     // If either the LHS or the RHS are Zero, the result is zero.
933     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
934                              RHSKnownZero, RHSKnownOne, Depth+1) ||
935         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
936                              LHSKnownZero, LHSKnownOne, Depth+1))
937       return I;
938     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
939     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
940
941     // If all of the demanded bits are known 1 on one side, return the other.
942     // These bits cannot contribute to the result of the 'and'.
943     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
944         (DemandedMask & ~LHSKnownZero))
945       return I->getOperand(0);
946     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
947         (DemandedMask & ~RHSKnownZero))
948       return I->getOperand(1);
949     
950     // If all of the demanded bits in the inputs are known zeros, return zero.
951     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
952       return Context->getNullValue(VTy);
953       
954     // If the RHS is a constant, see if we can simplify it.
955     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
956       return I;
957       
958     // Output known-1 bits are only known if set in both the LHS & RHS.
959     RHSKnownOne &= LHSKnownOne;
960     // Output known-0 are known to be clear if zero in either the LHS | RHS.
961     RHSKnownZero |= LHSKnownZero;
962     break;
963   case Instruction::Or:
964     // If either the LHS or the RHS are One, the result is One.
965     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
966                              RHSKnownZero, RHSKnownOne, Depth+1) ||
967         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
968                              LHSKnownZero, LHSKnownOne, Depth+1))
969       return I;
970     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
971     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
972     
973     // If all of the demanded bits are known zero on one side, return the other.
974     // These bits cannot contribute to the result of the 'or'.
975     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
976         (DemandedMask & ~LHSKnownOne))
977       return I->getOperand(0);
978     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
979         (DemandedMask & ~RHSKnownOne))
980       return I->getOperand(1);
981
982     // If all of the potentially set bits on one side are known to be set on
983     // the other side, just use the 'other' side.
984     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
985         (DemandedMask & (~RHSKnownZero)))
986       return I->getOperand(0);
987     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
988         (DemandedMask & (~LHSKnownZero)))
989       return I->getOperand(1);
990         
991     // If the RHS is a constant, see if we can simplify it.
992     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
993       return I;
994           
995     // Output known-0 bits are only known if clear in both the LHS & RHS.
996     RHSKnownZero &= LHSKnownZero;
997     // Output known-1 are known to be set if set in either the LHS | RHS.
998     RHSKnownOne |= LHSKnownOne;
999     break;
1000   case Instruction::Xor: {
1001     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1002                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1003         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1004                              LHSKnownZero, LHSKnownOne, Depth+1))
1005       return I;
1006     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1007     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1008     
1009     // If all of the demanded bits are known zero on one side, return the other.
1010     // These bits cannot contribute to the result of the 'xor'.
1011     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1012       return I->getOperand(0);
1013     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1014       return I->getOperand(1);
1015     
1016     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1017     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1018                          (RHSKnownOne & LHSKnownOne);
1019     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1020     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1021                         (RHSKnownOne & LHSKnownZero);
1022     
1023     // If all of the demanded bits are known to be zero on one side or the
1024     // other, turn this into an *inclusive* or.
1025     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1026     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1027       Instruction *Or =
1028         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1029                                  I->getName());
1030       return InsertNewInstBefore(Or, *I);
1031     }
1032     
1033     // If all of the demanded bits on one side are known, and all of the set
1034     // bits on that side are also known to be set on the other side, turn this
1035     // into an AND, as we know the bits will be cleared.
1036     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1037     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1038       // all known
1039       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1040         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1041         Instruction *And = 
1042           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1043         return InsertNewInstBefore(And, *I);
1044       }
1045     }
1046     
1047     // If the RHS is a constant, see if we can simplify it.
1048     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1049     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1050       return I;
1051     
1052     RHSKnownZero = KnownZeroOut;
1053     RHSKnownOne  = KnownOneOut;
1054     break;
1055   }
1056   case Instruction::Select:
1057     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1058                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1059         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1060                              LHSKnownZero, LHSKnownOne, Depth+1))
1061       return I;
1062     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1063     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1064     
1065     // If the operands are constants, see if we can simplify them.
1066     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1067         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1068       return I;
1069     
1070     // Only known if known in both the LHS and RHS.
1071     RHSKnownOne &= LHSKnownOne;
1072     RHSKnownZero &= LHSKnownZero;
1073     break;
1074   case Instruction::Trunc: {
1075     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1076     DemandedMask.zext(truncBf);
1077     RHSKnownZero.zext(truncBf);
1078     RHSKnownOne.zext(truncBf);
1079     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1080                              RHSKnownZero, RHSKnownOne, Depth+1))
1081       return I;
1082     DemandedMask.trunc(BitWidth);
1083     RHSKnownZero.trunc(BitWidth);
1084     RHSKnownOne.trunc(BitWidth);
1085     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1086     break;
1087   }
1088   case Instruction::BitCast:
1089     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1090       return false;  // vector->int or fp->int?
1091
1092     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1093       if (const VectorType *SrcVTy =
1094             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1095         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1096           // Don't touch a bitcast between vectors of different element counts.
1097           return false;
1098       } else
1099         // Don't touch a scalar-to-vector bitcast.
1100         return false;
1101     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1102       // Don't touch a vector-to-scalar bitcast.
1103       return false;
1104
1105     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1109     break;
1110   case Instruction::ZExt: {
1111     // Compute the bits in the result that are not present in the input.
1112     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1113     
1114     DemandedMask.trunc(SrcBitWidth);
1115     RHSKnownZero.trunc(SrcBitWidth);
1116     RHSKnownOne.trunc(SrcBitWidth);
1117     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1118                              RHSKnownZero, RHSKnownOne, Depth+1))
1119       return I;
1120     DemandedMask.zext(BitWidth);
1121     RHSKnownZero.zext(BitWidth);
1122     RHSKnownOne.zext(BitWidth);
1123     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1124     // The top bits are known to be zero.
1125     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1126     break;
1127   }
1128   case Instruction::SExt: {
1129     // Compute the bits in the result that are not present in the input.
1130     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1131     
1132     APInt InputDemandedBits = DemandedMask & 
1133                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1134
1135     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1136     // If any of the sign extended bits are demanded, we know that the sign
1137     // bit is demanded.
1138     if ((NewBits & DemandedMask) != 0)
1139       InputDemandedBits.set(SrcBitWidth-1);
1140       
1141     InputDemandedBits.trunc(SrcBitWidth);
1142     RHSKnownZero.trunc(SrcBitWidth);
1143     RHSKnownOne.trunc(SrcBitWidth);
1144     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1145                              RHSKnownZero, RHSKnownOne, Depth+1))
1146       return I;
1147     InputDemandedBits.zext(BitWidth);
1148     RHSKnownZero.zext(BitWidth);
1149     RHSKnownOne.zext(BitWidth);
1150     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1151       
1152     // If the sign bit of the input is known set or clear, then we know the
1153     // top bits of the result.
1154
1155     // If the input sign bit is known zero, or if the NewBits are not demanded
1156     // convert this into a zero extension.
1157     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1158       // Convert to ZExt cast
1159       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1160       return InsertNewInstBefore(NewCast, *I);
1161     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1162       RHSKnownOne |= NewBits;
1163     }
1164     break;
1165   }
1166   case Instruction::Add: {
1167     // Figure out what the input bits are.  If the top bits of the and result
1168     // are not demanded, then the add doesn't demand them from its input
1169     // either.
1170     unsigned NLZ = DemandedMask.countLeadingZeros();
1171       
1172     // If there is a constant on the RHS, there are a variety of xformations
1173     // we can do.
1174     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1175       // If null, this should be simplified elsewhere.  Some of the xforms here
1176       // won't work if the RHS is zero.
1177       if (RHS->isZero())
1178         break;
1179       
1180       // If the top bit of the output is demanded, demand everything from the
1181       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1182       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1183
1184       // Find information about known zero/one bits in the input.
1185       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1186                                LHSKnownZero, LHSKnownOne, Depth+1))
1187         return I;
1188
1189       // If the RHS of the add has bits set that can't affect the input, reduce
1190       // the constant.
1191       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1192         return I;
1193       
1194       // Avoid excess work.
1195       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1196         break;
1197       
1198       // Turn it into OR if input bits are zero.
1199       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1200         Instruction *Or =
1201           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1202                                    I->getName());
1203         return InsertNewInstBefore(Or, *I);
1204       }
1205       
1206       // We can say something about the output known-zero and known-one bits,
1207       // depending on potential carries from the input constant and the
1208       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1209       // bits set and the RHS constant is 0x01001, then we know we have a known
1210       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1211       
1212       // To compute this, we first compute the potential carry bits.  These are
1213       // the bits which may be modified.  I'm not aware of a better way to do
1214       // this scan.
1215       const APInt &RHSVal = RHS->getValue();
1216       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1217       
1218       // Now that we know which bits have carries, compute the known-1/0 sets.
1219       
1220       // Bits are known one if they are known zero in one operand and one in the
1221       // other, and there is no input carry.
1222       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1223                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1224       
1225       // Bits are known zero if they are known zero in both operands and there
1226       // is no input carry.
1227       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1228     } else {
1229       // If the high-bits of this ADD are not demanded, then it does not demand
1230       // the high bits of its LHS or RHS.
1231       if (DemandedMask[BitWidth-1] == 0) {
1232         // Right fill the mask of bits for this ADD to demand the most
1233         // significant bit and all those below it.
1234         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1235         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1236                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1237             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1238                                  LHSKnownZero, LHSKnownOne, Depth+1))
1239           return I;
1240       }
1241     }
1242     break;
1243   }
1244   case Instruction::Sub:
1245     // If the high-bits of this SUB are not demanded, then it does not demand
1246     // the high bits of its LHS or RHS.
1247     if (DemandedMask[BitWidth-1] == 0) {
1248       // Right fill the mask of bits for this SUB to demand the most
1249       // significant bit and all those below it.
1250       uint32_t NLZ = DemandedMask.countLeadingZeros();
1251       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1252       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1253                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1254           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1255                                LHSKnownZero, LHSKnownOne, Depth+1))
1256         return I;
1257     }
1258     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1259     // the known zeros and ones.
1260     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1261     break;
1262   case Instruction::Shl:
1263     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1264       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1265       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1266       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1267                                RHSKnownZero, RHSKnownOne, Depth+1))
1268         return I;
1269       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1270       RHSKnownZero <<= ShiftAmt;
1271       RHSKnownOne  <<= ShiftAmt;
1272       // low bits known zero.
1273       if (ShiftAmt)
1274         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1275     }
1276     break;
1277   case Instruction::LShr:
1278     // For a logical shift right
1279     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1280       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1281       
1282       // Unsigned shift right.
1283       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1284       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1285                                RHSKnownZero, RHSKnownOne, Depth+1))
1286         return I;
1287       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1288       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1289       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1290       if (ShiftAmt) {
1291         // Compute the new bits that are at the top now.
1292         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1293         RHSKnownZero |= HighBits;  // high bits known zero.
1294       }
1295     }
1296     break;
1297   case Instruction::AShr:
1298     // If this is an arithmetic shift right and only the low-bit is set, we can
1299     // always convert this into a logical shr, even if the shift amount is
1300     // variable.  The low bit of the shift cannot be an input sign bit unless
1301     // the shift amount is >= the size of the datatype, which is undefined.
1302     if (DemandedMask == 1) {
1303       // Perform the logical shift right.
1304       Instruction *NewVal = BinaryOperator::CreateLShr(
1305                         I->getOperand(0), I->getOperand(1), I->getName());
1306       return InsertNewInstBefore(NewVal, *I);
1307     }    
1308
1309     // If the sign bit is the only bit demanded by this ashr, then there is no
1310     // need to do it, the shift doesn't change the high bit.
1311     if (DemandedMask.isSignBit())
1312       return I->getOperand(0);
1313     
1314     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1316       
1317       // Signed shift right.
1318       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1319       // If any of the "high bits" are demanded, we should set the sign bit as
1320       // demanded.
1321       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1322         DemandedMaskIn.set(BitWidth-1);
1323       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1324                                RHSKnownZero, RHSKnownOne, Depth+1))
1325         return I;
1326       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1327       // Compute the new bits that are at the top now.
1328       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1329       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1330       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1331         
1332       // Handle the sign bits.
1333       APInt SignBit(APInt::getSignBit(BitWidth));
1334       // Adjust to where it is now in the mask.
1335       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1336         
1337       // If the input sign bit is known to be zero, or if none of the top bits
1338       // are demanded, turn this into an unsigned shift right.
1339       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1340           (HighBits & ~DemandedMask) == HighBits) {
1341         // Perform the logical shift right.
1342         Instruction *NewVal = BinaryOperator::CreateLShr(
1343                           I->getOperand(0), SA, I->getName());
1344         return InsertNewInstBefore(NewVal, *I);
1345       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1346         RHSKnownOne |= HighBits;
1347       }
1348     }
1349     break;
1350   case Instruction::SRem:
1351     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1352       APInt RA = Rem->getValue().abs();
1353       if (RA.isPowerOf2()) {
1354         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1355           return I->getOperand(0);
1356
1357         APInt LowBits = RA - 1;
1358         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1359         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1360                                  LHSKnownZero, LHSKnownOne, Depth+1))
1361           return I;
1362
1363         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1364           LHSKnownZero |= ~LowBits;
1365
1366         KnownZero |= LHSKnownZero & DemandedMask;
1367
1368         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1369       }
1370     }
1371     break;
1372   case Instruction::URem: {
1373     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1374     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1375     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1376                              KnownZero2, KnownOne2, Depth+1) ||
1377         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1378                              KnownZero2, KnownOne2, Depth+1))
1379       return I;
1380
1381     unsigned Leaders = KnownZero2.countLeadingOnes();
1382     Leaders = std::max(Leaders,
1383                        KnownZero2.countLeadingOnes());
1384     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1385     break;
1386   }
1387   case Instruction::Call:
1388     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1389       switch (II->getIntrinsicID()) {
1390       default: break;
1391       case Intrinsic::bswap: {
1392         // If the only bits demanded come from one byte of the bswap result,
1393         // just shift the input byte into position to eliminate the bswap.
1394         unsigned NLZ = DemandedMask.countLeadingZeros();
1395         unsigned NTZ = DemandedMask.countTrailingZeros();
1396           
1397         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1398         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1399         // have 14 leading zeros, round to 8.
1400         NLZ &= ~7;
1401         NTZ &= ~7;
1402         // If we need exactly one byte, we can do this transformation.
1403         if (BitWidth-NLZ-NTZ == 8) {
1404           unsigned ResultBit = NTZ;
1405           unsigned InputBit = BitWidth-NTZ-8;
1406           
1407           // Replace this with either a left or right shift to get the byte into
1408           // the right place.
1409           Instruction *NewVal;
1410           if (InputBit > ResultBit)
1411             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1412                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1413           else
1414             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1415                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1416           NewVal->takeName(I);
1417           return InsertNewInstBefore(NewVal, *I);
1418         }
1419           
1420         // TODO: Could compute known zero/one bits based on the input.
1421         break;
1422       }
1423       }
1424     }
1425     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1426     break;
1427   }
1428   
1429   // If the client is only demanding bits that we know, return the known
1430   // constant.
1431   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1432     Constant *C = Context->getConstantInt(RHSKnownOne);
1433     if (isa<PointerType>(V->getType()))
1434       C = Context->getConstantExprIntToPtr(C, V->getType());
1435     return C;
1436   }
1437   return false;
1438 }
1439
1440
1441 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1442 /// any number of elements. DemandedElts contains the set of elements that are
1443 /// actually used by the caller.  This method analyzes which elements of the
1444 /// operand are undef and returns that information in UndefElts.
1445 ///
1446 /// If the information about demanded elements can be used to simplify the
1447 /// operation, the operation is simplified, then the resultant value is
1448 /// returned.  This returns null if no change was made.
1449 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1450                                                 APInt& UndefElts,
1451                                                 unsigned Depth) {
1452   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1453   APInt EltMask(APInt::getAllOnesValue(VWidth));
1454   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1455
1456   if (isa<UndefValue>(V)) {
1457     // If the entire vector is undefined, just return this info.
1458     UndefElts = EltMask;
1459     return 0;
1460   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1461     UndefElts = EltMask;
1462     return Context->getUndef(V->getType());
1463   }
1464
1465   UndefElts = 0;
1466   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1467     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1468     Constant *Undef = Context->getUndef(EltTy);
1469
1470     std::vector<Constant*> Elts;
1471     for (unsigned i = 0; i != VWidth; ++i)
1472       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1473         Elts.push_back(Undef);
1474         UndefElts.set(i);
1475       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1476         Elts.push_back(Undef);
1477         UndefElts.set(i);
1478       } else {                               // Otherwise, defined.
1479         Elts.push_back(CP->getOperand(i));
1480       }
1481
1482     // If we changed the constant, return it.
1483     Constant *NewCP = Context->getConstantVector(Elts);
1484     return NewCP != CP ? NewCP : 0;
1485   } else if (isa<ConstantAggregateZero>(V)) {
1486     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1487     // set to undef.
1488     
1489     // Check if this is identity. If so, return 0 since we are not simplifying
1490     // anything.
1491     if (DemandedElts == ((1ULL << VWidth) -1))
1492       return 0;
1493     
1494     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1495     Constant *Zero = Context->getNullValue(EltTy);
1496     Constant *Undef = Context->getUndef(EltTy);
1497     std::vector<Constant*> Elts;
1498     for (unsigned i = 0; i != VWidth; ++i) {
1499       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1500       Elts.push_back(Elt);
1501     }
1502     UndefElts = DemandedElts ^ EltMask;
1503     return Context->getConstantVector(Elts);
1504   }
1505   
1506   // Limit search depth.
1507   if (Depth == 10)
1508     return 0;
1509
1510   // If multiple users are using the root value, procede with
1511   // simplification conservatively assuming that all elements
1512   // are needed.
1513   if (!V->hasOneUse()) {
1514     // Quit if we find multiple users of a non-root value though.
1515     // They'll be handled when it's their turn to be visited by
1516     // the main instcombine process.
1517     if (Depth != 0)
1518       // TODO: Just compute the UndefElts information recursively.
1519       return 0;
1520
1521     // Conservatively assume that all elements are needed.
1522     DemandedElts = EltMask;
1523   }
1524   
1525   Instruction *I = dyn_cast<Instruction>(V);
1526   if (!I) return 0;        // Only analyze instructions.
1527   
1528   bool MadeChange = false;
1529   APInt UndefElts2(VWidth, 0);
1530   Value *TmpV;
1531   switch (I->getOpcode()) {
1532   default: break;
1533     
1534   case Instruction::InsertElement: {
1535     // If this is a variable index, we don't know which element it overwrites.
1536     // demand exactly the same input as we produce.
1537     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1538     if (Idx == 0) {
1539       // Note that we can't propagate undef elt info, because we don't know
1540       // which elt is getting updated.
1541       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1542                                         UndefElts2, Depth+1);
1543       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544       break;
1545     }
1546     
1547     // If this is inserting an element that isn't demanded, remove this
1548     // insertelement.
1549     unsigned IdxNo = Idx->getZExtValue();
1550     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1551       return AddSoonDeadInstToWorklist(*I, 0);
1552     
1553     // Otherwise, the element inserted overwrites whatever was there, so the
1554     // input demanded set is simpler than the output set.
1555     APInt DemandedElts2 = DemandedElts;
1556     DemandedElts2.clear(IdxNo);
1557     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1558                                       UndefElts, Depth+1);
1559     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1560
1561     // The inserted element is defined.
1562     UndefElts.clear(IdxNo);
1563     break;
1564   }
1565   case Instruction::ShuffleVector: {
1566     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1567     uint64_t LHSVWidth =
1568       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1569     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1570     for (unsigned i = 0; i < VWidth; i++) {
1571       if (DemandedElts[i]) {
1572         unsigned MaskVal = Shuffle->getMaskValue(i);
1573         if (MaskVal != -1u) {
1574           assert(MaskVal < LHSVWidth * 2 &&
1575                  "shufflevector mask index out of range!");
1576           if (MaskVal < LHSVWidth)
1577             LeftDemanded.set(MaskVal);
1578           else
1579             RightDemanded.set(MaskVal - LHSVWidth);
1580         }
1581       }
1582     }
1583
1584     APInt UndefElts4(LHSVWidth, 0);
1585     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1586                                       UndefElts4, Depth+1);
1587     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1588
1589     APInt UndefElts3(LHSVWidth, 0);
1590     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1591                                       UndefElts3, Depth+1);
1592     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1593
1594     bool NewUndefElts = false;
1595     for (unsigned i = 0; i < VWidth; i++) {
1596       unsigned MaskVal = Shuffle->getMaskValue(i);
1597       if (MaskVal == -1u) {
1598         UndefElts.set(i);
1599       } else if (MaskVal < LHSVWidth) {
1600         if (UndefElts4[MaskVal]) {
1601           NewUndefElts = true;
1602           UndefElts.set(i);
1603         }
1604       } else {
1605         if (UndefElts3[MaskVal - LHSVWidth]) {
1606           NewUndefElts = true;
1607           UndefElts.set(i);
1608         }
1609       }
1610     }
1611
1612     if (NewUndefElts) {
1613       // Add additional discovered undefs.
1614       std::vector<Constant*> Elts;
1615       for (unsigned i = 0; i < VWidth; ++i) {
1616         if (UndefElts[i])
1617           Elts.push_back(Context->getUndef(Type::Int32Ty));
1618         else
1619           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1620                                           Shuffle->getMaskValue(i)));
1621       }
1622       I->setOperand(2, Context->getConstantVector(Elts));
1623       MadeChange = true;
1624     }
1625     break;
1626   }
1627   case Instruction::BitCast: {
1628     // Vector->vector casts only.
1629     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1630     if (!VTy) break;
1631     unsigned InVWidth = VTy->getNumElements();
1632     APInt InputDemandedElts(InVWidth, 0);
1633     unsigned Ratio;
1634
1635     if (VWidth == InVWidth) {
1636       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1637       // elements as are demanded of us.
1638       Ratio = 1;
1639       InputDemandedElts = DemandedElts;
1640     } else if (VWidth > InVWidth) {
1641       // Untested so far.
1642       break;
1643       
1644       // If there are more elements in the result than there are in the source,
1645       // then an input element is live if any of the corresponding output
1646       // elements are live.
1647       Ratio = VWidth/InVWidth;
1648       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1649         if (DemandedElts[OutIdx])
1650           InputDemandedElts.set(OutIdx/Ratio);
1651       }
1652     } else {
1653       // Untested so far.
1654       break;
1655       
1656       // If there are more elements in the source than there are in the result,
1657       // then an input element is live if the corresponding output element is
1658       // live.
1659       Ratio = InVWidth/VWidth;
1660       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1661         if (DemandedElts[InIdx/Ratio])
1662           InputDemandedElts.set(InIdx);
1663     }
1664     
1665     // div/rem demand all inputs, because they don't want divide by zero.
1666     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1667                                       UndefElts2, Depth+1);
1668     if (TmpV) {
1669       I->setOperand(0, TmpV);
1670       MadeChange = true;
1671     }
1672     
1673     UndefElts = UndefElts2;
1674     if (VWidth > InVWidth) {
1675       llvm_unreachable("Unimp");
1676       // If there are more elements in the result than there are in the source,
1677       // then an output element is undef if the corresponding input element is
1678       // undef.
1679       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1680         if (UndefElts2[OutIdx/Ratio])
1681           UndefElts.set(OutIdx);
1682     } else if (VWidth < InVWidth) {
1683       llvm_unreachable("Unimp");
1684       // If there are more elements in the source than there are in the result,
1685       // then a result element is undef if all of the corresponding input
1686       // elements are undef.
1687       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1688       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1689         if (!UndefElts2[InIdx])            // Not undef?
1690           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1691     }
1692     break;
1693   }
1694   case Instruction::And:
1695   case Instruction::Or:
1696   case Instruction::Xor:
1697   case Instruction::Add:
1698   case Instruction::Sub:
1699   case Instruction::Mul:
1700     // div/rem demand all inputs, because they don't want divide by zero.
1701     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1702                                       UndefElts, Depth+1);
1703     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1705                                       UndefElts2, Depth+1);
1706     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1707       
1708     // Output elements are undefined if both are undefined.  Consider things
1709     // like undef&0.  The result is known zero, not undef.
1710     UndefElts &= UndefElts2;
1711     break;
1712     
1713   case Instruction::Call: {
1714     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1715     if (!II) break;
1716     switch (II->getIntrinsicID()) {
1717     default: break;
1718       
1719     // Binary vector operations that work column-wise.  A dest element is a
1720     // function of the corresponding input elements from the two inputs.
1721     case Intrinsic::x86_sse_sub_ss:
1722     case Intrinsic::x86_sse_mul_ss:
1723     case Intrinsic::x86_sse_min_ss:
1724     case Intrinsic::x86_sse_max_ss:
1725     case Intrinsic::x86_sse2_sub_sd:
1726     case Intrinsic::x86_sse2_mul_sd:
1727     case Intrinsic::x86_sse2_min_sd:
1728     case Intrinsic::x86_sse2_max_sd:
1729       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1730                                         UndefElts, Depth+1);
1731       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1732       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1733                                         UndefElts2, Depth+1);
1734       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1735
1736       // If only the low elt is demanded and this is a scalarizable intrinsic,
1737       // scalarize it now.
1738       if (DemandedElts == 1) {
1739         switch (II->getIntrinsicID()) {
1740         default: break;
1741         case Intrinsic::x86_sse_sub_ss:
1742         case Intrinsic::x86_sse_mul_ss:
1743         case Intrinsic::x86_sse2_sub_sd:
1744         case Intrinsic::x86_sse2_mul_sd:
1745           // TODO: Lower MIN/MAX/ABS/etc
1746           Value *LHS = II->getOperand(1);
1747           Value *RHS = II->getOperand(2);
1748           // Extract the element as scalars.
1749           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 
1750             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1751           RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1752             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1753           
1754           switch (II->getIntrinsicID()) {
1755           default: llvm_unreachable("Case stmts out of sync!");
1756           case Intrinsic::x86_sse_sub_ss:
1757           case Intrinsic::x86_sse2_sub_sd:
1758             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1759                                                         II->getName()), *II);
1760             break;
1761           case Intrinsic::x86_sse_mul_ss:
1762           case Intrinsic::x86_sse2_mul_sd:
1763             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1764                                                          II->getName()), *II);
1765             break;
1766           }
1767           
1768           Instruction *New =
1769             InsertElementInst::Create(
1770               Context->getUndef(II->getType()), TmpV,
1771               Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1772           InsertNewInstBefore(New, *II);
1773           AddSoonDeadInstToWorklist(*II, 0);
1774           return New;
1775         }            
1776       }
1777         
1778       // Output elements are undefined if both are undefined.  Consider things
1779       // like undef&0.  The result is known zero, not undef.
1780       UndefElts &= UndefElts2;
1781       break;
1782     }
1783     break;
1784   }
1785   }
1786   return MadeChange ? I : 0;
1787 }
1788
1789
1790 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1791 /// function is designed to check a chain of associative operators for a
1792 /// potential to apply a certain optimization.  Since the optimization may be
1793 /// applicable if the expression was reassociated, this checks the chain, then
1794 /// reassociates the expression as necessary to expose the optimization
1795 /// opportunity.  This makes use of a special Functor, which must define
1796 /// 'shouldApply' and 'apply' methods.
1797 ///
1798 template<typename Functor>
1799 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1800                                    LLVMContext *Context) {
1801   unsigned Opcode = Root.getOpcode();
1802   Value *LHS = Root.getOperand(0);
1803
1804   // Quick check, see if the immediate LHS matches...
1805   if (F.shouldApply(LHS))
1806     return F.apply(Root);
1807
1808   // Otherwise, if the LHS is not of the same opcode as the root, return.
1809   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1810   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1811     // Should we apply this transform to the RHS?
1812     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1813
1814     // If not to the RHS, check to see if we should apply to the LHS...
1815     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1816       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1817       ShouldApply = true;
1818     }
1819
1820     // If the functor wants to apply the optimization to the RHS of LHSI,
1821     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1822     if (ShouldApply) {
1823       // Now all of the instructions are in the current basic block, go ahead
1824       // and perform the reassociation.
1825       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1826
1827       // First move the selected RHS to the LHS of the root...
1828       Root.setOperand(0, LHSI->getOperand(1));
1829
1830       // Make what used to be the LHS of the root be the user of the root...
1831       Value *ExtraOperand = TmpLHSI->getOperand(1);
1832       if (&Root == TmpLHSI) {
1833         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1834         return 0;
1835       }
1836       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1837       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1838       BasicBlock::iterator ARI = &Root; ++ARI;
1839       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1840       ARI = Root;
1841
1842       // Now propagate the ExtraOperand down the chain of instructions until we
1843       // get to LHSI.
1844       while (TmpLHSI != LHSI) {
1845         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1846         // Move the instruction to immediately before the chain we are
1847         // constructing to avoid breaking dominance properties.
1848         NextLHSI->moveBefore(ARI);
1849         ARI = NextLHSI;
1850
1851         Value *NextOp = NextLHSI->getOperand(1);
1852         NextLHSI->setOperand(1, ExtraOperand);
1853         TmpLHSI = NextLHSI;
1854         ExtraOperand = NextOp;
1855       }
1856
1857       // Now that the instructions are reassociated, have the functor perform
1858       // the transformation...
1859       return F.apply(Root);
1860     }
1861
1862     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1863   }
1864   return 0;
1865 }
1866
1867 namespace {
1868
1869 // AddRHS - Implements: X + X --> X << 1
1870 struct AddRHS {
1871   Value *RHS;
1872   LLVMContext *Context;
1873   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1874   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1875   Instruction *apply(BinaryOperator &Add) const {
1876     return BinaryOperator::CreateShl(Add.getOperand(0),
1877                                      Context->getConstantInt(Add.getType(), 1));
1878   }
1879 };
1880
1881 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1882 //                 iff C1&C2 == 0
1883 struct AddMaskingAnd {
1884   Constant *C2;
1885   LLVMContext *Context;
1886   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1887   bool shouldApply(Value *LHS) const {
1888     ConstantInt *C1;
1889     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1890            Context->getConstantExprAnd(C1, C2)->isNullValue();
1891   }
1892   Instruction *apply(BinaryOperator &Add) const {
1893     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1894   }
1895 };
1896
1897 }
1898
1899 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1900                                              InstCombiner *IC) {
1901   LLVMContext *Context = IC->getContext();
1902   
1903   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1904     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1905   }
1906
1907   // Figure out if the constant is the left or the right argument.
1908   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1909   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1910
1911   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1912     if (ConstIsRHS)
1913       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1914     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1915   }
1916
1917   Value *Op0 = SO, *Op1 = ConstOperand;
1918   if (!ConstIsRHS)
1919     std::swap(Op0, Op1);
1920   Instruction *New;
1921   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1922     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1923   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1924     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1925                           Op0, Op1, SO->getName()+".cmp");
1926   else {
1927     llvm_unreachable("Unknown binary instruction type!");
1928   }
1929   return IC->InsertNewInstBefore(New, I);
1930 }
1931
1932 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1933 // constant as the other operand, try to fold the binary operator into the
1934 // select arguments.  This also works for Cast instructions, which obviously do
1935 // not have a second operand.
1936 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1937                                      InstCombiner *IC) {
1938   // Don't modify shared select instructions
1939   if (!SI->hasOneUse()) return 0;
1940   Value *TV = SI->getOperand(1);
1941   Value *FV = SI->getOperand(2);
1942
1943   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1944     // Bool selects with constant operands can be folded to logical ops.
1945     if (SI->getType() == Type::Int1Ty) return 0;
1946
1947     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1948     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1949
1950     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1951                               SelectFalseVal);
1952   }
1953   return 0;
1954 }
1955
1956
1957 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1958 /// node as operand #0, see if we can fold the instruction into the PHI (which
1959 /// is only possible if all operands to the PHI are constants).
1960 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1961   PHINode *PN = cast<PHINode>(I.getOperand(0));
1962   unsigned NumPHIValues = PN->getNumIncomingValues();
1963   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1964
1965   // Check to see if all of the operands of the PHI are constants.  If there is
1966   // one non-constant value, remember the BB it is.  If there is more than one
1967   // or if *it* is a PHI, bail out.
1968   BasicBlock *NonConstBB = 0;
1969   for (unsigned i = 0; i != NumPHIValues; ++i)
1970     if (!isa<Constant>(PN->getIncomingValue(i))) {
1971       if (NonConstBB) return 0;  // More than one non-const value.
1972       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1973       NonConstBB = PN->getIncomingBlock(i);
1974       
1975       // If the incoming non-constant value is in I's block, we have an infinite
1976       // loop.
1977       if (NonConstBB == I.getParent())
1978         return 0;
1979     }
1980   
1981   // If there is exactly one non-constant value, we can insert a copy of the
1982   // operation in that block.  However, if this is a critical edge, we would be
1983   // inserting the computation one some other paths (e.g. inside a loop).  Only
1984   // do this if the pred block is unconditionally branching into the phi block.
1985   if (NonConstBB) {
1986     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1987     if (!BI || !BI->isUnconditional()) return 0;
1988   }
1989
1990   // Okay, we can do the transformation: create the new PHI node.
1991   PHINode *NewPN = PHINode::Create(I.getType(), "");
1992   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1993   InsertNewInstBefore(NewPN, *PN);
1994   NewPN->takeName(PN);
1995
1996   // Next, add all of the operands to the PHI.
1997   if (I.getNumOperands() == 2) {
1998     Constant *C = cast<Constant>(I.getOperand(1));
1999     for (unsigned i = 0; i != NumPHIValues; ++i) {
2000       Value *InV = 0;
2001       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2002         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2003           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2004         else
2005           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2006       } else {
2007         assert(PN->getIncomingBlock(i) == NonConstBB);
2008         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2009           InV = BinaryOperator::Create(BO->getOpcode(),
2010                                        PN->getIncomingValue(i), C, "phitmp",
2011                                        NonConstBB->getTerminator());
2012         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2013           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2014                                 CI->getPredicate(),
2015                                 PN->getIncomingValue(i), C, "phitmp",
2016                                 NonConstBB->getTerminator());
2017         else
2018           llvm_unreachable("Unknown binop!");
2019         
2020         AddToWorkList(cast<Instruction>(InV));
2021       }
2022       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2023     }
2024   } else { 
2025     CastInst *CI = cast<CastInst>(&I);
2026     const Type *RetTy = CI->getType();
2027     for (unsigned i = 0; i != NumPHIValues; ++i) {
2028       Value *InV;
2029       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2030         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2031       } else {
2032         assert(PN->getIncomingBlock(i) == NonConstBB);
2033         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2034                                I.getType(), "phitmp", 
2035                                NonConstBB->getTerminator());
2036         AddToWorkList(cast<Instruction>(InV));
2037       }
2038       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2039     }
2040   }
2041   return ReplaceInstUsesWith(I, NewPN);
2042 }
2043
2044
2045 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2046 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2047 /// This basically requires proving that the add in the original type would not
2048 /// overflow to change the sign bit or have a carry out.
2049 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2050   // There are different heuristics we can use for this.  Here are some simple
2051   // ones.
2052   
2053   // Add has the property that adding any two 2's complement numbers can only 
2054   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2055   // have at least two sign bits, we know that the addition of the two values will
2056   // sign extend fine.
2057   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2058     return true;
2059   
2060   
2061   // If one of the operands only has one non-zero bit, and if the other operand
2062   // has a known-zero bit in a more significant place than it (not including the
2063   // sign bit) the ripple may go up to and fill the zero, but won't change the
2064   // sign.  For example, (X & ~4) + 1.
2065   
2066   // TODO: Implement.
2067   
2068   return false;
2069 }
2070
2071
2072 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2073   bool Changed = SimplifyCommutative(I);
2074   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2075
2076   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2077     // X + undef -> undef
2078     if (isa<UndefValue>(RHS))
2079       return ReplaceInstUsesWith(I, RHS);
2080
2081     // X + 0 --> X
2082     if (RHSC->isNullValue())
2083       return ReplaceInstUsesWith(I, LHS);
2084
2085     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2086       // X + (signbit) --> X ^ signbit
2087       const APInt& Val = CI->getValue();
2088       uint32_t BitWidth = Val.getBitWidth();
2089       if (Val == APInt::getSignBit(BitWidth))
2090         return BinaryOperator::CreateXor(LHS, RHS);
2091       
2092       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2093       // (X & 254)+1 -> (X&254)|1
2094       if (SimplifyDemandedInstructionBits(I))
2095         return &I;
2096
2097       // zext(bool) + C -> bool ? C + 1 : C
2098       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2099         if (ZI->getSrcTy() == Type::Int1Ty)
2100           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2101     }
2102
2103     if (isa<PHINode>(LHS))
2104       if (Instruction *NV = FoldOpIntoPhi(I))
2105         return NV;
2106     
2107     ConstantInt *XorRHS = 0;
2108     Value *XorLHS = 0;
2109     if (isa<ConstantInt>(RHSC) &&
2110         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2111       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2112       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2113       
2114       uint32_t Size = TySizeBits / 2;
2115       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2116       APInt CFF80Val(-C0080Val);
2117       do {
2118         if (TySizeBits > Size) {
2119           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2120           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2121           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2122               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2123             // This is a sign extend if the top bits are known zero.
2124             if (!MaskedValueIsZero(XorLHS, 
2125                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2126               Size = 0;  // Not a sign ext, but can't be any others either.
2127             break;
2128           }
2129         }
2130         Size >>= 1;
2131         C0080Val = APIntOps::lshr(C0080Val, Size);
2132         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2133       } while (Size >= 1);
2134       
2135       // FIXME: This shouldn't be necessary. When the backends can handle types
2136       // with funny bit widths then this switch statement should be removed. It
2137       // is just here to get the size of the "middle" type back up to something
2138       // that the back ends can handle.
2139       const Type *MiddleType = 0;
2140       switch (Size) {
2141         default: break;
2142         case 32: MiddleType = Type::Int32Ty; break;
2143         case 16: MiddleType = Type::Int16Ty; break;
2144         case  8: MiddleType = Type::Int8Ty; break;
2145       }
2146       if (MiddleType) {
2147         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2148         InsertNewInstBefore(NewTrunc, I);
2149         return new SExtInst(NewTrunc, I.getType(), I.getName());
2150       }
2151     }
2152   }
2153
2154   if (I.getType() == Type::Int1Ty)
2155     return BinaryOperator::CreateXor(LHS, RHS);
2156
2157   // X + X --> X << 1
2158   if (I.getType()->isInteger()) {
2159     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2160       return Result;
2161
2162     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2163       if (RHSI->getOpcode() == Instruction::Sub)
2164         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2165           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2166     }
2167     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2168       if (LHSI->getOpcode() == Instruction::Sub)
2169         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2170           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2171     }
2172   }
2173
2174   // -A + B  -->  B - A
2175   // -A + -B  -->  -(A + B)
2176   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2177     if (LHS->getType()->isIntOrIntVector()) {
2178       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2179         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2180         InsertNewInstBefore(NewAdd, I);
2181         return BinaryOperator::CreateNeg(*Context, NewAdd);
2182       }
2183     }
2184     
2185     return BinaryOperator::CreateSub(RHS, LHSV);
2186   }
2187
2188   // A + -B  -->  A - B
2189   if (!isa<Constant>(RHS))
2190     if (Value *V = dyn_castNegVal(RHS, Context))
2191       return BinaryOperator::CreateSub(LHS, V);
2192
2193
2194   ConstantInt *C2;
2195   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2196     if (X == RHS)   // X*C + X --> X * (C+1)
2197       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2198
2199     // X*C1 + X*C2 --> X * (C1+C2)
2200     ConstantInt *C1;
2201     if (X == dyn_castFoldableMul(RHS, C1, Context))
2202       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2203   }
2204
2205   // X + X*C --> X * (C+1)
2206   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2207     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2208
2209   // X + ~X --> -1   since   ~X = -X-1
2210   if (dyn_castNotVal(LHS, Context) == RHS ||
2211       dyn_castNotVal(RHS, Context) == LHS)
2212     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2213   
2214
2215   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2216   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2217     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2218       return R;
2219   
2220   // A+B --> A|B iff A and B have no bits set in common.
2221   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2222     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2223     APInt LHSKnownOne(IT->getBitWidth(), 0);
2224     APInt LHSKnownZero(IT->getBitWidth(), 0);
2225     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2226     if (LHSKnownZero != 0) {
2227       APInt RHSKnownOne(IT->getBitWidth(), 0);
2228       APInt RHSKnownZero(IT->getBitWidth(), 0);
2229       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2230       
2231       // No bits in common -> bitwise or.
2232       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2233         return BinaryOperator::CreateOr(LHS, RHS);
2234     }
2235   }
2236
2237   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2238   if (I.getType()->isIntOrIntVector()) {
2239     Value *W, *X, *Y, *Z;
2240     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2241         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2242       if (W != Y) {
2243         if (W == Z) {
2244           std::swap(Y, Z);
2245         } else if (Y == X) {
2246           std::swap(W, X);
2247         } else if (X == Z) {
2248           std::swap(Y, Z);
2249           std::swap(W, X);
2250         }
2251       }
2252
2253       if (W == Y) {
2254         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2255                                                             LHS->getName()), I);
2256         return BinaryOperator::CreateMul(W, NewAdd);
2257       }
2258     }
2259   }
2260
2261   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2262     Value *X = 0;
2263     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2264       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2265
2266     // (X & FF00) + xx00  -> (X+xx00) & FF00
2267     if (LHS->hasOneUse() &&
2268         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2269       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2270       if (Anded == CRHS) {
2271         // See if all bits from the first bit set in the Add RHS up are included
2272         // in the mask.  First, get the rightmost bit.
2273         const APInt& AddRHSV = CRHS->getValue();
2274
2275         // Form a mask of all bits from the lowest bit added through the top.
2276         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2277
2278         // See if the and mask includes all of these bits.
2279         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2280
2281         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2282           // Okay, the xform is safe.  Insert the new add pronto.
2283           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2284                                                             LHS->getName()), I);
2285           return BinaryOperator::CreateAnd(NewAdd, C2);
2286         }
2287       }
2288     }
2289
2290     // Try to fold constant add into select arguments.
2291     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2292       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2293         return R;
2294   }
2295
2296   // add (cast *A to intptrtype) B -> 
2297   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2298   {
2299     CastInst *CI = dyn_cast<CastInst>(LHS);
2300     Value *Other = RHS;
2301     if (!CI) {
2302       CI = dyn_cast<CastInst>(RHS);
2303       Other = LHS;
2304     }
2305     if (CI && CI->getType()->isSized() && 
2306         (CI->getType()->getScalarSizeInBits() ==
2307          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2308         && isa<PointerType>(CI->getOperand(0)->getType())) {
2309       unsigned AS =
2310         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2311       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2312                                   Context->getPointerType(Type::Int8Ty, AS), I);
2313       GetElementPtrInst *GEP = GetElementPtrInst::Create(I2, Other, "ctg2");
2314       // A GEP formed from an arbitrary add may overflow.
2315       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
2316       I2 = InsertNewInstBefore(GEP, I);
2317       return new PtrToIntInst(I2, CI->getType());
2318     }
2319   }
2320   
2321   // add (select X 0 (sub n A)) A  -->  select X A n
2322   {
2323     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2324     Value *A = RHS;
2325     if (!SI) {
2326       SI = dyn_cast<SelectInst>(RHS);
2327       A = LHS;
2328     }
2329     if (SI && SI->hasOneUse()) {
2330       Value *TV = SI->getTrueValue();
2331       Value *FV = SI->getFalseValue();
2332       Value *N;
2333
2334       // Can we fold the add into the argument of the select?
2335       // We check both true and false select arguments for a matching subtract.
2336       if (match(FV, m_Zero(), *Context) &&
2337           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2338         // Fold the add into the true select value.
2339         return SelectInst::Create(SI->getCondition(), N, A);
2340       if (match(TV, m_Zero(), *Context) &&
2341           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2342         // Fold the add into the false select value.
2343         return SelectInst::Create(SI->getCondition(), A, N);
2344     }
2345   }
2346
2347   // Check for (add (sext x), y), see if we can merge this into an
2348   // integer add followed by a sext.
2349   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2350     // (add (sext x), cst) --> (sext (add x, cst'))
2351     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2352       Constant *CI = 
2353         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2354       if (LHSConv->hasOneUse() &&
2355           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2356           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2357         // Insert the new, smaller add.
2358         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2359                                                         CI, "addconv");
2360         InsertNewInstBefore(NewAdd, I);
2361         return new SExtInst(NewAdd, I.getType());
2362       }
2363     }
2364     
2365     // (add (sext x), (sext y)) --> (sext (add int x, y))
2366     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2367       // Only do this if x/y have the same type, if at last one of them has a
2368       // single use (so we don't increase the number of sexts), and if the
2369       // integer add will not overflow.
2370       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2371           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2372           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2373                                    RHSConv->getOperand(0))) {
2374         // Insert the new integer add.
2375         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2376                                                         RHSConv->getOperand(0),
2377                                                         "addconv");
2378         InsertNewInstBefore(NewAdd, I);
2379         return new SExtInst(NewAdd, I.getType());
2380       }
2381     }
2382   }
2383
2384   return Changed ? &I : 0;
2385 }
2386
2387 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2388   bool Changed = SimplifyCommutative(I);
2389   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2390
2391   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2392     // X + 0 --> X
2393     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2394       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2395                               (I.getType())->getValueAPF()))
2396         return ReplaceInstUsesWith(I, LHS);
2397     }
2398
2399     if (isa<PHINode>(LHS))
2400       if (Instruction *NV = FoldOpIntoPhi(I))
2401         return NV;
2402   }
2403
2404   // -A + B  -->  B - A
2405   // -A + -B  -->  -(A + B)
2406   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2407     return BinaryOperator::CreateFSub(RHS, LHSV);
2408
2409   // A + -B  -->  A - B
2410   if (!isa<Constant>(RHS))
2411     if (Value *V = dyn_castFNegVal(RHS, Context))
2412       return BinaryOperator::CreateFSub(LHS, V);
2413
2414   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2415   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2416     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2417       return ReplaceInstUsesWith(I, LHS);
2418
2419   // Check for (add double (sitofp x), y), see if we can merge this into an
2420   // integer add followed by a promotion.
2421   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2422     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2423     // ... if the constant fits in the integer value.  This is useful for things
2424     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2425     // requires a constant pool load, and generally allows the add to be better
2426     // instcombined.
2427     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2428       Constant *CI = 
2429       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2430       if (LHSConv->hasOneUse() &&
2431           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2432           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2433         // Insert the new integer add.
2434         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2435                                                         CI, "addconv");
2436         InsertNewInstBefore(NewAdd, I);
2437         return new SIToFPInst(NewAdd, I.getType());
2438       }
2439     }
2440     
2441     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2442     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2443       // Only do this if x/y have the same type, if at last one of them has a
2444       // single use (so we don't increase the number of int->fp conversions),
2445       // and if the integer add will not overflow.
2446       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2447           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2448           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2449                                    RHSConv->getOperand(0))) {
2450         // Insert the new integer add.
2451         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2452                                                         RHSConv->getOperand(0),
2453                                                         "addconv");
2454         InsertNewInstBefore(NewAdd, I);
2455         return new SIToFPInst(NewAdd, I.getType());
2456       }
2457     }
2458   }
2459   
2460   return Changed ? &I : 0;
2461 }
2462
2463 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2464   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2465
2466   if (Op0 == Op1)                        // sub X, X  -> 0
2467     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2468
2469   // If this is a 'B = x-(-A)', change to B = x+A...
2470   if (Value *V = dyn_castNegVal(Op1, Context))
2471     return BinaryOperator::CreateAdd(Op0, V);
2472
2473   if (isa<UndefValue>(Op0))
2474     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2475   if (isa<UndefValue>(Op1))
2476     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2477
2478   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2479     // Replace (-1 - A) with (~A)...
2480     if (C->isAllOnesValue())
2481       return BinaryOperator::CreateNot(*Context, Op1);
2482
2483     // C - ~X == X + (1+C)
2484     Value *X = 0;
2485     if (match(Op1, m_Not(m_Value(X)), *Context))
2486       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2487
2488     // -(X >>u 31) -> (X >>s 31)
2489     // -(X >>s 31) -> (X >>u 31)
2490     if (C->isZero()) {
2491       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2492         if (SI->getOpcode() == Instruction::LShr) {
2493           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2494             // Check to see if we are shifting out everything but the sign bit.
2495             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2496                 SI->getType()->getPrimitiveSizeInBits()-1) {
2497               // Ok, the transformation is safe.  Insert AShr.
2498               return BinaryOperator::Create(Instruction::AShr, 
2499                                           SI->getOperand(0), CU, SI->getName());
2500             }
2501           }
2502         }
2503         else if (SI->getOpcode() == Instruction::AShr) {
2504           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2505             // Check to see if we are shifting out everything but the sign bit.
2506             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2507                 SI->getType()->getPrimitiveSizeInBits()-1) {
2508               // Ok, the transformation is safe.  Insert LShr. 
2509               return BinaryOperator::CreateLShr(
2510                                           SI->getOperand(0), CU, SI->getName());
2511             }
2512           }
2513         }
2514       }
2515     }
2516
2517     // Try to fold constant sub into select arguments.
2518     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2519       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2520         return R;
2521
2522     // C - zext(bool) -> bool ? C - 1 : C
2523     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2524       if (ZI->getSrcTy() == Type::Int1Ty)
2525         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2526   }
2527
2528   if (I.getType() == Type::Int1Ty)
2529     return BinaryOperator::CreateXor(Op0, Op1);
2530
2531   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2532     if (Op1I->getOpcode() == Instruction::Add) {
2533       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2534         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2535                                          I.getName());
2536       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2537         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2538                                          I.getName());
2539       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2540         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2541           // C1-(X+C2) --> (C1-C2)-X
2542           return BinaryOperator::CreateSub(
2543             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2544       }
2545     }
2546
2547     if (Op1I->hasOneUse()) {
2548       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2549       // is not used by anyone else...
2550       //
2551       if (Op1I->getOpcode() == Instruction::Sub) {
2552         // Swap the two operands of the subexpr...
2553         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2554         Op1I->setOperand(0, IIOp1);
2555         Op1I->setOperand(1, IIOp0);
2556
2557         // Create the new top level add instruction...
2558         return BinaryOperator::CreateAdd(Op0, Op1);
2559       }
2560
2561       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2562       //
2563       if (Op1I->getOpcode() == Instruction::And &&
2564           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2565         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2566
2567         Value *NewNot =
2568           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2569                                                         OtherOp, "B.not"), I);
2570         return BinaryOperator::CreateAnd(Op0, NewNot);
2571       }
2572
2573       // 0 - (X sdiv C)  -> (X sdiv -C)
2574       if (Op1I->getOpcode() == Instruction::SDiv)
2575         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2576           if (CSI->isZero())
2577             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2578               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2579                                           Context->getConstantExprNeg(DivRHS));
2580
2581       // X - X*C --> X * (1-C)
2582       ConstantInt *C2 = 0;
2583       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2584         Constant *CP1 = 
2585           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2586                                              C2);
2587         return BinaryOperator::CreateMul(Op0, CP1);
2588       }
2589     }
2590   }
2591
2592   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2593     if (Op0I->getOpcode() == Instruction::Add) {
2594       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2595         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2596       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2597         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2598     } else if (Op0I->getOpcode() == Instruction::Sub) {
2599       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2600         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2601                                          I.getName());
2602     }
2603   }
2604
2605   ConstantInt *C1;
2606   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2607     if (X == Op1)  // X*C - X --> X * (C-1)
2608       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2609
2610     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2611     if (X == dyn_castFoldableMul(Op1, C2, Context))
2612       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2613   }
2614   return 0;
2615 }
2616
2617 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2618   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2619
2620   // If this is a 'B = x-(-A)', change to B = x+A...
2621   if (Value *V = dyn_castFNegVal(Op1, Context))
2622     return BinaryOperator::CreateFAdd(Op0, V);
2623
2624   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2625     if (Op1I->getOpcode() == Instruction::FAdd) {
2626       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2627         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2628                                           I.getName());
2629       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2630         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2631                                           I.getName());
2632     }
2633   }
2634
2635   return 0;
2636 }
2637
2638 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2639 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2640 /// TrueIfSigned if the result of the comparison is true when the input value is
2641 /// signed.
2642 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2643                            bool &TrueIfSigned) {
2644   switch (pred) {
2645   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2646     TrueIfSigned = true;
2647     return RHS->isZero();
2648   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2649     TrueIfSigned = true;
2650     return RHS->isAllOnesValue();
2651   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2652     TrueIfSigned = false;
2653     return RHS->isAllOnesValue();
2654   case ICmpInst::ICMP_UGT:
2655     // True if LHS u> RHS and RHS == high-bit-mask - 1
2656     TrueIfSigned = true;
2657     return RHS->getValue() ==
2658       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2659   case ICmpInst::ICMP_UGE: 
2660     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2661     TrueIfSigned = true;
2662     return RHS->getValue().isSignBit();
2663   default:
2664     return false;
2665   }
2666 }
2667
2668 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2669   bool Changed = SimplifyCommutative(I);
2670   Value *Op0 = I.getOperand(0);
2671
2672   // TODO: If Op1 is undef and Op0 is finite, return zero.
2673   if (!I.getType()->isFPOrFPVector() &&
2674       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2675     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2676
2677   // Simplify mul instructions with a constant RHS...
2678   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2679     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2680
2681       // ((X << C1)*C2) == (X * (C2 << C1))
2682       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2683         if (SI->getOpcode() == Instruction::Shl)
2684           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2685             return BinaryOperator::CreateMul(SI->getOperand(0),
2686                                         Context->getConstantExprShl(CI, ShOp));
2687
2688       if (CI->isZero())
2689         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2690       if (CI->equalsInt(1))                  // X * 1  == X
2691         return ReplaceInstUsesWith(I, Op0);
2692       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2693         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2694
2695       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2696       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2697         return BinaryOperator::CreateShl(Op0,
2698                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2699       }
2700     } else if (isa<VectorType>(Op1->getType())) {
2701       if (Op1->isNullValue())
2702         return ReplaceInstUsesWith(I, Op1);
2703
2704       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2705         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2706           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2707
2708         // As above, vector X*splat(1.0) -> X in all defined cases.
2709         if (Constant *Splat = Op1V->getSplatValue()) {
2710           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2711             if (CI->equalsInt(1))
2712               return ReplaceInstUsesWith(I, Op0);
2713         }
2714       }
2715     }
2716     
2717     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2718       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2719           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2720         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2721         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2722                                                      Op1, "tmp");
2723         InsertNewInstBefore(Add, I);
2724         Value *C1C2 = Context->getConstantExprMul(Op1, 
2725                                            cast<Constant>(Op0I->getOperand(1)));
2726         return BinaryOperator::CreateAdd(Add, C1C2);
2727         
2728       }
2729
2730     // Try to fold constant mul into select arguments.
2731     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2732       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2733         return R;
2734
2735     if (isa<PHINode>(Op0))
2736       if (Instruction *NV = FoldOpIntoPhi(I))
2737         return NV;
2738   }
2739
2740   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2741     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2742       return BinaryOperator::CreateMul(Op0v, Op1v);
2743
2744   // (X / Y) *  Y = X - (X % Y)
2745   // (X / Y) * -Y = (X % Y) - X
2746   {
2747     Value *Op1 = I.getOperand(1);
2748     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2749     if (!BO ||
2750         (BO->getOpcode() != Instruction::UDiv && 
2751          BO->getOpcode() != Instruction::SDiv)) {
2752       Op1 = Op0;
2753       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2754     }
2755     Value *Neg = dyn_castNegVal(Op1, Context);
2756     if (BO && BO->hasOneUse() &&
2757         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2758         (BO->getOpcode() == Instruction::UDiv ||
2759          BO->getOpcode() == Instruction::SDiv)) {
2760       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2761
2762       Instruction *Rem;
2763       if (BO->getOpcode() == Instruction::UDiv)
2764         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2765       else
2766         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2767
2768       InsertNewInstBefore(Rem, I);
2769       Rem->takeName(BO);
2770
2771       if (Op1BO == Op1)
2772         return BinaryOperator::CreateSub(Op0BO, Rem);
2773       else
2774         return BinaryOperator::CreateSub(Rem, Op0BO);
2775     }
2776   }
2777
2778   if (I.getType() == Type::Int1Ty)
2779     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2780
2781   // If one of the operands of the multiply is a cast from a boolean value, then
2782   // we know the bool is either zero or one, so this is a 'masking' multiply.
2783   // See if we can simplify things based on how the boolean was originally
2784   // formed.
2785   CastInst *BoolCast = 0;
2786   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2787     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2788       BoolCast = CI;
2789   if (!BoolCast)
2790     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2791       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2792         BoolCast = CI;
2793   if (BoolCast) {
2794     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2795       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2796       const Type *SCOpTy = SCIOp0->getType();
2797       bool TIS = false;
2798       
2799       // If the icmp is true iff the sign bit of X is set, then convert this
2800       // multiply into a shift/and combination.
2801       if (isa<ConstantInt>(SCIOp1) &&
2802           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2803           TIS) {
2804         // Shift the X value right to turn it into "all signbits".
2805         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2806                                           SCOpTy->getPrimitiveSizeInBits()-1);
2807         Value *V =
2808           InsertNewInstBefore(
2809             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2810                                             BoolCast->getOperand(0)->getName()+
2811                                             ".mask"), I);
2812
2813         // If the multiply type is not the same as the source type, sign extend
2814         // or truncate to the multiply type.
2815         if (I.getType() != V->getType()) {
2816           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2817           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2818           Instruction::CastOps opcode = 
2819             (SrcBits == DstBits ? Instruction::BitCast : 
2820              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2821           V = InsertCastBefore(opcode, V, I.getType(), I);
2822         }
2823
2824         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2825         return BinaryOperator::CreateAnd(V, OtherOp);
2826       }
2827     }
2828   }
2829
2830   return Changed ? &I : 0;
2831 }
2832
2833 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2834   bool Changed = SimplifyCommutative(I);
2835   Value *Op0 = I.getOperand(0);
2836
2837   // Simplify mul instructions with a constant RHS...
2838   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2839     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2840       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2841       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2842       if (Op1F->isExactlyValue(1.0))
2843         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2844     } else if (isa<VectorType>(Op1->getType())) {
2845       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2846         // As above, vector X*splat(1.0) -> X in all defined cases.
2847         if (Constant *Splat = Op1V->getSplatValue()) {
2848           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2849             if (F->isExactlyValue(1.0))
2850               return ReplaceInstUsesWith(I, Op0);
2851         }
2852       }
2853     }
2854
2855     // Try to fold constant mul into select arguments.
2856     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2857       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2858         return R;
2859
2860     if (isa<PHINode>(Op0))
2861       if (Instruction *NV = FoldOpIntoPhi(I))
2862         return NV;
2863   }
2864
2865   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2866     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2867       return BinaryOperator::CreateFMul(Op0v, Op1v);
2868
2869   return Changed ? &I : 0;
2870 }
2871
2872 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2873 /// instruction.
2874 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2875   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2876   
2877   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2878   int NonNullOperand = -1;
2879   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2880     if (ST->isNullValue())
2881       NonNullOperand = 2;
2882   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2883   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2884     if (ST->isNullValue())
2885       NonNullOperand = 1;
2886   
2887   if (NonNullOperand == -1)
2888     return false;
2889   
2890   Value *SelectCond = SI->getOperand(0);
2891   
2892   // Change the div/rem to use 'Y' instead of the select.
2893   I.setOperand(1, SI->getOperand(NonNullOperand));
2894   
2895   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2896   // problem.  However, the select, or the condition of the select may have
2897   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2898   // propagate the known value for the select into other uses of it, and
2899   // propagate a known value of the condition into its other users.
2900   
2901   // If the select and condition only have a single use, don't bother with this,
2902   // early exit.
2903   if (SI->use_empty() && SelectCond->hasOneUse())
2904     return true;
2905   
2906   // Scan the current block backward, looking for other uses of SI.
2907   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2908   
2909   while (BBI != BBFront) {
2910     --BBI;
2911     // If we found a call to a function, we can't assume it will return, so
2912     // information from below it cannot be propagated above it.
2913     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2914       break;
2915     
2916     // Replace uses of the select or its condition with the known values.
2917     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2918          I != E; ++I) {
2919       if (*I == SI) {
2920         *I = SI->getOperand(NonNullOperand);
2921         AddToWorkList(BBI);
2922       } else if (*I == SelectCond) {
2923         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2924                                    Context->getConstantIntFalse();
2925         AddToWorkList(BBI);
2926       }
2927     }
2928     
2929     // If we past the instruction, quit looking for it.
2930     if (&*BBI == SI)
2931       SI = 0;
2932     if (&*BBI == SelectCond)
2933       SelectCond = 0;
2934     
2935     // If we ran out of things to eliminate, break out of the loop.
2936     if (SelectCond == 0 && SI == 0)
2937       break;
2938     
2939   }
2940   return true;
2941 }
2942
2943
2944 /// This function implements the transforms on div instructions that work
2945 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2946 /// used by the visitors to those instructions.
2947 /// @brief Transforms common to all three div instructions
2948 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2949   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2950
2951   // undef / X -> 0        for integer.
2952   // undef / X -> undef    for FP (the undef could be a snan).
2953   if (isa<UndefValue>(Op0)) {
2954     if (Op0->getType()->isFPOrFPVector())
2955       return ReplaceInstUsesWith(I, Op0);
2956     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2957   }
2958
2959   // X / undef -> undef
2960   if (isa<UndefValue>(Op1))
2961     return ReplaceInstUsesWith(I, Op1);
2962
2963   return 0;
2964 }
2965
2966 /// This function implements the transforms common to both integer division
2967 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2968 /// division instructions.
2969 /// @brief Common integer divide transforms
2970 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
2973   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2974   if (Op0 == Op1) {
2975     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2976       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2977       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2978       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2979     }
2980
2981     Constant *CI = Context->getConstantInt(I.getType(), 1);
2982     return ReplaceInstUsesWith(I, CI);
2983   }
2984   
2985   if (Instruction *Common = commonDivTransforms(I))
2986     return Common;
2987   
2988   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2989   // This does not apply for fdiv.
2990   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2991     return &I;
2992
2993   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2994     // div X, 1 == X
2995     if (RHS->equalsInt(1))
2996       return ReplaceInstUsesWith(I, Op0);
2997
2998     // (X / C1) / C2  -> X / (C1*C2)
2999     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3000       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3001         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3002           if (MultiplyOverflows(RHS, LHSRHS,
3003                                 I.getOpcode()==Instruction::SDiv, Context))
3004             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3005           else 
3006             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3007                                       Context->getConstantExprMul(RHS, LHSRHS));
3008         }
3009
3010     if (!RHS->isZero()) { // avoid X udiv 0
3011       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3012         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3013           return R;
3014       if (isa<PHINode>(Op0))
3015         if (Instruction *NV = FoldOpIntoPhi(I))
3016           return NV;
3017     }
3018   }
3019
3020   // 0 / X == 0, we don't need to preserve faults!
3021   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3022     if (LHS->equalsInt(0))
3023       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3024
3025   // It can't be division by zero, hence it must be division by one.
3026   if (I.getType() == Type::Int1Ty)
3027     return ReplaceInstUsesWith(I, Op0);
3028
3029   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3030     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3031       // div X, 1 == X
3032       if (X->isOne())
3033         return ReplaceInstUsesWith(I, Op0);
3034   }
3035
3036   return 0;
3037 }
3038
3039 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3040   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3041
3042   // Handle the integer div common cases
3043   if (Instruction *Common = commonIDivTransforms(I))
3044     return Common;
3045
3046   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3047     // X udiv C^2 -> X >> C
3048     // Check to see if this is an unsigned division with an exact power of 2,
3049     // if so, convert to a right shift.
3050     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3051       return BinaryOperator::CreateLShr(Op0, 
3052             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3053
3054     // X udiv C, where C >= signbit
3055     if (C->getValue().isNegative()) {
3056       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3057                                                     ICmpInst::ICMP_ULT, Op0, C),
3058                                       I);
3059       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3060                                 Context->getConstantInt(I.getType(), 1));
3061     }
3062   }
3063
3064   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3065   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3066     if (RHSI->getOpcode() == Instruction::Shl &&
3067         isa<ConstantInt>(RHSI->getOperand(0))) {
3068       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3069       if (C1.isPowerOf2()) {
3070         Value *N = RHSI->getOperand(1);
3071         const Type *NTy = N->getType();
3072         if (uint32_t C2 = C1.logBase2()) {
3073           Constant *C2V = Context->getConstantInt(NTy, C2);
3074           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3075         }
3076         return BinaryOperator::CreateLShr(Op0, N);
3077       }
3078     }
3079   }
3080   
3081   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3082   // where C1&C2 are powers of two.
3083   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3084     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3085       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3086         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3087         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3088           // Compute the shift amounts
3089           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3090           // Construct the "on true" case of the select
3091           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3092           Instruction *TSI = BinaryOperator::CreateLShr(
3093                                                  Op0, TC, SI->getName()+".t");
3094           TSI = InsertNewInstBefore(TSI, I);
3095   
3096           // Construct the "on false" case of the select
3097           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3098           Instruction *FSI = BinaryOperator::CreateLShr(
3099                                                  Op0, FC, SI->getName()+".f");
3100           FSI = InsertNewInstBefore(FSI, I);
3101
3102           // construct the select instruction and return it.
3103           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3104         }
3105       }
3106   return 0;
3107 }
3108
3109 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3110   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3111
3112   // Handle the integer div common cases
3113   if (Instruction *Common = commonIDivTransforms(I))
3114     return Common;
3115
3116   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117     // sdiv X, -1 == -X
3118     if (RHS->isAllOnesValue())
3119       return BinaryOperator::CreateNeg(*Context, Op0);
3120   }
3121
3122   // If the sign bits of both operands are zero (i.e. we can prove they are
3123   // unsigned inputs), turn this into a udiv.
3124   if (I.getType()->isInteger()) {
3125     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3126     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3127       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3128       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3129     }
3130   }      
3131   
3132   return 0;
3133 }
3134
3135 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3136   return commonDivTransforms(I);
3137 }
3138
3139 /// This function implements the transforms on rem instructions that work
3140 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3141 /// is used by the visitors to those instructions.
3142 /// @brief Transforms common to all three rem instructions
3143 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3144   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3145
3146   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3147     if (I.getType()->isFPOrFPVector())
3148       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3149     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3150   }
3151   if (isa<UndefValue>(Op1))
3152     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3153
3154   // Handle cases involving: rem X, (select Cond, Y, Z)
3155   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3156     return &I;
3157
3158   return 0;
3159 }
3160
3161 /// This function implements the transforms common to both integer remainder
3162 /// instructions (urem and srem). It is called by the visitors to those integer
3163 /// remainder instructions.
3164 /// @brief Common integer remainder transforms
3165 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3166   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3167
3168   if (Instruction *common = commonRemTransforms(I))
3169     return common;
3170
3171   // 0 % X == 0 for integer, we don't need to preserve faults!
3172   if (Constant *LHS = dyn_cast<Constant>(Op0))
3173     if (LHS->isNullValue())
3174       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3175
3176   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3177     // X % 0 == undef, we don't need to preserve faults!
3178     if (RHS->equalsInt(0))
3179       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3180     
3181     if (RHS->equalsInt(1))  // X % 1 == 0
3182       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3183
3184     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3185       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3186         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3187           return R;
3188       } else if (isa<PHINode>(Op0I)) {
3189         if (Instruction *NV = FoldOpIntoPhi(I))
3190           return NV;
3191       }
3192
3193       // See if we can fold away this rem instruction.
3194       if (SimplifyDemandedInstructionBits(I))
3195         return &I;
3196     }
3197   }
3198
3199   return 0;
3200 }
3201
3202 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3203   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205   if (Instruction *common = commonIRemTransforms(I))
3206     return common;
3207   
3208   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209     // X urem C^2 -> X and C
3210     // Check to see if this is an unsigned remainder with an exact power of 2,
3211     // if so, convert to a bitwise and.
3212     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3213       if (C->getValue().isPowerOf2())
3214         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3215   }
3216
3217   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3218     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3219     if (RHSI->getOpcode() == Instruction::Shl &&
3220         isa<ConstantInt>(RHSI->getOperand(0))) {
3221       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3222         Constant *N1 = Context->getAllOnesValue(I.getType());
3223         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3224                                                                    "tmp"), I);
3225         return BinaryOperator::CreateAnd(Op0, Add);
3226       }
3227     }
3228   }
3229
3230   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3231   // where C1&C2 are powers of two.
3232   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3233     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3234       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3235         // STO == 0 and SFO == 0 handled above.
3236         if ((STO->getValue().isPowerOf2()) && 
3237             (SFO->getValue().isPowerOf2())) {
3238           Value *TrueAnd = InsertNewInstBefore(
3239             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3240                                       SI->getName()+".t"), I);
3241           Value *FalseAnd = InsertNewInstBefore(
3242             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3243                                       SI->getName()+".f"), I);
3244           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3245         }
3246       }
3247   }
3248   
3249   return 0;
3250 }
3251
3252 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3254
3255   // Handle the integer rem common cases
3256   if (Instruction *common = commonIRemTransforms(I))
3257     return common;
3258   
3259   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3260     if (!isa<Constant>(RHSNeg) ||
3261         (isa<ConstantInt>(RHSNeg) &&
3262          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3263       // X % -Y -> X % Y
3264       AddUsesToWorkList(I);
3265       I.setOperand(1, RHSNeg);
3266       return &I;
3267     }
3268
3269   // If the sign bits of both operands are zero (i.e. we can prove they are
3270   // unsigned inputs), turn this into a urem.
3271   if (I.getType()->isInteger()) {
3272     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3273     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3274       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3275       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3276     }
3277   }
3278
3279   // If it's a constant vector, flip any negative values positive.
3280   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3281     unsigned VWidth = RHSV->getNumOperands();
3282
3283     bool hasNegative = false;
3284     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3285       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3286         if (RHS->getValue().isNegative())
3287           hasNegative = true;
3288
3289     if (hasNegative) {
3290       std::vector<Constant *> Elts(VWidth);
3291       for (unsigned i = 0; i != VWidth; ++i) {
3292         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3293           if (RHS->getValue().isNegative())
3294             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3295           else
3296             Elts[i] = RHS;
3297         }
3298       }
3299
3300       Constant *NewRHSV = Context->getConstantVector(Elts);
3301       if (NewRHSV != RHSV) {
3302         AddUsesToWorkList(I);
3303         I.setOperand(1, NewRHSV);
3304         return &I;
3305       }
3306     }
3307   }
3308
3309   return 0;
3310 }
3311
3312 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3313   return commonRemTransforms(I);
3314 }
3315
3316 // isOneBitSet - Return true if there is exactly one bit set in the specified
3317 // constant.
3318 static bool isOneBitSet(const ConstantInt *CI) {
3319   return CI->getValue().isPowerOf2();
3320 }
3321
3322 // isHighOnes - Return true if the constant is of the form 1+0+.
3323 // This is the same as lowones(~X).
3324 static bool isHighOnes(const ConstantInt *CI) {
3325   return (~CI->getValue() + 1).isPowerOf2();
3326 }
3327
3328 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3329 /// are carefully arranged to allow folding of expressions such as:
3330 ///
3331 ///      (A < B) | (A > B) --> (A != B)
3332 ///
3333 /// Note that this is only valid if the first and second predicates have the
3334 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3335 ///
3336 /// Three bits are used to represent the condition, as follows:
3337 ///   0  A > B
3338 ///   1  A == B
3339 ///   2  A < B
3340 ///
3341 /// <=>  Value  Definition
3342 /// 000     0   Always false
3343 /// 001     1   A >  B
3344 /// 010     2   A == B
3345 /// 011     3   A >= B
3346 /// 100     4   A <  B
3347 /// 101     5   A != B
3348 /// 110     6   A <= B
3349 /// 111     7   Always true
3350 ///  
3351 static unsigned getICmpCode(const ICmpInst *ICI) {
3352   switch (ICI->getPredicate()) {
3353     // False -> 0
3354   case ICmpInst::ICMP_UGT: return 1;  // 001
3355   case ICmpInst::ICMP_SGT: return 1;  // 001
3356   case ICmpInst::ICMP_EQ:  return 2;  // 010
3357   case ICmpInst::ICMP_UGE: return 3;  // 011
3358   case ICmpInst::ICMP_SGE: return 3;  // 011
3359   case ICmpInst::ICMP_ULT: return 4;  // 100
3360   case ICmpInst::ICMP_SLT: return 4;  // 100
3361   case ICmpInst::ICMP_NE:  return 5;  // 101
3362   case ICmpInst::ICMP_ULE: return 6;  // 110
3363   case ICmpInst::ICMP_SLE: return 6;  // 110
3364     // True -> 7
3365   default:
3366     llvm_unreachable("Invalid ICmp predicate!");
3367     return 0;
3368   }
3369 }
3370
3371 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3372 /// predicate into a three bit mask. It also returns whether it is an ordered
3373 /// predicate by reference.
3374 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3375   isOrdered = false;
3376   switch (CC) {
3377   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3378   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3379   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3380   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3381   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3382   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3383   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3384   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3385   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3386   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3387   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3388   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3389   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3390   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3391     // True -> 7
3392   default:
3393     // Not expecting FCMP_FALSE and FCMP_TRUE;
3394     llvm_unreachable("Unexpected FCmp predicate!");
3395     return 0;
3396   }
3397 }
3398
3399 /// getICmpValue - This is the complement of getICmpCode, which turns an
3400 /// opcode and two operands into either a constant true or false, or a brand 
3401 /// new ICmp instruction. The sign is passed in to determine which kind
3402 /// of predicate to use in the new icmp instruction.
3403 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3404                            LLVMContext *Context) {
3405   switch (code) {
3406   default: llvm_unreachable("Illegal ICmp code!");
3407   case  0: return Context->getConstantIntFalse();
3408   case  1: 
3409     if (sign)
3410       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3411     else
3412       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3413   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3414   case  3: 
3415     if (sign)
3416       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3417     else
3418       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3419   case  4: 
3420     if (sign)
3421       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3422     else
3423       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3424   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3425   case  6: 
3426     if (sign)
3427       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3428     else
3429       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3430   case  7: return Context->getConstantIntTrue();
3431   }
3432 }
3433
3434 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3435 /// opcode and two operands into either a FCmp instruction. isordered is passed
3436 /// in to determine which kind of predicate to use in the new fcmp instruction.
3437 static Value *getFCmpValue(bool isordered, unsigned code,
3438                            Value *LHS, Value *RHS, LLVMContext *Context) {
3439   switch (code) {
3440   default: llvm_unreachable("Illegal FCmp code!");
3441   case  0:
3442     if (isordered)
3443       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3444     else
3445       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3446   case  1: 
3447     if (isordered)
3448       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3449     else
3450       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3451   case  2: 
3452     if (isordered)
3453       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3454     else
3455       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3456   case  3: 
3457     if (isordered)
3458       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3459     else
3460       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3461   case  4: 
3462     if (isordered)
3463       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3464     else
3465       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3466   case  5: 
3467     if (isordered)
3468       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3469     else
3470       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3471   case  6: 
3472     if (isordered)
3473       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3474     else
3475       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3476   case  7: return Context->getConstantIntTrue();
3477   }
3478 }
3479
3480 /// PredicatesFoldable - Return true if both predicates match sign or if at
3481 /// least one of them is an equality comparison (which is signless).
3482 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3483   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3484          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3485          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3486 }
3487
3488 namespace { 
3489 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3490 struct FoldICmpLogical {
3491   InstCombiner &IC;
3492   Value *LHS, *RHS;
3493   ICmpInst::Predicate pred;
3494   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3495     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3496       pred(ICI->getPredicate()) {}
3497   bool shouldApply(Value *V) const {
3498     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3499       if (PredicatesFoldable(pred, ICI->getPredicate()))
3500         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3501                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3502     return false;
3503   }
3504   Instruction *apply(Instruction &Log) const {
3505     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3506     if (ICI->getOperand(0) != LHS) {
3507       assert(ICI->getOperand(1) == LHS);
3508       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3509     }
3510
3511     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3512     unsigned LHSCode = getICmpCode(ICI);
3513     unsigned RHSCode = getICmpCode(RHSICI);
3514     unsigned Code;
3515     switch (Log.getOpcode()) {
3516     case Instruction::And: Code = LHSCode & RHSCode; break;
3517     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3518     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3519     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3520     }
3521
3522     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3523                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3524       
3525     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3526     if (Instruction *I = dyn_cast<Instruction>(RV))
3527       return I;
3528     // Otherwise, it's a constant boolean value...
3529     return IC.ReplaceInstUsesWith(Log, RV);
3530   }
3531 };
3532 } // end anonymous namespace
3533
3534 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3535 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3536 // guaranteed to be a binary operator.
3537 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3538                                     ConstantInt *OpRHS,
3539                                     ConstantInt *AndRHS,
3540                                     BinaryOperator &TheAnd) {
3541   Value *X = Op->getOperand(0);
3542   Constant *Together = 0;
3543   if (!Op->isShift())
3544     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3545
3546   switch (Op->getOpcode()) {
3547   case Instruction::Xor:
3548     if (Op->hasOneUse()) {
3549       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3550       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3551       InsertNewInstBefore(And, TheAnd);
3552       And->takeName(Op);
3553       return BinaryOperator::CreateXor(And, Together);
3554     }
3555     break;
3556   case Instruction::Or:
3557     if (Together == AndRHS) // (X | C) & C --> C
3558       return ReplaceInstUsesWith(TheAnd, AndRHS);
3559
3560     if (Op->hasOneUse() && Together != OpRHS) {
3561       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3562       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3563       InsertNewInstBefore(Or, TheAnd);
3564       Or->takeName(Op);
3565       return BinaryOperator::CreateAnd(Or, AndRHS);
3566     }
3567     break;
3568   case Instruction::Add:
3569     if (Op->hasOneUse()) {
3570       // Adding a one to a single bit bit-field should be turned into an XOR
3571       // of the bit.  First thing to check is to see if this AND is with a
3572       // single bit constant.
3573       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3574
3575       // If there is only one bit set...
3576       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3577         // Ok, at this point, we know that we are masking the result of the
3578         // ADD down to exactly one bit.  If the constant we are adding has
3579         // no bits set below this bit, then we can eliminate the ADD.
3580         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3581
3582         // Check to see if any bits below the one bit set in AndRHSV are set.
3583         if ((AddRHS & (AndRHSV-1)) == 0) {
3584           // If not, the only thing that can effect the output of the AND is
3585           // the bit specified by AndRHSV.  If that bit is set, the effect of
3586           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3587           // no effect.
3588           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3589             TheAnd.setOperand(0, X);
3590             return &TheAnd;
3591           } else {
3592             // Pull the XOR out of the AND.
3593             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3594             InsertNewInstBefore(NewAnd, TheAnd);
3595             NewAnd->takeName(Op);
3596             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3597           }
3598         }
3599       }
3600     }
3601     break;
3602
3603   case Instruction::Shl: {
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!
3606     //
3607     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3608     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3609     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3610     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3611
3612     if (CI->getValue() == ShlMask) { 
3613     // Masking out bits that the shift already masks
3614       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3615     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3616       TheAnd.setOperand(1, CI);
3617       return &TheAnd;
3618     }
3619     break;
3620   }
3621   case Instruction::LShr:
3622   {
3623     // We know that the AND will not produce any of the bits shifted in, so if
3624     // the anded constant includes them, clear them now!  This only applies to
3625     // unsigned shifts, because a signed shr may bring in set bits!
3626     //
3627     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3628     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3629     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3630     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3631
3632     if (CI->getValue() == ShrMask) {   
3633     // Masking out bits that the shift already masks.
3634       return ReplaceInstUsesWith(TheAnd, Op);
3635     } else if (CI != AndRHS) {
3636       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3637       return &TheAnd;
3638     }
3639     break;
3640   }
3641   case Instruction::AShr:
3642     // Signed shr.
3643     // See if this is shifting in some sign extension, then masking it out
3644     // with an and.
3645     if (Op->hasOneUse()) {
3646       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3647       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3648       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3649       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3650       if (C == AndRHS) {          // Masking out bits shifted in.
3651         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3652         // Make the argument unsigned.
3653         Value *ShVal = Op->getOperand(0);
3654         ShVal = InsertNewInstBefore(
3655             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3656                                    Op->getName()), TheAnd);
3657         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3658       }
3659     }
3660     break;
3661   }
3662   return 0;
3663 }
3664
3665
3666 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3667 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3668 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3669 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3670 /// insert new instructions.
3671 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3672                                            bool isSigned, bool Inside, 
3673                                            Instruction &IB) {
3674   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3675             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3676          "Lo is not <= Hi in range emission code!");
3677     
3678   if (Inside) {
3679     if (Lo == Hi)  // Trivially false.
3680       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3681
3682     // V >= Min && V < Hi --> V < Hi
3683     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3684       ICmpInst::Predicate pred = (isSigned ? 
3685         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3686       return new ICmpInst(*Context, pred, V, Hi);
3687     }
3688
3689     // Emit V-Lo <u Hi-Lo
3690     Constant *NegLo = Context->getConstantExprNeg(Lo);
3691     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3692     InsertNewInstBefore(Add, IB);
3693     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3694     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3695   }
3696
3697   if (Lo == Hi)  // Trivially true.
3698     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3699
3700   // V < Min || V >= Hi -> V > Hi-1
3701   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3702   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3703     ICmpInst::Predicate pred = (isSigned ? 
3704         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3705     return new ICmpInst(*Context, pred, V, Hi);
3706   }
3707
3708   // Emit V-Lo >u Hi-1-Lo
3709   // Note that Hi has already had one subtracted from it, above.
3710   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3711   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3712   InsertNewInstBefore(Add, IB);
3713   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3714   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3715 }
3716
3717 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3718 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3719 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3720 // not, since all 1s are not contiguous.
3721 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3722   const APInt& V = Val->getValue();
3723   uint32_t BitWidth = Val->getType()->getBitWidth();
3724   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3725
3726   // look for the first zero bit after the run of ones
3727   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3728   // look for the first non-zero bit
3729   ME = V.getActiveBits(); 
3730   return true;
3731 }
3732
3733 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3734 /// where isSub determines whether the operator is a sub.  If we can fold one of
3735 /// the following xforms:
3736 /// 
3737 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3738 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3739 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740 ///
3741 /// return (A +/- B).
3742 ///
3743 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3744                                         ConstantInt *Mask, bool isSub,
3745                                         Instruction &I) {
3746   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3747   if (!LHSI || LHSI->getNumOperands() != 2 ||
3748       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3749
3750   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3751
3752   switch (LHSI->getOpcode()) {
3753   default: return 0;
3754   case Instruction::And:
3755     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3756       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3757       if ((Mask->getValue().countLeadingZeros() + 
3758            Mask->getValue().countPopulation()) == 
3759           Mask->getValue().getBitWidth())
3760         break;
3761
3762       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3763       // part, we don't need any explicit masks to take them out of A.  If that
3764       // is all N is, ignore it.
3765       uint32_t MB = 0, ME = 0;
3766       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3767         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3768         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3769         if (MaskedValueIsZero(RHS, Mask))
3770           break;
3771       }
3772     }
3773     return 0;
3774   case Instruction::Or:
3775   case Instruction::Xor:
3776     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3777     if ((Mask->getValue().countLeadingZeros() + 
3778          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3779         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3780       break;
3781     return 0;
3782   }
3783   
3784   Instruction *New;
3785   if (isSub)
3786     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3787   else
3788     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3789   return InsertNewInstBefore(New, I);
3790 }
3791
3792 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3793 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3794                                           ICmpInst *LHS, ICmpInst *RHS) {
3795   Value *Val, *Val2;
3796   ConstantInt *LHSCst, *RHSCst;
3797   ICmpInst::Predicate LHSCC, RHSCC;
3798   
3799   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3800   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3801                          m_ConstantInt(LHSCst)), *Context) ||
3802       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3803                          m_ConstantInt(RHSCst)), *Context))
3804     return 0;
3805   
3806   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3807   // where C is a power of 2
3808   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3809       LHSCst->getValue().isPowerOf2()) {
3810     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3811     InsertNewInstBefore(NewOr, I);
3812     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3813   }
3814   
3815   // From here on, we only handle:
3816   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3817   if (Val != Val2) return 0;
3818   
3819   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3820   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3821       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3822       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3823       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3824     return 0;
3825   
3826   // We can't fold (ugt x, C) & (sgt x, C2).
3827   if (!PredicatesFoldable(LHSCC, RHSCC))
3828     return 0;
3829     
3830   // Ensure that the larger constant is on the RHS.
3831   bool ShouldSwap;
3832   if (ICmpInst::isSignedPredicate(LHSCC) ||
3833       (ICmpInst::isEquality(LHSCC) && 
3834        ICmpInst::isSignedPredicate(RHSCC)))
3835     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3836   else
3837     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3838     
3839   if (ShouldSwap) {
3840     std::swap(LHS, RHS);
3841     std::swap(LHSCst, RHSCst);
3842     std::swap(LHSCC, RHSCC);
3843   }
3844
3845   // At this point, we know we have have two icmp instructions
3846   // comparing a value against two constants and and'ing the result
3847   // together.  Because of the above check, we know that we only have
3848   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3849   // (from the FoldICmpLogical check above), that the two constants 
3850   // are not equal and that the larger constant is on the RHS
3851   assert(LHSCst != RHSCst && "Compares not folded above?");
3852
3853   switch (LHSCC) {
3854   default: llvm_unreachable("Unknown integer condition code!");
3855   case ICmpInst::ICMP_EQ:
3856     switch (RHSCC) {
3857     default: llvm_unreachable("Unknown integer condition code!");
3858     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3859     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3860     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3861       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3862     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3863     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3864     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3865       return ReplaceInstUsesWith(I, LHS);
3866     }
3867   case ICmpInst::ICMP_NE:
3868     switch (RHSCC) {
3869     default: llvm_unreachable("Unknown integer condition code!");
3870     case ICmpInst::ICMP_ULT:
3871       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3872         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3873       break;                        // (X != 13 & X u< 15) -> no change
3874     case ICmpInst::ICMP_SLT:
3875       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3876         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3877       break;                        // (X != 13 & X s< 15) -> no change
3878     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3879     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3880     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3881       return ReplaceInstUsesWith(I, RHS);
3882     case ICmpInst::ICMP_NE:
3883       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3884         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3885         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3886                                                      Val->getName()+".off");
3887         InsertNewInstBefore(Add, I);
3888         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3889                             Context->getConstantInt(Add->getType(), 1));
3890       }
3891       break;                        // (X != 13 & X != 15) -> no change
3892     }
3893     break;
3894   case ICmpInst::ICMP_ULT:
3895     switch (RHSCC) {
3896     default: llvm_unreachable("Unknown integer condition code!");
3897     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3898     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3899       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3900     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3901       break;
3902     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3903     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3904       return ReplaceInstUsesWith(I, LHS);
3905     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3906       break;
3907     }
3908     break;
3909   case ICmpInst::ICMP_SLT:
3910     switch (RHSCC) {
3911     default: llvm_unreachable("Unknown integer condition code!");
3912     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3913     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3914       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3915     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3916       break;
3917     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3918     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3919       return ReplaceInstUsesWith(I, LHS);
3920     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3921       break;
3922     }
3923     break;
3924   case ICmpInst::ICMP_UGT:
3925     switch (RHSCC) {
3926     default: llvm_unreachable("Unknown integer condition code!");
3927     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3928     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3929       return ReplaceInstUsesWith(I, RHS);
3930     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3931       break;
3932     case ICmpInst::ICMP_NE:
3933       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3934         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3935       break;                        // (X u> 13 & X != 15) -> no change
3936     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3937       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3938                              RHSCst, false, true, I);
3939     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3940       break;
3941     }
3942     break;
3943   case ICmpInst::ICMP_SGT:
3944     switch (RHSCC) {
3945     default: llvm_unreachable("Unknown integer condition code!");
3946     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3947     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3948       return ReplaceInstUsesWith(I, RHS);
3949     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3950       break;
3951     case ICmpInst::ICMP_NE:
3952       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3953         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3954       break;                        // (X s> 13 & X != 15) -> no change
3955     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3956       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3957                              RHSCst, true, true, I);
3958     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3959       break;
3960     }
3961     break;
3962   }
3963  
3964   return 0;
3965 }
3966
3967
3968 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3969   bool Changed = SimplifyCommutative(I);
3970   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3971
3972   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3973     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3974
3975   // and X, X = X
3976   if (Op0 == Op1)
3977     return ReplaceInstUsesWith(I, Op1);
3978
3979   // See if we can simplify any instructions used by the instruction whose sole 
3980   // purpose is to compute bits we don't care about.
3981   if (SimplifyDemandedInstructionBits(I))
3982     return &I;
3983   if (isa<VectorType>(I.getType())) {
3984     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3985       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3986         return ReplaceInstUsesWith(I, I.getOperand(0));
3987     } else if (isa<ConstantAggregateZero>(Op1)) {
3988       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3989     }
3990   }
3991
3992   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3993     const APInt& AndRHSMask = AndRHS->getValue();
3994     APInt NotAndRHS(~AndRHSMask);
3995
3996     // Optimize a variety of ((val OP C1) & C2) combinations...
3997     if (isa<BinaryOperator>(Op0)) {
3998       Instruction *Op0I = cast<Instruction>(Op0);
3999       Value *Op0LHS = Op0I->getOperand(0);
4000       Value *Op0RHS = Op0I->getOperand(1);
4001       switch (Op0I->getOpcode()) {
4002       case Instruction::Xor:
4003       case Instruction::Or:
4004         // If the mask is only needed on one incoming arm, push it up.
4005         if (Op0I->hasOneUse()) {
4006           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4007             // Not masking anything out for the LHS, move to RHS.
4008             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4009                                                    Op0RHS->getName()+".masked");
4010             InsertNewInstBefore(NewRHS, I);
4011             return BinaryOperator::Create(
4012                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4013           }
4014           if (!isa<Constant>(Op0RHS) &&
4015               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4016             // Not masking anything out for the RHS, move to LHS.
4017             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4018                                                    Op0LHS->getName()+".masked");
4019             InsertNewInstBefore(NewLHS, I);
4020             return BinaryOperator::Create(
4021                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4022           }
4023         }
4024
4025         break;
4026       case Instruction::Add:
4027         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4028         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4029         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4031           return BinaryOperator::CreateAnd(V, AndRHS);
4032         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4033           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4034         break;
4035
4036       case Instruction::Sub:
4037         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4038         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4039         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4041           return BinaryOperator::CreateAnd(V, AndRHS);
4042
4043         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4044         // has 1's for all bits that the subtraction with A might affect.
4045         if (Op0I->hasOneUse()) {
4046           uint32_t BitWidth = AndRHSMask.getBitWidth();
4047           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4048           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4049
4050           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4051           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4052               MaskedValueIsZero(Op0LHS, Mask)) {
4053             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4054             InsertNewInstBefore(NewNeg, I);
4055             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4056           }
4057         }
4058         break;
4059
4060       case Instruction::Shl:
4061       case Instruction::LShr:
4062         // (1 << x) & 1 --> zext(x == 0)
4063         // (1 >> x) & 1 --> zext(x == 0)
4064         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4065           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4066                                     Op0RHS, Context->getNullValue(I.getType()));
4067           InsertNewInstBefore(NewICmp, I);
4068           return new ZExtInst(NewICmp, I.getType());
4069         }
4070         break;
4071       }
4072
4073       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4074         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4075           return Res;
4076     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4077       // If this is an integer truncation or change from signed-to-unsigned, and
4078       // if the source is an and/or with immediate, transform it.  This
4079       // frequently occurs for bitfield accesses.
4080       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4081         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4082             CastOp->getNumOperands() == 2)
4083           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4084             if (CastOp->getOpcode() == Instruction::And) {
4085               // Change: and (cast (and X, C1) to T), C2
4086               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4087               // This will fold the two constants together, which may allow 
4088               // other simplifications.
4089               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4090                 CastOp->getOperand(0), I.getType(), 
4091                 CastOp->getName()+".shrunk");
4092               NewCast = InsertNewInstBefore(NewCast, I);
4093               // trunc_or_bitcast(C1)&C2
4094               Constant *C3 =
4095                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4096               C3 = Context->getConstantExprAnd(C3, AndRHS);
4097               return BinaryOperator::CreateAnd(NewCast, C3);
4098             } else if (CastOp->getOpcode() == Instruction::Or) {
4099               // Change: and (cast (or X, C1) to T), C2
4100               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4101               Constant *C3 =
4102                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4103               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4104                 // trunc(C1)&C2
4105                 return ReplaceInstUsesWith(I, AndRHS);
4106             }
4107           }
4108       }
4109     }
4110
4111     // Try to fold constant and into select arguments.
4112     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4113       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4114         return R;
4115     if (isa<PHINode>(Op0))
4116       if (Instruction *NV = FoldOpIntoPhi(I))
4117         return NV;
4118   }
4119
4120   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4121   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4122
4123   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4124     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4125
4126   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4127   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4128     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4129                                                I.getName()+".demorgan");
4130     InsertNewInstBefore(Or, I);
4131     return BinaryOperator::CreateNot(*Context, Or);
4132   }
4133   
4134   {
4135     Value *A = 0, *B = 0, *C = 0, *D = 0;
4136     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4137       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4138         return ReplaceInstUsesWith(I, Op1);
4139     
4140       // (A|B) & ~(A&B) -> A^B
4141       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4142         if ((A == C && B == D) || (A == D && B == C))
4143           return BinaryOperator::CreateXor(A, B);
4144       }
4145     }
4146     
4147     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4148       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4149         return ReplaceInstUsesWith(I, Op0);
4150
4151       // ~(A&B) & (A|B) -> A^B
4152       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4153         if ((A == C && B == D) || (A == D && B == C))
4154           return BinaryOperator::CreateXor(A, B);
4155       }
4156     }
4157     
4158     if (Op0->hasOneUse() &&
4159         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4160       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4161         I.swapOperands();     // Simplify below
4162         std::swap(Op0, Op1);
4163       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4164         cast<BinaryOperator>(Op0)->swapOperands();
4165         I.swapOperands();     // Simplify below
4166         std::swap(Op0, Op1);
4167       }
4168     }
4169
4170     if (Op1->hasOneUse() &&
4171         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4172       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4173         cast<BinaryOperator>(Op1)->swapOperands();
4174         std::swap(A, B);
4175       }
4176       if (A == Op0) {                                // A&(A^B) -> A & ~B
4177         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4178         InsertNewInstBefore(NotB, I);
4179         return BinaryOperator::CreateAnd(A, NotB);
4180       }
4181     }
4182
4183     // (A&((~A)|B)) -> A&B
4184     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4185         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4186       return BinaryOperator::CreateAnd(A, Op1);
4187     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4188         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4189       return BinaryOperator::CreateAnd(A, Op0);
4190   }
4191   
4192   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4193     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4194     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4195       return R;
4196
4197     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4198       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4199         return Res;
4200   }
4201
4202   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4203   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4204     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4205       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4206         const Type *SrcTy = Op0C->getOperand(0)->getType();
4207         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4208             // Only do this if the casts both really cause code to be generated.
4209             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4210                               I.getType(), TD) &&
4211             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4212                               I.getType(), TD)) {
4213           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4214                                                          Op1C->getOperand(0),
4215                                                          I.getName());
4216           InsertNewInstBefore(NewOp, I);
4217           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4218         }
4219       }
4220     
4221   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4222   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4223     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4224       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4225           SI0->getOperand(1) == SI1->getOperand(1) &&
4226           (SI0->hasOneUse() || SI1->hasOneUse())) {
4227         Instruction *NewOp =
4228           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4229                                                         SI1->getOperand(0),
4230                                                         SI0->getName()), I);
4231         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4232                                       SI1->getOperand(1));
4233       }
4234   }
4235
4236   // If and'ing two fcmp, try combine them into one.
4237   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4238     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4239       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4240           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4241         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4242         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4243           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4244             // If either of the constants are nans, then the whole thing returns
4245             // false.
4246             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4247               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4248             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4249                                 LHS->getOperand(0), RHS->getOperand(0));
4250           }
4251       } else {
4252         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4253         FCmpInst::Predicate Op0CC, Op1CC;
4254         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4255                   m_Value(Op0RHS)), *Context) &&
4256             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4257                   m_Value(Op1RHS)), *Context)) {
4258           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4259             // Swap RHS operands to match LHS.
4260             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4261             std::swap(Op1LHS, Op1RHS);
4262           }
4263           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4264             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4265             if (Op0CC == Op1CC)
4266               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4267                                   Op0LHS, Op0RHS);
4268             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4269                      Op1CC == FCmpInst::FCMP_FALSE)
4270               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4271             else if (Op0CC == FCmpInst::FCMP_TRUE)
4272               return ReplaceInstUsesWith(I, Op1);
4273             else if (Op1CC == FCmpInst::FCMP_TRUE)
4274               return ReplaceInstUsesWith(I, Op0);
4275             bool Op0Ordered;
4276             bool Op1Ordered;
4277             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4278             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4279             if (Op1Pred == 0) {
4280               std::swap(Op0, Op1);
4281               std::swap(Op0Pred, Op1Pred);
4282               std::swap(Op0Ordered, Op1Ordered);
4283             }
4284             if (Op0Pred == 0) {
4285               // uno && ueq -> uno && (uno || eq) -> ueq
4286               // ord && olt -> ord && (ord && lt) -> olt
4287               if (Op0Ordered == Op1Ordered)
4288                 return ReplaceInstUsesWith(I, Op1);
4289               // uno && oeq -> uno && (ord && eq) -> false
4290               // uno && ord -> false
4291               if (!Op0Ordered)
4292                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4293               // ord && ueq -> ord && (uno || eq) -> oeq
4294               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4295                                                     Op0LHS, Op0RHS, Context));
4296             }
4297           }
4298         }
4299       }
4300     }
4301   }
4302
4303   return Changed ? &I : 0;
4304 }
4305
4306 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4307 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4308 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4309 /// the expression came from the corresponding "byte swapped" byte in some other
4310 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4311 /// we know that the expression deposits the low byte of %X into the high byte
4312 /// of the bswap result and that all other bytes are zero.  This expression is
4313 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4314 /// match.
4315 ///
4316 /// This function returns true if the match was unsuccessful and false if so.
4317 /// On entry to the function the "OverallLeftShift" is a signed integer value
4318 /// indicating the number of bytes that the subexpression is later shifted.  For
4319 /// example, if the expression is later right shifted by 16 bits, the
4320 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4321 /// byte of ByteValues is actually being set.
4322 ///
4323 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4324 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4325 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4326 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4327 /// always in the local (OverallLeftShift) coordinate space.
4328 ///
4329 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4330                               SmallVector<Value*, 8> &ByteValues) {
4331   if (Instruction *I = dyn_cast<Instruction>(V)) {
4332     // If this is an or instruction, it may be an inner node of the bswap.
4333     if (I->getOpcode() == Instruction::Or) {
4334       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4335                                ByteValues) ||
4336              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4337                                ByteValues);
4338     }
4339   
4340     // If this is a logical shift by a constant multiple of 8, recurse with
4341     // OverallLeftShift and ByteMask adjusted.
4342     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4343       unsigned ShAmt = 
4344         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4345       // Ensure the shift amount is defined and of a byte value.
4346       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4347         return true;
4348
4349       unsigned ByteShift = ShAmt >> 3;
4350       if (I->getOpcode() == Instruction::Shl) {
4351         // X << 2 -> collect(X, +2)
4352         OverallLeftShift += ByteShift;
4353         ByteMask >>= ByteShift;
4354       } else {
4355         // X >>u 2 -> collect(X, -2)
4356         OverallLeftShift -= ByteShift;
4357         ByteMask <<= ByteShift;
4358         ByteMask &= (~0U >> (32-ByteValues.size()));
4359       }
4360
4361       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4362       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4363
4364       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4365                                ByteValues);
4366     }
4367
4368     // If this is a logical 'and' with a mask that clears bytes, clear the
4369     // corresponding bytes in ByteMask.
4370     if (I->getOpcode() == Instruction::And &&
4371         isa<ConstantInt>(I->getOperand(1))) {
4372       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4373       unsigned NumBytes = ByteValues.size();
4374       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4375       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4376       
4377       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4378         // If this byte is masked out by a later operation, we don't care what
4379         // the and mask is.
4380         if ((ByteMask & (1 << i)) == 0)
4381           continue;
4382         
4383         // If the AndMask is all zeros for this byte, clear the bit.
4384         APInt MaskB = AndMask & Byte;
4385         if (MaskB == 0) {
4386           ByteMask &= ~(1U << i);
4387           continue;
4388         }
4389         
4390         // If the AndMask is not all ones for this byte, it's not a bytezap.
4391         if (MaskB != Byte)
4392           return true;
4393
4394         // Otherwise, this byte is kept.
4395       }
4396
4397       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4398                                ByteValues);
4399     }
4400   }
4401   
4402   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4403   // the input value to the bswap.  Some observations: 1) if more than one byte
4404   // is demanded from this input, then it could not be successfully assembled
4405   // into a byteswap.  At least one of the two bytes would not be aligned with
4406   // their ultimate destination.
4407   if (!isPowerOf2_32(ByteMask)) return true;
4408   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4409   
4410   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4411   // is demanded, it needs to go into byte 0 of the result.  This means that the
4412   // byte needs to be shifted until it lands in the right byte bucket.  The
4413   // shift amount depends on the position: if the byte is coming from the high
4414   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4415   // low part, it must be shifted left.
4416   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4417   if (InputByteNo < ByteValues.size()/2) {
4418     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419       return true;
4420   } else {
4421     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4422       return true;
4423   }
4424   
4425   // If the destination byte value is already defined, the values are or'd
4426   // together, which isn't a bswap (unless it's an or of the same bits).
4427   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4428     return true;
4429   ByteValues[DestByteNo] = V;
4430   return false;
4431 }
4432
4433 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4434 /// If so, insert the new bswap intrinsic and return it.
4435 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4436   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4437   if (!ITy || ITy->getBitWidth() % 16 || 
4438       // ByteMask only allows up to 32-byte values.
4439       ITy->getBitWidth() > 32*8) 
4440     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4441   
4442   /// ByteValues - For each byte of the result, we keep track of which value
4443   /// defines each byte.
4444   SmallVector<Value*, 8> ByteValues;
4445   ByteValues.resize(ITy->getBitWidth()/8);
4446     
4447   // Try to find all the pieces corresponding to the bswap.
4448   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4449   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4450     return 0;
4451   
4452   // Check to see if all of the bytes come from the same value.
4453   Value *V = ByteValues[0];
4454   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4455   
4456   // Check to make sure that all of the bytes come from the same value.
4457   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4458     if (ByteValues[i] != V)
4459       return 0;
4460   const Type *Tys[] = { ITy };
4461   Module *M = I.getParent()->getParent()->getParent();
4462   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4463   return CallInst::Create(F, V);
4464 }
4465
4466 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4467 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4468 /// we can simplify this expression to "cond ? C : D or B".
4469 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4470                                          Value *C, Value *D,
4471                                          LLVMContext *Context) {
4472   // If A is not a select of -1/0, this cannot match.
4473   Value *Cond = 0;
4474   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4475     return 0;
4476
4477   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4478   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4479     return SelectInst::Create(Cond, C, B);
4480   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4481     return SelectInst::Create(Cond, C, B);
4482   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4483   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4484     return SelectInst::Create(Cond, C, D);
4485   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4486     return SelectInst::Create(Cond, C, D);
4487   return 0;
4488 }
4489
4490 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4491 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4492                                          ICmpInst *LHS, ICmpInst *RHS) {
4493   Value *Val, *Val2;
4494   ConstantInt *LHSCst, *RHSCst;
4495   ICmpInst::Predicate LHSCC, RHSCC;
4496   
4497   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4498   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4499              m_ConstantInt(LHSCst)), *Context) ||
4500       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4501              m_ConstantInt(RHSCst)), *Context))
4502     return 0;
4503   
4504   // From here on, we only handle:
4505   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4506   if (Val != Val2) return 0;
4507   
4508   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4509   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4510       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4511       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4512       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4513     return 0;
4514   
4515   // We can't fold (ugt x, C) | (sgt x, C2).
4516   if (!PredicatesFoldable(LHSCC, RHSCC))
4517     return 0;
4518   
4519   // Ensure that the larger constant is on the RHS.
4520   bool ShouldSwap;
4521   if (ICmpInst::isSignedPredicate(LHSCC) ||
4522       (ICmpInst::isEquality(LHSCC) && 
4523        ICmpInst::isSignedPredicate(RHSCC)))
4524     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4525   else
4526     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4527   
4528   if (ShouldSwap) {
4529     std::swap(LHS, RHS);
4530     std::swap(LHSCst, RHSCst);
4531     std::swap(LHSCC, RHSCC);
4532   }
4533   
4534   // At this point, we know we have have two icmp instructions
4535   // comparing a value against two constants and or'ing the result
4536   // together.  Because of the above check, we know that we only have
4537   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4538   // FoldICmpLogical check above), that the two constants are not
4539   // equal.
4540   assert(LHSCst != RHSCst && "Compares not folded above?");
4541
4542   switch (LHSCC) {
4543   default: llvm_unreachable("Unknown integer condition code!");
4544   case ICmpInst::ICMP_EQ:
4545     switch (RHSCC) {
4546     default: llvm_unreachable("Unknown integer condition code!");
4547     case ICmpInst::ICMP_EQ:
4548       if (LHSCst == SubOne(RHSCst, Context)) {
4549         // (X == 13 | X == 14) -> X-13 <u 2
4550         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4551         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4552                                                      Val->getName()+".off");
4553         InsertNewInstBefore(Add, I);
4554         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4555         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4556       }
4557       break;                         // (X == 13 | X == 15) -> no change
4558     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4559     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4560       break;
4561     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4562     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4563     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4564       return ReplaceInstUsesWith(I, RHS);
4565     }
4566     break;
4567   case ICmpInst::ICMP_NE:
4568     switch (RHSCC) {
4569     default: llvm_unreachable("Unknown integer condition code!");
4570     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4571     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4572     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4573       return ReplaceInstUsesWith(I, LHS);
4574     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4575     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4576     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4577       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4578     }
4579     break;
4580   case ICmpInst::ICMP_ULT:
4581     switch (RHSCC) {
4582     default: llvm_unreachable("Unknown integer condition code!");
4583     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4584       break;
4585     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4586       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4587       // this can cause overflow.
4588       if (RHSCst->isMaxValue(false))
4589         return ReplaceInstUsesWith(I, LHS);
4590       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4591                              false, false, I);
4592     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4593       break;
4594     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4595     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4596       return ReplaceInstUsesWith(I, RHS);
4597     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4598       break;
4599     }
4600     break;
4601   case ICmpInst::ICMP_SLT:
4602     switch (RHSCC) {
4603     default: llvm_unreachable("Unknown integer condition code!");
4604     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4605       break;
4606     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4607       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4608       // this can cause overflow.
4609       if (RHSCst->isMaxValue(true))
4610         return ReplaceInstUsesWith(I, LHS);
4611       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4612                              true, false, I);
4613     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4614       break;
4615     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4616     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4617       return ReplaceInstUsesWith(I, RHS);
4618     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4619       break;
4620     }
4621     break;
4622   case ICmpInst::ICMP_UGT:
4623     switch (RHSCC) {
4624     default: llvm_unreachable("Unknown integer condition code!");
4625     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4626     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4627       return ReplaceInstUsesWith(I, LHS);
4628     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4629       break;
4630     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4631     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4632       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4633     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4634       break;
4635     }
4636     break;
4637   case ICmpInst::ICMP_SGT:
4638     switch (RHSCC) {
4639     default: llvm_unreachable("Unknown integer condition code!");
4640     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4641     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4642       return ReplaceInstUsesWith(I, LHS);
4643     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4644       break;
4645     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4646     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4647       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4648     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4649       break;
4650     }
4651     break;
4652   }
4653   return 0;
4654 }
4655
4656 /// FoldOrWithConstants - This helper function folds:
4657 ///
4658 ///     ((A | B) & C1) | (B & C2)
4659 ///
4660 /// into:
4661 /// 
4662 ///     (A & C1) | B
4663 ///
4664 /// when the XOR of the two constants is "all ones" (-1).
4665 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4666                                                Value *A, Value *B, Value *C) {
4667   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4668   if (!CI1) return 0;
4669
4670   Value *V1 = 0;
4671   ConstantInt *CI2 = 0;
4672   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4673
4674   APInt Xor = CI1->getValue() ^ CI2->getValue();
4675   if (!Xor.isAllOnesValue()) return 0;
4676
4677   if (V1 == A || V1 == B) {
4678     Instruction *NewOp =
4679       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4680     return BinaryOperator::CreateOr(NewOp, V1);
4681   }
4682
4683   return 0;
4684 }
4685
4686 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4687   bool Changed = SimplifyCommutative(I);
4688   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4689
4690   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4691     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4692
4693   // or X, X = X
4694   if (Op0 == Op1)
4695     return ReplaceInstUsesWith(I, Op0);
4696
4697   // See if we can simplify any instructions used by the instruction whose sole 
4698   // purpose is to compute bits we don't care about.
4699   if (SimplifyDemandedInstructionBits(I))
4700     return &I;
4701   if (isa<VectorType>(I.getType())) {
4702     if (isa<ConstantAggregateZero>(Op1)) {
4703       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4704     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4705       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4706         return ReplaceInstUsesWith(I, I.getOperand(1));
4707     }
4708   }
4709
4710   // or X, -1 == -1
4711   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4712     ConstantInt *C1 = 0; Value *X = 0;
4713     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4714     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4715         isOnlyUse(Op0)) {
4716       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4717       InsertNewInstBefore(Or, I);
4718       Or->takeName(Op0);
4719       return BinaryOperator::CreateAnd(Or, 
4720                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4721     }
4722
4723     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4724     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4725         isOnlyUse(Op0)) {
4726       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4727       InsertNewInstBefore(Or, I);
4728       Or->takeName(Op0);
4729       return BinaryOperator::CreateXor(Or,
4730                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4731     }
4732
4733     // Try to fold constant and into select arguments.
4734     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4735       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4736         return R;
4737     if (isa<PHINode>(Op0))
4738       if (Instruction *NV = FoldOpIntoPhi(I))
4739         return NV;
4740   }
4741
4742   Value *A = 0, *B = 0;
4743   ConstantInt *C1 = 0, *C2 = 0;
4744
4745   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4746     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4747       return ReplaceInstUsesWith(I, Op1);
4748   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4749     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4750       return ReplaceInstUsesWith(I, Op0);
4751
4752   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4753   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4754   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4755       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4756       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4757        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4758     if (Instruction *BSwap = MatchBSwap(I))
4759       return BSwap;
4760   }
4761   
4762   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4763   if (Op0->hasOneUse() &&
4764       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4765       MaskedValueIsZero(Op1, C1->getValue())) {
4766     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4767     InsertNewInstBefore(NOr, I);
4768     NOr->takeName(Op0);
4769     return BinaryOperator::CreateXor(NOr, C1);
4770   }
4771
4772   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4773   if (Op1->hasOneUse() &&
4774       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4775       MaskedValueIsZero(Op0, C1->getValue())) {
4776     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4777     InsertNewInstBefore(NOr, I);
4778     NOr->takeName(Op0);
4779     return BinaryOperator::CreateXor(NOr, C1);
4780   }
4781
4782   // (A & C)|(B & D)
4783   Value *C = 0, *D = 0;
4784   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4785       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4786     Value *V1 = 0, *V2 = 0, *V3 = 0;
4787     C1 = dyn_cast<ConstantInt>(C);
4788     C2 = dyn_cast<ConstantInt>(D);
4789     if (C1 && C2) {  // (A & C1)|(B & C2)
4790       // If we have: ((V + N) & C1) | (V & C2)
4791       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4792       // replace with V+N.
4793       if (C1->getValue() == ~C2->getValue()) {
4794         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4795             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4796           // Add commutes, try both ways.
4797           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4798             return ReplaceInstUsesWith(I, A);
4799           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4800             return ReplaceInstUsesWith(I, A);
4801         }
4802         // Or commutes, try both ways.
4803         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4804             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4805           // Add commutes, try both ways.
4806           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4807             return ReplaceInstUsesWith(I, B);
4808           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4809             return ReplaceInstUsesWith(I, B);
4810         }
4811       }
4812       V1 = 0; V2 = 0; V3 = 0;
4813     }
4814     
4815     // Check to see if we have any common things being and'ed.  If so, find the
4816     // terms for V1 & (V2|V3).
4817     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4818       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4819         V1 = A, V2 = C, V3 = D;
4820       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4821         V1 = A, V2 = B, V3 = C;
4822       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4823         V1 = C, V2 = A, V3 = D;
4824       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4825         V1 = C, V2 = A, V3 = B;
4826       
4827       if (V1) {
4828         Value *Or =
4829           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4830         return BinaryOperator::CreateAnd(V1, Or);
4831       }
4832     }
4833
4834     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4835     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4836       return Match;
4837     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4838       return Match;
4839     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4840       return Match;
4841     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4842       return Match;
4843
4844     // ((A&~B)|(~A&B)) -> A^B
4845     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4846          match(B, m_Not(m_Specific(A)), *Context)))
4847       return BinaryOperator::CreateXor(A, D);
4848     // ((~B&A)|(~A&B)) -> A^B
4849     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4850          match(B, m_Not(m_Specific(C)), *Context)))
4851       return BinaryOperator::CreateXor(C, D);
4852     // ((A&~B)|(B&~A)) -> A^B
4853     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4854          match(D, m_Not(m_Specific(A)), *Context)))
4855       return BinaryOperator::CreateXor(A, B);
4856     // ((~B&A)|(B&~A)) -> A^B
4857     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4858          match(D, m_Not(m_Specific(C)), *Context)))
4859       return BinaryOperator::CreateXor(C, B);
4860   }
4861   
4862   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4863   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4864     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4865       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4866           SI0->getOperand(1) == SI1->getOperand(1) &&
4867           (SI0->hasOneUse() || SI1->hasOneUse())) {
4868         Instruction *NewOp =
4869         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4870                                                      SI1->getOperand(0),
4871                                                      SI0->getName()), I);
4872         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4873                                       SI1->getOperand(1));
4874       }
4875   }
4876
4877   // ((A|B)&1)|(B&-2) -> (A&1) | B
4878   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4879       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4880     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4881     if (Ret) return Ret;
4882   }
4883   // (B&-2)|((A|B)&1) -> (A&1) | B
4884   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4885       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4886     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4887     if (Ret) return Ret;
4888   }
4889
4890   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4891     if (A == Op1)   // ~A | A == -1
4892       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4893   } else {
4894     A = 0;
4895   }
4896   // Note, A is still live here!
4897   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4898     if (Op0 == B)
4899       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4900
4901     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4902     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4903       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4904                                               I.getName()+".demorgan"), I);
4905       return BinaryOperator::CreateNot(*Context, And);
4906     }
4907   }
4908
4909   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4910   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4911     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4912       return R;
4913
4914     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4915       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4916         return Res;
4917   }
4918     
4919   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4920   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4921     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4922       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4923         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4924             !isa<ICmpInst>(Op1C->getOperand(0))) {
4925           const Type *SrcTy = Op0C->getOperand(0)->getType();
4926           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4927               // Only do this if the casts both really cause code to be
4928               // generated.
4929               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4930                                 I.getType(), TD) &&
4931               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4932                                 I.getType(), TD)) {
4933             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4934                                                           Op1C->getOperand(0),
4935                                                           I.getName());
4936             InsertNewInstBefore(NewOp, I);
4937             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4938           }
4939         }
4940       }
4941   }
4942   
4943     
4944   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4945   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4946     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4947       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4948           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4949           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4950         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4951           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4952             // If either of the constants are nans, then the whole thing returns
4953             // true.
4954             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4955               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4956             
4957             // Otherwise, no need to compare the two constants, compare the
4958             // rest.
4959             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4960                                 LHS->getOperand(0), RHS->getOperand(0));
4961           }
4962       } else {
4963         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4964         FCmpInst::Predicate Op0CC, Op1CC;
4965         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4966                   m_Value(Op0RHS)), *Context) &&
4967             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4968                   m_Value(Op1RHS)), *Context)) {
4969           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4970             // Swap RHS operands to match LHS.
4971             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4972             std::swap(Op1LHS, Op1RHS);
4973           }
4974           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4975             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4976             if (Op0CC == Op1CC)
4977               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4978                                   Op0LHS, Op0RHS);
4979             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4980                      Op1CC == FCmpInst::FCMP_TRUE)
4981               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4982             else if (Op0CC == FCmpInst::FCMP_FALSE)
4983               return ReplaceInstUsesWith(I, Op1);
4984             else if (Op1CC == FCmpInst::FCMP_FALSE)
4985               return ReplaceInstUsesWith(I, Op0);
4986             bool Op0Ordered;
4987             bool Op1Ordered;
4988             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4989             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4990             if (Op0Ordered == Op1Ordered) {
4991               // If both are ordered or unordered, return a new fcmp with
4992               // or'ed predicates.
4993               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4994                                        Op0LHS, Op0RHS, Context);
4995               if (Instruction *I = dyn_cast<Instruction>(RV))
4996                 return I;
4997               // Otherwise, it's a constant boolean value...
4998               return ReplaceInstUsesWith(I, RV);
4999             }
5000           }
5001         }
5002       }
5003     }
5004   }
5005
5006   return Changed ? &I : 0;
5007 }
5008
5009 namespace {
5010
5011 // XorSelf - Implements: X ^ X --> 0
5012 struct XorSelf {
5013   Value *RHS;
5014   XorSelf(Value *rhs) : RHS(rhs) {}
5015   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5016   Instruction *apply(BinaryOperator &Xor) const {
5017     return &Xor;
5018   }
5019 };
5020
5021 }
5022
5023 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5024   bool Changed = SimplifyCommutative(I);
5025   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5026
5027   if (isa<UndefValue>(Op1)) {
5028     if (isa<UndefValue>(Op0))
5029       // Handle undef ^ undef -> 0 special case. This is a common
5030       // idiom (misuse).
5031       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5032     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5033   }
5034
5035   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5036   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5037     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5038     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5039   }
5040   
5041   // See if we can simplify any instructions used by the instruction whose sole 
5042   // purpose is to compute bits we don't care about.
5043   if (SimplifyDemandedInstructionBits(I))
5044     return &I;
5045   if (isa<VectorType>(I.getType()))
5046     if (isa<ConstantAggregateZero>(Op1))
5047       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5048
5049   // Is this a ~ operation?
5050   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5051     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5052     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5053     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5054       if (Op0I->getOpcode() == Instruction::And || 
5055           Op0I->getOpcode() == Instruction::Or) {
5056         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5057         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5058           Instruction *NotY =
5059             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5060                                       Op0I->getOperand(1)->getName()+".not");
5061           InsertNewInstBefore(NotY, I);
5062           if (Op0I->getOpcode() == Instruction::And)
5063             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5064           else
5065             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5066         }
5067       }
5068     }
5069   }
5070   
5071   
5072   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5073     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5074       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5075       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5076         return new ICmpInst(*Context, ICI->getInversePredicate(),
5077                             ICI->getOperand(0), ICI->getOperand(1));
5078
5079       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5080         return new FCmpInst(*Context, FCI->getInversePredicate(),
5081                             FCI->getOperand(0), FCI->getOperand(1));
5082     }
5083
5084     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5085     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5086       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5087         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5088           Instruction::CastOps Opcode = Op0C->getOpcode();
5089           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5090             if (RHS == Context->getConstantExprCast(Opcode, 
5091                                              Context->getConstantIntTrue(),
5092                                              Op0C->getDestTy())) {
5093               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5094                                      *Context,
5095                                      CI->getOpcode(), CI->getInversePredicate(),
5096                                      CI->getOperand(0), CI->getOperand(1)), I);
5097               NewCI->takeName(CI);
5098               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5099             }
5100           }
5101         }
5102       }
5103     }
5104
5105     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5106       // ~(c-X) == X-c-1 == X+(-c-1)
5107       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5108         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5109           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5110           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5111                                       Context->getConstantInt(I.getType(), 1));
5112           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5113         }
5114           
5115       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5116         if (Op0I->getOpcode() == Instruction::Add) {
5117           // ~(X-c) --> (-c-1)-X
5118           if (RHS->isAllOnesValue()) {
5119             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5120             return BinaryOperator::CreateSub(
5121                            Context->getConstantExprSub(NegOp0CI,
5122                                       Context->getConstantInt(I.getType(), 1)),
5123                                       Op0I->getOperand(0));
5124           } else if (RHS->getValue().isSignBit()) {
5125             // (X + C) ^ signbit -> (X + C + signbit)
5126             Constant *C =
5127                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5128             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5129
5130           }
5131         } else if (Op0I->getOpcode() == Instruction::Or) {
5132           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5133           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5134             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5135             // Anything in both C1 and C2 is known to be zero, remove it from
5136             // NewRHS.
5137             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5138             NewRHS = Context->getConstantExprAnd(NewRHS, 
5139                                        Context->getConstantExprNot(CommonBits));
5140             AddToWorkList(Op0I);
5141             I.setOperand(0, Op0I->getOperand(0));
5142             I.setOperand(1, NewRHS);
5143             return &I;
5144           }
5145         }
5146       }
5147     }
5148
5149     // Try to fold constant and into select arguments.
5150     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5151       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5152         return R;
5153     if (isa<PHINode>(Op0))
5154       if (Instruction *NV = FoldOpIntoPhi(I))
5155         return NV;
5156   }
5157
5158   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5159     if (X == Op1)
5160       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5161
5162   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5163     if (X == Op0)
5164       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5165
5166   
5167   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5168   if (Op1I) {
5169     Value *A, *B;
5170     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5171       if (A == Op0) {              // B^(B|A) == (A|B)^B
5172         Op1I->swapOperands();
5173         I.swapOperands();
5174         std::swap(Op0, Op1);
5175       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5176         I.swapOperands();     // Simplified below.
5177         std::swap(Op0, Op1);
5178       }
5179     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5180       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5181     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5182       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5183     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5184                Op1I->hasOneUse()){
5185       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5186         Op1I->swapOperands();
5187         std::swap(A, B);
5188       }
5189       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5190         I.swapOperands();     // Simplified below.
5191         std::swap(Op0, Op1);
5192       }
5193     }
5194   }
5195   
5196   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5197   if (Op0I) {
5198     Value *A, *B;
5199     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5200         Op0I->hasOneUse()) {
5201       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5202         std::swap(A, B);
5203       if (B == Op1) {                                // (A|B)^B == A & ~B
5204         Instruction *NotB =
5205           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5206                                                         Op1, "tmp"), I);
5207         return BinaryOperator::CreateAnd(A, NotB);
5208       }
5209     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5210       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5211     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5212       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5213     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5214                Op0I->hasOneUse()){
5215       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5216         std::swap(A, B);
5217       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5218           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5219         Instruction *N =
5220           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5221         return BinaryOperator::CreateAnd(N, Op1);
5222       }
5223     }
5224   }
5225   
5226   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5227   if (Op0I && Op1I && Op0I->isShift() && 
5228       Op0I->getOpcode() == Op1I->getOpcode() && 
5229       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5230       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5231     Instruction *NewOp =
5232       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5233                                                     Op1I->getOperand(0),
5234                                                     Op0I->getName()), I);
5235     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5236                                   Op1I->getOperand(1));
5237   }
5238     
5239   if (Op0I && Op1I) {
5240     Value *A, *B, *C, *D;
5241     // (A & B)^(A | B) -> A ^ B
5242     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5243         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5244       if ((A == C && B == D) || (A == D && B == C)) 
5245         return BinaryOperator::CreateXor(A, B);
5246     }
5247     // (A | B)^(A & B) -> A ^ B
5248     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5249         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5250       if ((A == C && B == D) || (A == D && B == C)) 
5251         return BinaryOperator::CreateXor(A, B);
5252     }
5253     
5254     // (A & B)^(C & D)
5255     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5256         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5257         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5258       // (X & Y)^(X & Y) -> (Y^Z) & X
5259       Value *X = 0, *Y = 0, *Z = 0;
5260       if (A == C)
5261         X = A, Y = B, Z = D;
5262       else if (A == D)
5263         X = A, Y = B, Z = C;
5264       else if (B == C)
5265         X = B, Y = A, Z = D;
5266       else if (B == D)
5267         X = B, Y = A, Z = C;
5268       
5269       if (X) {
5270         Instruction *NewOp =
5271         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5272         return BinaryOperator::CreateAnd(NewOp, X);
5273       }
5274     }
5275   }
5276     
5277   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5278   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5279     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5280       return R;
5281
5282   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5283   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5284     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5285       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5286         const Type *SrcTy = Op0C->getOperand(0)->getType();
5287         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5288             // Only do this if the casts both really cause code to be generated.
5289             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5290                               I.getType(), TD) &&
5291             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5292                               I.getType(), TD)) {
5293           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5294                                                          Op1C->getOperand(0),
5295                                                          I.getName());
5296           InsertNewInstBefore(NewOp, I);
5297           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5298         }
5299       }
5300   }
5301
5302   return Changed ? &I : 0;
5303 }
5304
5305 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5306                                    LLVMContext *Context) {
5307   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5308 }
5309
5310 static bool HasAddOverflow(ConstantInt *Result,
5311                            ConstantInt *In1, ConstantInt *In2,
5312                            bool IsSigned) {
5313   if (IsSigned)
5314     if (In2->getValue().isNegative())
5315       return Result->getValue().sgt(In1->getValue());
5316     else
5317       return Result->getValue().slt(In1->getValue());
5318   else
5319     return Result->getValue().ult(In1->getValue());
5320 }
5321
5322 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5323 /// overflowed for this type.
5324 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5325                             Constant *In2, LLVMContext *Context,
5326                             bool IsSigned = false) {
5327   Result = Context->getConstantExprAdd(In1, In2);
5328
5329   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5330     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5331       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5332       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5333                          ExtractElement(In1, Idx, Context),
5334                          ExtractElement(In2, Idx, Context),
5335                          IsSigned))
5336         return true;
5337     }
5338     return false;
5339   }
5340
5341   return HasAddOverflow(cast<ConstantInt>(Result),
5342                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5343                         IsSigned);
5344 }
5345
5346 static bool HasSubOverflow(ConstantInt *Result,
5347                            ConstantInt *In1, ConstantInt *In2,
5348                            bool IsSigned) {
5349   if (IsSigned)
5350     if (In2->getValue().isNegative())
5351       return Result->getValue().slt(In1->getValue());
5352     else
5353       return Result->getValue().sgt(In1->getValue());
5354   else
5355     return Result->getValue().ugt(In1->getValue());
5356 }
5357
5358 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5359 /// overflowed for this type.
5360 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5361                             Constant *In2, LLVMContext *Context,
5362                             bool IsSigned = false) {
5363   Result = Context->getConstantExprSub(In1, In2);
5364
5365   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5366     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5367       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5368       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5369                          ExtractElement(In1, Idx, Context),
5370                          ExtractElement(In2, Idx, Context),
5371                          IsSigned))
5372         return true;
5373     }
5374     return false;
5375   }
5376
5377   return HasSubOverflow(cast<ConstantInt>(Result),
5378                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5379                         IsSigned);
5380 }
5381
5382 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5383 /// code necessary to compute the offset from the base pointer (without adding
5384 /// in the base pointer).  Return the result as a signed integer of intptr size.
5385 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5386   TargetData &TD = IC.getTargetData();
5387   gep_type_iterator GTI = gep_type_begin(GEP);
5388   const Type *IntPtrTy = TD.getIntPtrType();
5389   LLVMContext *Context = IC.getContext();
5390   Value *Result = Context->getNullValue(IntPtrTy);
5391
5392   // Build a mask for high order bits.
5393   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5394   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5395
5396   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5397        ++i, ++GTI) {
5398     Value *Op = *i;
5399     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5400     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5401       if (OpC->isZero()) continue;
5402       
5403       // Handle a struct index, which adds its field offset to the pointer.
5404       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5405         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5406         
5407         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5408           Result = 
5409              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5410         else
5411           Result = IC.InsertNewInstBefore(
5412                    BinaryOperator::CreateAdd(Result,
5413                                         Context->getConstantInt(IntPtrTy, Size),
5414                                              GEP->getName()+".offs"), I);
5415         continue;
5416       }
5417       
5418       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5419       Constant *OC =
5420               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5421       Scale = Context->getConstantExprMul(OC, Scale);
5422       if (Constant *RC = dyn_cast<Constant>(Result))
5423         Result = Context->getConstantExprAdd(RC, Scale);
5424       else {
5425         // Emit an add instruction.
5426         Result = IC.InsertNewInstBefore(
5427            BinaryOperator::CreateAdd(Result, Scale,
5428                                      GEP->getName()+".offs"), I);
5429       }
5430       continue;
5431     }
5432     // Convert to correct type.
5433     if (Op->getType() != IntPtrTy) {
5434       if (Constant *OpC = dyn_cast<Constant>(Op))
5435         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5436       else
5437         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5438                                                                 true,
5439                                                       Op->getName()+".c"), I);
5440     }
5441     if (Size != 1) {
5442       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5443       if (Constant *OpC = dyn_cast<Constant>(Op))
5444         Op = Context->getConstantExprMul(OpC, Scale);
5445       else    // We'll let instcombine(mul) convert this to a shl if possible.
5446         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5447                                                   GEP->getName()+".idx"), I);
5448     }
5449
5450     // Emit an add instruction.
5451     if (isa<Constant>(Op) && isa<Constant>(Result))
5452       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5453                                     cast<Constant>(Result));
5454     else
5455       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5456                                                   GEP->getName()+".offs"), I);
5457   }
5458   return Result;
5459 }
5460
5461
5462 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5463 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5464 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5465 /// be complex, and scales are involved.  The above expression would also be
5466 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5467 /// This later form is less amenable to optimization though, and we are allowed
5468 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5469 ///
5470 /// If we can't emit an optimized form for this expression, this returns null.
5471 /// 
5472 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5473                                           InstCombiner &IC) {
5474   TargetData &TD = IC.getTargetData();
5475   gep_type_iterator GTI = gep_type_begin(GEP);
5476
5477   // Check to see if this gep only has a single variable index.  If so, and if
5478   // any constant indices are a multiple of its scale, then we can compute this
5479   // in terms of the scale of the variable index.  For example, if the GEP
5480   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5481   // because the expression will cross zero at the same point.
5482   unsigned i, e = GEP->getNumOperands();
5483   int64_t Offset = 0;
5484   for (i = 1; i != e; ++i, ++GTI) {
5485     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5486       // Compute the aggregate offset of constant indices.
5487       if (CI->isZero()) continue;
5488
5489       // Handle a struct index, which adds its field offset to the pointer.
5490       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5491         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5492       } else {
5493         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5494         Offset += Size*CI->getSExtValue();
5495       }
5496     } else {
5497       // Found our variable index.
5498       break;
5499     }
5500   }
5501   
5502   // If there are no variable indices, we must have a constant offset, just
5503   // evaluate it the general way.
5504   if (i == e) return 0;
5505   
5506   Value *VariableIdx = GEP->getOperand(i);
5507   // Determine the scale factor of the variable element.  For example, this is
5508   // 4 if the variable index is into an array of i32.
5509   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5510   
5511   // Verify that there are no other variable indices.  If so, emit the hard way.
5512   for (++i, ++GTI; i != e; ++i, ++GTI) {
5513     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5514     if (!CI) return 0;
5515    
5516     // Compute the aggregate offset of constant indices.
5517     if (CI->isZero()) continue;
5518     
5519     // Handle a struct index, which adds its field offset to the pointer.
5520     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5521       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5522     } else {
5523       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5524       Offset += Size*CI->getSExtValue();
5525     }
5526   }
5527   
5528   // Okay, we know we have a single variable index, which must be a
5529   // pointer/array/vector index.  If there is no offset, life is simple, return
5530   // the index.
5531   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5532   if (Offset == 0) {
5533     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5534     // we don't need to bother extending: the extension won't affect where the
5535     // computation crosses zero.
5536     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5537       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5538                                   VariableIdx->getNameStart(), &I);
5539     return VariableIdx;
5540   }
5541   
5542   // Otherwise, there is an index.  The computation we will do will be modulo
5543   // the pointer size, so get it.
5544   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5545   
5546   Offset &= PtrSizeMask;
5547   VariableScale &= PtrSizeMask;
5548
5549   // To do this transformation, any constant index must be a multiple of the
5550   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5551   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5552   // multiple of the variable scale.
5553   int64_t NewOffs = Offset / (int64_t)VariableScale;
5554   if (Offset != NewOffs*(int64_t)VariableScale)
5555     return 0;
5556
5557   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5558   const Type *IntPtrTy = TD.getIntPtrType();
5559   if (VariableIdx->getType() != IntPtrTy)
5560     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5561                                               true /*SExt*/, 
5562                                               VariableIdx->getNameStart(), &I);
5563   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5564   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5565 }
5566
5567
5568 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5569 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5570 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5571                                        ICmpInst::Predicate Cond,
5572                                        Instruction &I) {
5573   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5574
5575   // Look through bitcasts.
5576   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5577     RHS = BCI->getOperand(0);
5578
5579   Value *PtrBase = GEPLHS->getOperand(0);
5580   if (PtrBase == RHS) {
5581     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5582     // This transformation (ignoring the base and scales) is valid because we
5583     // know pointers can't overflow.  See if we can output an optimized form.
5584     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5585     
5586     // If not, synthesize the offset the hard way.
5587     if (Offset == 0)
5588       Offset = EmitGEPOffset(GEPLHS, I, *this);
5589     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5590                         Context->getNullValue(Offset->getType()));
5591   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5592     // If the base pointers are different, but the indices are the same, just
5593     // compare the base pointer.
5594     if (PtrBase != GEPRHS->getOperand(0)) {
5595       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5596       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5597                         GEPRHS->getOperand(0)->getType();
5598       if (IndicesTheSame)
5599         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5600           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5601             IndicesTheSame = false;
5602             break;
5603           }
5604
5605       // If all indices are the same, just compare the base pointers.
5606       if (IndicesTheSame)
5607         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5608                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5609
5610       // Otherwise, the base pointers are different and the indices are
5611       // different, bail out.
5612       return 0;
5613     }
5614
5615     // If one of the GEPs has all zero indices, recurse.
5616     bool AllZeros = true;
5617     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5618       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5619           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5620         AllZeros = false;
5621         break;
5622       }
5623     if (AllZeros)
5624       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5625                           ICmpInst::getSwappedPredicate(Cond), I);
5626
5627     // If the other GEP has all zero indices, recurse.
5628     AllZeros = true;
5629     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5630       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5631           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5632         AllZeros = false;
5633         break;
5634       }
5635     if (AllZeros)
5636       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5637
5638     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5639       // If the GEPs only differ by one index, compare it.
5640       unsigned NumDifferences = 0;  // Keep track of # differences.
5641       unsigned DiffOperand = 0;     // The operand that differs.
5642       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5643         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5644           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5645                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5646             // Irreconcilable differences.
5647             NumDifferences = 2;
5648             break;
5649           } else {
5650             if (NumDifferences++) break;
5651             DiffOperand = i;
5652           }
5653         }
5654
5655       if (NumDifferences == 0)   // SAME GEP?
5656         return ReplaceInstUsesWith(I, // No comparison is needed here.
5657                                    Context->getConstantInt(Type::Int1Ty,
5658                                              ICmpInst::isTrueWhenEqual(Cond)));
5659
5660       else if (NumDifferences == 1) {
5661         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5662         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5663         // Make sure we do a signed comparison here.
5664         return new ICmpInst(*Context,
5665                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5666       }
5667     }
5668
5669     // Only lower this if the icmp is the only user of the GEP or if we expect
5670     // the result to fold to a constant!
5671     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5672         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5673       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5674       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5675       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5676       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5677     }
5678   }
5679   return 0;
5680 }
5681
5682 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5683 ///
5684 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5685                                                 Instruction *LHSI,
5686                                                 Constant *RHSC) {
5687   if (!isa<ConstantFP>(RHSC)) return 0;
5688   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5689   
5690   // Get the width of the mantissa.  We don't want to hack on conversions that
5691   // might lose information from the integer, e.g. "i64 -> float"
5692   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5693   if (MantissaWidth == -1) return 0;  // Unknown.
5694   
5695   // Check to see that the input is converted from an integer type that is small
5696   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5697   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5698   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5699   
5700   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5701   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5702   if (LHSUnsigned)
5703     ++InputSize;
5704   
5705   // If the conversion would lose info, don't hack on this.
5706   if ((int)InputSize > MantissaWidth)
5707     return 0;
5708   
5709   // Otherwise, we can potentially simplify the comparison.  We know that it
5710   // will always come through as an integer value and we know the constant is
5711   // not a NAN (it would have been previously simplified).
5712   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5713   
5714   ICmpInst::Predicate Pred;
5715   switch (I.getPredicate()) {
5716   default: llvm_unreachable("Unexpected predicate!");
5717   case FCmpInst::FCMP_UEQ:
5718   case FCmpInst::FCMP_OEQ:
5719     Pred = ICmpInst::ICMP_EQ;
5720     break;
5721   case FCmpInst::FCMP_UGT:
5722   case FCmpInst::FCMP_OGT:
5723     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5724     break;
5725   case FCmpInst::FCMP_UGE:
5726   case FCmpInst::FCMP_OGE:
5727     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5728     break;
5729   case FCmpInst::FCMP_ULT:
5730   case FCmpInst::FCMP_OLT:
5731     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5732     break;
5733   case FCmpInst::FCMP_ULE:
5734   case FCmpInst::FCMP_OLE:
5735     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5736     break;
5737   case FCmpInst::FCMP_UNE:
5738   case FCmpInst::FCMP_ONE:
5739     Pred = ICmpInst::ICMP_NE;
5740     break;
5741   case FCmpInst::FCMP_ORD:
5742     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5743   case FCmpInst::FCMP_UNO:
5744     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5745   }
5746   
5747   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5748   
5749   // Now we know that the APFloat is a normal number, zero or inf.
5750   
5751   // See if the FP constant is too large for the integer.  For example,
5752   // comparing an i8 to 300.0.
5753   unsigned IntWidth = IntTy->getScalarSizeInBits();
5754   
5755   if (!LHSUnsigned) {
5756     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5757     // and large values.
5758     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5759     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5760                           APFloat::rmNearestTiesToEven);
5761     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5762       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5763           Pred == ICmpInst::ICMP_SLE)
5764         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5765       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5766     }
5767   } else {
5768     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5769     // +INF and large values.
5770     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5771     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5772                           APFloat::rmNearestTiesToEven);
5773     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5774       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5775           Pred == ICmpInst::ICMP_ULE)
5776         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5777       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5778     }
5779   }
5780   
5781   if (!LHSUnsigned) {
5782     // See if the RHS value is < SignedMin.
5783     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5784     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5785                           APFloat::rmNearestTiesToEven);
5786     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5787       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5788           Pred == ICmpInst::ICMP_SGE)
5789         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5790       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5791     }
5792   }
5793
5794   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5795   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5796   // casting the FP value to the integer value and back, checking for equality.
5797   // Don't do this for zero, because -0.0 is not fractional.
5798   Constant *RHSInt = LHSUnsigned
5799     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5800     : Context->getConstantExprFPToSI(RHSC, IntTy);
5801   if (!RHS.isZero()) {
5802     bool Equal = LHSUnsigned
5803       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5804       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5805     if (!Equal) {
5806       // If we had a comparison against a fractional value, we have to adjust
5807       // the compare predicate and sometimes the value.  RHSC is rounded towards
5808       // zero at this point.
5809       switch (Pred) {
5810       default: llvm_unreachable("Unexpected integer comparison!");
5811       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5812         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5813       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5814         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5815       case ICmpInst::ICMP_ULE:
5816         // (float)int <= 4.4   --> int <= 4
5817         // (float)int <= -4.4  --> false
5818         if (RHS.isNegative())
5819           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5820         break;
5821       case ICmpInst::ICMP_SLE:
5822         // (float)int <= 4.4   --> int <= 4
5823         // (float)int <= -4.4  --> int < -4
5824         if (RHS.isNegative())
5825           Pred = ICmpInst::ICMP_SLT;
5826         break;
5827       case ICmpInst::ICMP_ULT:
5828         // (float)int < -4.4   --> false
5829         // (float)int < 4.4    --> int <= 4
5830         if (RHS.isNegative())
5831           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5832         Pred = ICmpInst::ICMP_ULE;
5833         break;
5834       case ICmpInst::ICMP_SLT:
5835         // (float)int < -4.4   --> int < -4
5836         // (float)int < 4.4    --> int <= 4
5837         if (!RHS.isNegative())
5838           Pred = ICmpInst::ICMP_SLE;
5839         break;
5840       case ICmpInst::ICMP_UGT:
5841         // (float)int > 4.4    --> int > 4
5842         // (float)int > -4.4   --> true
5843         if (RHS.isNegative())
5844           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5845         break;
5846       case ICmpInst::ICMP_SGT:
5847         // (float)int > 4.4    --> int > 4
5848         // (float)int > -4.4   --> int >= -4
5849         if (RHS.isNegative())
5850           Pred = ICmpInst::ICMP_SGE;
5851         break;
5852       case ICmpInst::ICMP_UGE:
5853         // (float)int >= -4.4   --> true
5854         // (float)int >= 4.4    --> int > 4
5855         if (!RHS.isNegative())
5856           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5857         Pred = ICmpInst::ICMP_UGT;
5858         break;
5859       case ICmpInst::ICMP_SGE:
5860         // (float)int >= -4.4   --> int >= -4
5861         // (float)int >= 4.4    --> int > 4
5862         if (!RHS.isNegative())
5863           Pred = ICmpInst::ICMP_SGT;
5864         break;
5865       }
5866     }
5867   }
5868
5869   // Lower this FP comparison into an appropriate integer version of the
5870   // comparison.
5871   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5872 }
5873
5874 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5875   bool Changed = SimplifyCompare(I);
5876   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5877
5878   // Fold trivial predicates.
5879   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5880     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5881   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5882     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5883   
5884   // Simplify 'fcmp pred X, X'
5885   if (Op0 == Op1) {
5886     switch (I.getPredicate()) {
5887     default: llvm_unreachable("Unknown predicate!");
5888     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5889     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5890     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5891       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5892     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5893     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5894     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5895       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5896       
5897     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5898     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5899     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5900     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5901       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5902       I.setPredicate(FCmpInst::FCMP_UNO);
5903       I.setOperand(1, Context->getNullValue(Op0->getType()));
5904       return &I;
5905       
5906     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5907     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5908     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5909     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5910       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5911       I.setPredicate(FCmpInst::FCMP_ORD);
5912       I.setOperand(1, Context->getNullValue(Op0->getType()));
5913       return &I;
5914     }
5915   }
5916     
5917   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5918     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5919
5920   // Handle fcmp with constant RHS
5921   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5922     // If the constant is a nan, see if we can fold the comparison based on it.
5923     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5924       if (CFP->getValueAPF().isNaN()) {
5925         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5926           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5927         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5928                "Comparison must be either ordered or unordered!");
5929         // True if unordered.
5930         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5931       }
5932     }
5933     
5934     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5935       switch (LHSI->getOpcode()) {
5936       case Instruction::PHI:
5937         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5938         // block.  If in the same block, we're encouraging jump threading.  If
5939         // not, we are just pessimizing the code by making an i1 phi.
5940         if (LHSI->getParent() == I.getParent())
5941           if (Instruction *NV = FoldOpIntoPhi(I))
5942             return NV;
5943         break;
5944       case Instruction::SIToFP:
5945       case Instruction::UIToFP:
5946         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5947           return NV;
5948         break;
5949       case Instruction::Select:
5950         // If either operand of the select is a constant, we can fold the
5951         // comparison into the select arms, which will cause one to be
5952         // constant folded and the select turned into a bitwise or.
5953         Value *Op1 = 0, *Op2 = 0;
5954         if (LHSI->hasOneUse()) {
5955           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5956             // Fold the known value into the constant operand.
5957             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5958             // Insert a new FCmp of the other select operand.
5959             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5960                                                       LHSI->getOperand(2), RHSC,
5961                                                       I.getName()), I);
5962           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5963             // Fold the known value into the constant operand.
5964             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5965             // Insert a new FCmp of the other select operand.
5966             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5967                                                       LHSI->getOperand(1), RHSC,
5968                                                       I.getName()), I);
5969           }
5970         }
5971
5972         if (Op1)
5973           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5974         break;
5975       }
5976   }
5977
5978   return Changed ? &I : 0;
5979 }
5980
5981 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5982   bool Changed = SimplifyCompare(I);
5983   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5984   const Type *Ty = Op0->getType();
5985
5986   // icmp X, X
5987   if (Op0 == Op1)
5988     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5989                                                    I.isTrueWhenEqual()));
5990
5991   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5992     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5993   
5994   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5995   // addresses never equal each other!  We already know that Op0 != Op1.
5996   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5997        isa<ConstantPointerNull>(Op0)) &&
5998       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5999        isa<ConstantPointerNull>(Op1)))
6000     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
6001                                                    !I.isTrueWhenEqual()));
6002
6003   // icmp's with boolean values can always be turned into bitwise operations
6004   if (Ty == Type::Int1Ty) {
6005     switch (I.getPredicate()) {
6006     default: llvm_unreachable("Invalid icmp instruction!");
6007     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6008       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6009       InsertNewInstBefore(Xor, I);
6010       return BinaryOperator::CreateNot(*Context, Xor);
6011     }
6012     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6013       return BinaryOperator::CreateXor(Op0, Op1);
6014
6015     case ICmpInst::ICMP_UGT:
6016       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6017       // FALL THROUGH
6018     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6019       Instruction *Not = BinaryOperator::CreateNot(*Context,
6020                                                    Op0, I.getName()+"tmp");
6021       InsertNewInstBefore(Not, I);
6022       return BinaryOperator::CreateAnd(Not, Op1);
6023     }
6024     case ICmpInst::ICMP_SGT:
6025       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6026       // FALL THROUGH
6027     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6028       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6029                                                    Op1, I.getName()+"tmp");
6030       InsertNewInstBefore(Not, I);
6031       return BinaryOperator::CreateAnd(Not, Op0);
6032     }
6033     case ICmpInst::ICMP_UGE:
6034       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6035       // FALL THROUGH
6036     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6037       Instruction *Not = BinaryOperator::CreateNot(*Context,
6038                                                    Op0, I.getName()+"tmp");
6039       InsertNewInstBefore(Not, I);
6040       return BinaryOperator::CreateOr(Not, Op1);
6041     }
6042     case ICmpInst::ICMP_SGE:
6043       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6044       // FALL THROUGH
6045     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6046       Instruction *Not = BinaryOperator::CreateNot(*Context,
6047                                                    Op1, I.getName()+"tmp");
6048       InsertNewInstBefore(Not, I);
6049       return BinaryOperator::CreateOr(Not, Op0);
6050     }
6051     }
6052   }
6053
6054   unsigned BitWidth = 0;
6055   if (TD)
6056     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6057   else if (Ty->isIntOrIntVector())
6058     BitWidth = Ty->getScalarSizeInBits();
6059
6060   bool isSignBit = false;
6061
6062   // See if we are doing a comparison with a constant.
6063   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6064     Value *A = 0, *B = 0;
6065     
6066     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6067     if (I.isEquality() && CI->isNullValue() &&
6068         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6069       // (icmp cond A B) if cond is equality
6070       return new ICmpInst(*Context, I.getPredicate(), A, B);
6071     }
6072     
6073     // If we have an icmp le or icmp ge instruction, turn it into the
6074     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6075     // them being folded in the code below.
6076     switch (I.getPredicate()) {
6077     default: break;
6078     case ICmpInst::ICMP_ULE:
6079       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6080         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6081       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6082                           AddOne(CI, Context));
6083     case ICmpInst::ICMP_SLE:
6084       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6085         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6086       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6087                           AddOne(CI, Context));
6088     case ICmpInst::ICMP_UGE:
6089       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6090         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6091       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6092                           SubOne(CI, Context));
6093     case ICmpInst::ICMP_SGE:
6094       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6095         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6096       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6097                           SubOne(CI, Context));
6098     }
6099     
6100     // If this comparison is a normal comparison, it demands all
6101     // bits, if it is a sign bit comparison, it only demands the sign bit.
6102     bool UnusedBit;
6103     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6104   }
6105
6106   // See if we can fold the comparison based on range information we can get
6107   // by checking whether bits are known to be zero or one in the input.
6108   if (BitWidth != 0) {
6109     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6110     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6111
6112     if (SimplifyDemandedBits(I.getOperandUse(0),
6113                              isSignBit ? APInt::getSignBit(BitWidth)
6114                                        : APInt::getAllOnesValue(BitWidth),
6115                              Op0KnownZero, Op0KnownOne, 0))
6116       return &I;
6117     if (SimplifyDemandedBits(I.getOperandUse(1),
6118                              APInt::getAllOnesValue(BitWidth),
6119                              Op1KnownZero, Op1KnownOne, 0))
6120       return &I;
6121
6122     // Given the known and unknown bits, compute a range that the LHS could be
6123     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6124     // EQ and NE we use unsigned values.
6125     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6126     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6127     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6128       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129                                              Op0Min, Op0Max);
6130       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131                                              Op1Min, Op1Max);
6132     } else {
6133       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6134                                                Op0Min, Op0Max);
6135       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6136                                                Op1Min, Op1Max);
6137     }
6138
6139     // If Min and Max are known to be the same, then SimplifyDemandedBits
6140     // figured out that the LHS is a constant.  Just constant fold this now so
6141     // that code below can assume that Min != Max.
6142     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6143       return new ICmpInst(*Context, I.getPredicate(),
6144                           Context->getConstantInt(Op0Min), Op1);
6145     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6146       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6147                           Context->getConstantInt(Op1Min));
6148
6149     // Based on the range information we know about the LHS, see if we can
6150     // simplify this comparison.  For example, (x&4) < 8  is always true.
6151     switch (I.getPredicate()) {
6152     default: llvm_unreachable("Unknown icmp opcode!");
6153     case ICmpInst::ICMP_EQ:
6154       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6155         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6156       break;
6157     case ICmpInst::ICMP_NE:
6158       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6159         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6160       break;
6161     case ICmpInst::ICMP_ULT:
6162       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6163         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6164       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6165         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6166       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6167         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6168       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6170           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6171                               SubOne(CI, Context));
6172
6173         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6174         if (CI->isMinValue(true))
6175           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6176                            Context->getAllOnesValue(Op0->getType()));
6177       }
6178       break;
6179     case ICmpInst::ICMP_UGT:
6180       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6181         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6182       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6183         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6184
6185       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6186         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6187       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6189           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6190                               AddOne(CI, Context));
6191
6192         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6193         if (CI->isMaxValue(true))
6194           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6195                               Context->getNullValue(Op0->getType()));
6196       }
6197       break;
6198     case ICmpInst::ICMP_SLT:
6199       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6200         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6201       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6202         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6203       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6204         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6205       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6206         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6207           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6208                               SubOne(CI, Context));
6209       }
6210       break;
6211     case ICmpInst::ICMP_SGT:
6212       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6213         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6214       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6215         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6216
6217       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6218         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6219       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6220         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6221           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6222                               AddOne(CI, Context));
6223       }
6224       break;
6225     case ICmpInst::ICMP_SGE:
6226       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6227       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6228         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6229       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6230         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6231       break;
6232     case ICmpInst::ICMP_SLE:
6233       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6234       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6235         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6236       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6237         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6238       break;
6239     case ICmpInst::ICMP_UGE:
6240       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6241       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6242         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6243       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6244         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6245       break;
6246     case ICmpInst::ICMP_ULE:
6247       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6248       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6249         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6250       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6251         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6252       break;
6253     }
6254
6255     // Turn a signed comparison into an unsigned one if both operands
6256     // are known to have the same sign.
6257     if (I.isSignedPredicate() &&
6258         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6259          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6260       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6261   }
6262
6263   // Test if the ICmpInst instruction is used exclusively by a select as
6264   // part of a minimum or maximum operation. If so, refrain from doing
6265   // any other folding. This helps out other analyses which understand
6266   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6267   // and CodeGen. And in this case, at least one of the comparison
6268   // operands has at least one user besides the compare (the select),
6269   // which would often largely negate the benefit of folding anyway.
6270   if (I.hasOneUse())
6271     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6272       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6273           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6274         return 0;
6275
6276   // See if we are doing a comparison between a constant and an instruction that
6277   // can be folded into the comparison.
6278   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6279     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6280     // instruction, see if that instruction also has constants so that the 
6281     // instruction can be folded into the icmp 
6282     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6283       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6284         return Res;
6285   }
6286
6287   // Handle icmp with constant (but not simple integer constant) RHS
6288   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6289     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290       switch (LHSI->getOpcode()) {
6291       case Instruction::GetElementPtr:
6292         if (RHSC->isNullValue()) {
6293           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6294           bool isAllZeros = true;
6295           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6296             if (!isa<Constant>(LHSI->getOperand(i)) ||
6297                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6298               isAllZeros = false;
6299               break;
6300             }
6301           if (isAllZeros)
6302             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6303                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6304         }
6305         break;
6306
6307       case Instruction::PHI:
6308         // Only fold icmp into the PHI if the phi and fcmp are in the same
6309         // block.  If in the same block, we're encouraging jump threading.  If
6310         // not, we are just pessimizing the code by making an i1 phi.
6311         if (LHSI->getParent() == I.getParent())
6312           if (Instruction *NV = FoldOpIntoPhi(I))
6313             return NV;
6314         break;
6315       case Instruction::Select: {
6316         // If either operand of the select is a constant, we can fold the
6317         // comparison into the select arms, which will cause one to be
6318         // constant folded and the select turned into a bitwise or.
6319         Value *Op1 = 0, *Op2 = 0;
6320         if (LHSI->hasOneUse()) {
6321           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6322             // Fold the known value into the constant operand.
6323             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6324             // Insert a new ICmp of the other select operand.
6325             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6326                                                    LHSI->getOperand(2), RHSC,
6327                                                    I.getName()), I);
6328           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329             // Fold the known value into the constant operand.
6330             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6331             // Insert a new ICmp of the other select operand.
6332             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6333                                                    LHSI->getOperand(1), RHSC,
6334                                                    I.getName()), I);
6335           }
6336         }
6337
6338         if (Op1)
6339           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6340         break;
6341       }
6342       case Instruction::Malloc:
6343         // If we have (malloc != null), and if the malloc has a single use, we
6344         // can assume it is successful and remove the malloc.
6345         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6346           AddToWorkList(LHSI);
6347           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6348                                                          !I.isTrueWhenEqual()));
6349         }
6350         break;
6351       }
6352   }
6353
6354   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6355   if (User *GEP = dyn_castGetElementPtr(Op0))
6356     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6357       return NI;
6358   if (User *GEP = dyn_castGetElementPtr(Op1))
6359     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6360                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6361       return NI;
6362
6363   // Test to see if the operands of the icmp are casted versions of other
6364   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6365   // now.
6366   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6367     if (isa<PointerType>(Op0->getType()) && 
6368         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6369       // We keep moving the cast from the left operand over to the right
6370       // operand, where it can often be eliminated completely.
6371       Op0 = CI->getOperand(0);
6372
6373       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6374       // so eliminate it as well.
6375       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6376         Op1 = CI2->getOperand(0);
6377
6378       // If Op1 is a constant, we can fold the cast into the constant.
6379       if (Op0->getType() != Op1->getType()) {
6380         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6381           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6382         } else {
6383           // Otherwise, cast the RHS right before the icmp
6384           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6385         }
6386       }
6387       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6388     }
6389   }
6390   
6391   if (isa<CastInst>(Op0)) {
6392     // Handle the special case of: icmp (cast bool to X), <cst>
6393     // This comes up when you have code like
6394     //   int X = A < B;
6395     //   if (X) ...
6396     // For generality, we handle any zero-extension of any operand comparison
6397     // with a constant or another cast from the same type.
6398     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6399       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6400         return R;
6401   }
6402   
6403   // See if it's the same type of instruction on the left and right.
6404   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6405     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6406       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6407           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6408         switch (Op0I->getOpcode()) {
6409         default: break;
6410         case Instruction::Add:
6411         case Instruction::Sub:
6412         case Instruction::Xor:
6413           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6414             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6415                                 Op1I->getOperand(0));
6416           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6417           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6418             if (CI->getValue().isSignBit()) {
6419               ICmpInst::Predicate Pred = I.isSignedPredicate()
6420                                              ? I.getUnsignedPredicate()
6421                                              : I.getSignedPredicate();
6422               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6423                                   Op1I->getOperand(0));
6424             }
6425             
6426             if (CI->getValue().isMaxSignedValue()) {
6427               ICmpInst::Predicate Pred = I.isSignedPredicate()
6428                                              ? I.getUnsignedPredicate()
6429                                              : I.getSignedPredicate();
6430               Pred = I.getSwappedPredicate(Pred);
6431               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6432                                   Op1I->getOperand(0));
6433             }
6434           }
6435           break;
6436         case Instruction::Mul:
6437           if (!I.isEquality())
6438             break;
6439
6440           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6441             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6442             // Mask = -1 >> count-trailing-zeros(Cst).
6443             if (!CI->isZero() && !CI->isOne()) {
6444               const APInt &AP = CI->getValue();
6445               ConstantInt *Mask = Context->getConstantInt(
6446                                       APInt::getLowBitsSet(AP.getBitWidth(),
6447                                                            AP.getBitWidth() -
6448                                                       AP.countTrailingZeros()));
6449               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6450                                                             Mask);
6451               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6452                                                             Mask);
6453               InsertNewInstBefore(And1, I);
6454               InsertNewInstBefore(And2, I);
6455               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6456             }
6457           }
6458           break;
6459         }
6460       }
6461     }
6462   }
6463   
6464   // ~x < ~y --> y < x
6465   { Value *A, *B;
6466     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6467         match(Op1, m_Not(m_Value(B)), *Context))
6468       return new ICmpInst(*Context, I.getPredicate(), B, A);
6469   }
6470   
6471   if (I.isEquality()) {
6472     Value *A, *B, *C, *D;
6473     
6474     // -x == -y --> x == y
6475     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6476         match(Op1, m_Neg(m_Value(B)), *Context))
6477       return new ICmpInst(*Context, I.getPredicate(), A, B);
6478     
6479     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6480       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6481         Value *OtherVal = A == Op1 ? B : A;
6482         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6483                             Context->getNullValue(A->getType()));
6484       }
6485
6486       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6487         // A^c1 == C^c2 --> A == C^(c1^c2)
6488         ConstantInt *C1, *C2;
6489         if (match(B, m_ConstantInt(C1), *Context) &&
6490             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6491           Constant *NC = 
6492                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6493           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6494           return new ICmpInst(*Context, I.getPredicate(), A,
6495                               InsertNewInstBefore(Xor, I));
6496         }
6497         
6498         // A^B == A^D -> B == D
6499         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6500         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6501         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6502         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6503       }
6504     }
6505     
6506     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6507         (A == Op0 || B == Op0)) {
6508       // A == (A^B)  ->  B == 0
6509       Value *OtherVal = A == Op0 ? B : A;
6510       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6511                           Context->getNullValue(A->getType()));
6512     }
6513
6514     // (A-B) == A  ->  B == 0
6515     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6516       return new ICmpInst(*Context, I.getPredicate(), B, 
6517                           Context->getNullValue(B->getType()));
6518
6519     // A == (A-B)  ->  B == 0
6520     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6521       return new ICmpInst(*Context, I.getPredicate(), B,
6522                           Context->getNullValue(B->getType()));
6523     
6524     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6525     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6526         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6527         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6528       Value *X = 0, *Y = 0, *Z = 0;
6529       
6530       if (A == C) {
6531         X = B; Y = D; Z = A;
6532       } else if (A == D) {
6533         X = B; Y = C; Z = A;
6534       } else if (B == C) {
6535         X = A; Y = D; Z = B;
6536       } else if (B == D) {
6537         X = A; Y = C; Z = B;
6538       }
6539       
6540       if (X) {   // Build (X^Y) & Z
6541         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6542         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6543         I.setOperand(0, Op1);
6544         I.setOperand(1, Context->getNullValue(Op1->getType()));
6545         return &I;
6546       }
6547     }
6548   }
6549   return Changed ? &I : 0;
6550 }
6551
6552
6553 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6554 /// and CmpRHS are both known to be integer constants.
6555 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6556                                           ConstantInt *DivRHS) {
6557   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6558   const APInt &CmpRHSV = CmpRHS->getValue();
6559   
6560   // FIXME: If the operand types don't match the type of the divide 
6561   // then don't attempt this transform. The code below doesn't have the
6562   // logic to deal with a signed divide and an unsigned compare (and
6563   // vice versa). This is because (x /s C1) <s C2  produces different 
6564   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6565   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6566   // work. :(  The if statement below tests that condition and bails 
6567   // if it finds it. 
6568   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6569   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6570     return 0;
6571   if (DivRHS->isZero())
6572     return 0; // The ProdOV computation fails on divide by zero.
6573   if (DivIsSigned && DivRHS->isAllOnesValue())
6574     return 0; // The overflow computation also screws up here
6575   if (DivRHS->isOne())
6576     return 0; // Not worth bothering, and eliminates some funny cases
6577               // with INT_MIN.
6578
6579   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6580   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6581   // C2 (CI). By solving for X we can turn this into a range check 
6582   // instead of computing a divide. 
6583   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6584
6585   // Determine if the product overflows by seeing if the product is
6586   // not equal to the divide. Make sure we do the same kind of divide
6587   // as in the LHS instruction that we're folding. 
6588   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6589                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6590
6591   // Get the ICmp opcode
6592   ICmpInst::Predicate Pred = ICI.getPredicate();
6593
6594   // Figure out the interval that is being checked.  For example, a comparison
6595   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6596   // Compute this interval based on the constants involved and the signedness of
6597   // the compare/divide.  This computes a half-open interval, keeping track of
6598   // whether either value in the interval overflows.  After analysis each
6599   // overflow variable is set to 0 if it's corresponding bound variable is valid
6600   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6601   int LoOverflow = 0, HiOverflow = 0;
6602   Constant *LoBound = 0, *HiBound = 0;
6603   
6604   if (!DivIsSigned) {  // udiv
6605     // e.g. X/5 op 3  --> [15, 20)
6606     LoBound = Prod;
6607     HiOverflow = LoOverflow = ProdOV;
6608     if (!HiOverflow)
6609       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6610   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6611     if (CmpRHSV == 0) {       // (X / pos) op 0
6612       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6613       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6614                                                                     Context)));
6615       HiBound = DivRHS;
6616     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6617       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6618       HiOverflow = LoOverflow = ProdOV;
6619       if (!HiOverflow)
6620         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6621     } else {                       // (X / pos) op neg
6622       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6623       HiBound = AddOne(Prod, Context);
6624       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6625       if (!LoOverflow) {
6626         ConstantInt* DivNeg =
6627                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6628         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6629                                      true) ? -1 : 0;
6630        }
6631     }
6632   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6633     if (CmpRHSV == 0) {       // (X / neg) op 0
6634       // e.g. X/-5 op 0  --> [-4, 5)
6635       LoBound = AddOne(DivRHS, Context);
6636       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6637       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6638         HiOverflow = 1;            // [INTMIN+1, overflow)
6639         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6640       }
6641     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6642       // e.g. X/-5 op 3  --> [-19, -14)
6643       HiBound = AddOne(Prod, Context);
6644       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6645       if (!LoOverflow)
6646         LoOverflow = AddWithOverflow(LoBound, HiBound,
6647                                      DivRHS, Context, true) ? -1 : 0;
6648     } else {                       // (X / neg) op neg
6649       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6650       LoOverflow = HiOverflow = ProdOV;
6651       if (!HiOverflow)
6652         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6653     }
6654     
6655     // Dividing by a negative swaps the condition.  LT <-> GT
6656     Pred = ICmpInst::getSwappedPredicate(Pred);
6657   }
6658
6659   Value *X = DivI->getOperand(0);
6660   switch (Pred) {
6661   default: llvm_unreachable("Unhandled icmp opcode!");
6662   case ICmpInst::ICMP_EQ:
6663     if (LoOverflow && HiOverflow)
6664       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6665     else if (HiOverflow)
6666       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6667                           ICmpInst::ICMP_UGE, X, LoBound);
6668     else if (LoOverflow)
6669       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6670                           ICmpInst::ICMP_ULT, X, HiBound);
6671     else
6672       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6673   case ICmpInst::ICMP_NE:
6674     if (LoOverflow && HiOverflow)
6675       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6676     else if (HiOverflow)
6677       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6678                           ICmpInst::ICMP_ULT, X, LoBound);
6679     else if (LoOverflow)
6680       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6681                           ICmpInst::ICMP_UGE, X, HiBound);
6682     else
6683       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6684   case ICmpInst::ICMP_ULT:
6685   case ICmpInst::ICMP_SLT:
6686     if (LoOverflow == +1)   // Low bound is greater than input range.
6687       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6688     if (LoOverflow == -1)   // Low bound is less than input range.
6689       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6690     return new ICmpInst(*Context, Pred, X, LoBound);
6691   case ICmpInst::ICMP_UGT:
6692   case ICmpInst::ICMP_SGT:
6693     if (HiOverflow == +1)       // High bound greater than input range.
6694       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6695     else if (HiOverflow == -1)  // High bound less than input range.
6696       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6697     if (Pred == ICmpInst::ICMP_UGT)
6698       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6699     else
6700       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6701   }
6702 }
6703
6704
6705 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6706 ///
6707 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6708                                                           Instruction *LHSI,
6709                                                           ConstantInt *RHS) {
6710   const APInt &RHSV = RHS->getValue();
6711   
6712   switch (LHSI->getOpcode()) {
6713   case Instruction::Trunc:
6714     if (ICI.isEquality() && LHSI->hasOneUse()) {
6715       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6716       // of the high bits truncated out of x are known.
6717       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6718              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6719       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6720       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6721       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6722       
6723       // If all the high bits are known, we can do this xform.
6724       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6725         // Pull in the high bits from known-ones set.
6726         APInt NewRHS(RHS->getValue());
6727         NewRHS.zext(SrcBits);
6728         NewRHS |= KnownOne;
6729         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6730                             Context->getConstantInt(NewRHS));
6731       }
6732     }
6733     break;
6734       
6735   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6736     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6737       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6738       // fold the xor.
6739       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6740           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6741         Value *CompareVal = LHSI->getOperand(0);
6742         
6743         // If the sign bit of the XorCST is not set, there is no change to
6744         // the operation, just stop using the Xor.
6745         if (!XorCST->getValue().isNegative()) {
6746           ICI.setOperand(0, CompareVal);
6747           AddToWorkList(LHSI);
6748           return &ICI;
6749         }
6750         
6751         // Was the old condition true if the operand is positive?
6752         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6753         
6754         // If so, the new one isn't.
6755         isTrueIfPositive ^= true;
6756         
6757         if (isTrueIfPositive)
6758           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6759                               SubOne(RHS, Context));
6760         else
6761           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6762                               AddOne(RHS, Context));
6763       }
6764
6765       if (LHSI->hasOneUse()) {
6766         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6767         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6768           const APInt &SignBit = XorCST->getValue();
6769           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6770                                          ? ICI.getUnsignedPredicate()
6771                                          : ICI.getSignedPredicate();
6772           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6773                               Context->getConstantInt(RHSV ^ SignBit));
6774         }
6775
6776         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6777         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6778           const APInt &NotSignBit = XorCST->getValue();
6779           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6780                                          ? ICI.getUnsignedPredicate()
6781                                          : ICI.getSignedPredicate();
6782           Pred = ICI.getSwappedPredicate(Pred);
6783           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6784                               Context->getConstantInt(RHSV ^ NotSignBit));
6785         }
6786       }
6787     }
6788     break;
6789   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6790     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6791         LHSI->getOperand(0)->hasOneUse()) {
6792       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6793       
6794       // If the LHS is an AND of a truncating cast, we can widen the
6795       // and/compare to be the input width without changing the value
6796       // produced, eliminating a cast.
6797       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6798         // We can do this transformation if either the AND constant does not
6799         // have its sign bit set or if it is an equality comparison. 
6800         // Extending a relational comparison when we're checking the sign
6801         // bit would not work.
6802         if (Cast->hasOneUse() &&
6803             (ICI.isEquality() ||
6804              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6805           uint32_t BitWidth = 
6806             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6807           APInt NewCST = AndCST->getValue();
6808           NewCST.zext(BitWidth);
6809           APInt NewCI = RHSV;
6810           NewCI.zext(BitWidth);
6811           Instruction *NewAnd = 
6812             BinaryOperator::CreateAnd(Cast->getOperand(0),
6813                                Context->getConstantInt(NewCST),LHSI->getName());
6814           InsertNewInstBefore(NewAnd, ICI);
6815           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6816                               Context->getConstantInt(NewCI));
6817         }
6818       }
6819       
6820       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6821       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6822       // happens a LOT in code produced by the C front-end, for bitfield
6823       // access.
6824       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6825       if (Shift && !Shift->isShift())
6826         Shift = 0;
6827       
6828       ConstantInt *ShAmt;
6829       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6830       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6831       const Type *AndTy = AndCST->getType();          // Type of the and.
6832       
6833       // We can fold this as long as we can't shift unknown bits
6834       // into the mask.  This can only happen with signed shift
6835       // rights, as they sign-extend.
6836       if (ShAmt) {
6837         bool CanFold = Shift->isLogicalShift();
6838         if (!CanFold) {
6839           // To test for the bad case of the signed shr, see if any
6840           // of the bits shifted in could be tested after the mask.
6841           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6842           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6843           
6844           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6845           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6846                AndCST->getValue()) == 0)
6847             CanFold = true;
6848         }
6849         
6850         if (CanFold) {
6851           Constant *NewCst;
6852           if (Shift->getOpcode() == Instruction::Shl)
6853             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6854           else
6855             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6856           
6857           // Check to see if we are shifting out any of the bits being
6858           // compared.
6859           if (Context->getConstantExpr(Shift->getOpcode(),
6860                                        NewCst, ShAmt) != RHS) {
6861             // If we shifted bits out, the fold is not going to work out.
6862             // As a special case, check to see if this means that the
6863             // result is always true or false now.
6864             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6865               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6866             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6867               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6868           } else {
6869             ICI.setOperand(1, NewCst);
6870             Constant *NewAndCST;
6871             if (Shift->getOpcode() == Instruction::Shl)
6872               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6873             else
6874               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6875             LHSI->setOperand(1, NewAndCST);
6876             LHSI->setOperand(0, Shift->getOperand(0));
6877             AddToWorkList(Shift); // Shift is dead.
6878             AddUsesToWorkList(ICI);
6879             return &ICI;
6880           }
6881         }
6882       }
6883       
6884       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6885       // preferable because it allows the C<<Y expression to be hoisted out
6886       // of a loop if Y is invariant and X is not.
6887       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6888           ICI.isEquality() && !Shift->isArithmeticShift() &&
6889           !isa<Constant>(Shift->getOperand(0))) {
6890         // Compute C << Y.
6891         Value *NS;
6892         if (Shift->getOpcode() == Instruction::LShr) {
6893           NS = BinaryOperator::CreateShl(AndCST, 
6894                                          Shift->getOperand(1), "tmp");
6895         } else {
6896           // Insert a logical shift.
6897           NS = BinaryOperator::CreateLShr(AndCST,
6898                                           Shift->getOperand(1), "tmp");
6899         }
6900         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6901         
6902         // Compute X & (C << Y).
6903         Instruction *NewAnd = 
6904           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6905         InsertNewInstBefore(NewAnd, ICI);
6906         
6907         ICI.setOperand(0, NewAnd);
6908         return &ICI;
6909       }
6910     }
6911     break;
6912     
6913   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6914     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6915     if (!ShAmt) break;
6916     
6917     uint32_t TypeBits = RHSV.getBitWidth();
6918     
6919     // Check that the shift amount is in range.  If not, don't perform
6920     // undefined shifts.  When the shift is visited it will be
6921     // simplified.
6922     if (ShAmt->uge(TypeBits))
6923       break;
6924     
6925     if (ICI.isEquality()) {
6926       // If we are comparing against bits always shifted out, the
6927       // comparison cannot succeed.
6928       Constant *Comp =
6929         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6930                                                                  ShAmt);
6931       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6932         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6933         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6934         return ReplaceInstUsesWith(ICI, Cst);
6935       }
6936       
6937       if (LHSI->hasOneUse()) {
6938         // Otherwise strength reduce the shift into an and.
6939         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6940         Constant *Mask =
6941           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6942                                                        TypeBits-ShAmtVal));
6943         
6944         Instruction *AndI =
6945           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6946                                     Mask, LHSI->getName()+".mask");
6947         Value *And = InsertNewInstBefore(AndI, ICI);
6948         return new ICmpInst(*Context, ICI.getPredicate(), And,
6949                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6950       }
6951     }
6952     
6953     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6954     bool TrueIfSigned = false;
6955     if (LHSI->hasOneUse() &&
6956         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6957       // (X << 31) <s 0  --> (X&1) != 0
6958       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6959                                            (TypeBits-ShAmt->getZExtValue()-1));
6960       Instruction *AndI =
6961         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6962                                   Mask, LHSI->getName()+".mask");
6963       Value *And = InsertNewInstBefore(AndI, ICI);
6964       
6965       return new ICmpInst(*Context,
6966                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6967                           And, Context->getNullValue(And->getType()));
6968     }
6969     break;
6970   }
6971     
6972   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6973   case Instruction::AShr: {
6974     // Only handle equality comparisons of shift-by-constant.
6975     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6976     if (!ShAmt || !ICI.isEquality()) break;
6977
6978     // Check that the shift amount is in range.  If not, don't perform
6979     // undefined shifts.  When the shift is visited it will be
6980     // simplified.
6981     uint32_t TypeBits = RHSV.getBitWidth();
6982     if (ShAmt->uge(TypeBits))
6983       break;
6984     
6985     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6986       
6987     // If we are comparing against bits always shifted out, the
6988     // comparison cannot succeed.
6989     APInt Comp = RHSV << ShAmtVal;
6990     if (LHSI->getOpcode() == Instruction::LShr)
6991       Comp = Comp.lshr(ShAmtVal);
6992     else
6993       Comp = Comp.ashr(ShAmtVal);
6994     
6995     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6996       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6997       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6998       return ReplaceInstUsesWith(ICI, Cst);
6999     }
7000     
7001     // Otherwise, check to see if the bits shifted out are known to be zero.
7002     // If so, we can compare against the unshifted value:
7003     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7004     if (LHSI->hasOneUse() &&
7005         MaskedValueIsZero(LHSI->getOperand(0), 
7006                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7007       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7008                           Context->getConstantExprShl(RHS, ShAmt));
7009     }
7010       
7011     if (LHSI->hasOneUse()) {
7012       // Otherwise strength reduce the shift into an and.
7013       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7014       Constant *Mask = Context->getConstantInt(Val);
7015       
7016       Instruction *AndI =
7017         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7018                                   Mask, LHSI->getName()+".mask");
7019       Value *And = InsertNewInstBefore(AndI, ICI);
7020       return new ICmpInst(*Context, ICI.getPredicate(), And,
7021                           Context->getConstantExprShl(RHS, ShAmt));
7022     }
7023     break;
7024   }
7025     
7026   case Instruction::SDiv:
7027   case Instruction::UDiv:
7028     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7029     // Fold this div into the comparison, producing a range check. 
7030     // Determine, based on the divide type, what the range is being 
7031     // checked.  If there is an overflow on the low or high side, remember 
7032     // it, otherwise compute the range [low, hi) bounding the new value.
7033     // See: InsertRangeTest above for the kinds of replacements possible.
7034     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7035       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7036                                           DivRHS))
7037         return R;
7038     break;
7039
7040   case Instruction::Add:
7041     // Fold: icmp pred (add, X, C1), C2
7042
7043     if (!ICI.isEquality()) {
7044       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7045       if (!LHSC) break;
7046       const APInt &LHSV = LHSC->getValue();
7047
7048       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7049                             .subtract(LHSV);
7050
7051       if (ICI.isSignedPredicate()) {
7052         if (CR.getLower().isSignBit()) {
7053           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7054                               Context->getConstantInt(CR.getUpper()));
7055         } else if (CR.getUpper().isSignBit()) {
7056           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7057                               Context->getConstantInt(CR.getLower()));
7058         }
7059       } else {
7060         if (CR.getLower().isMinValue()) {
7061           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7062                               Context->getConstantInt(CR.getUpper()));
7063         } else if (CR.getUpper().isMinValue()) {
7064           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7065                               Context->getConstantInt(CR.getLower()));
7066         }
7067       }
7068     }
7069     break;
7070   }
7071   
7072   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7073   if (ICI.isEquality()) {
7074     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7075     
7076     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7077     // the second operand is a constant, simplify a bit.
7078     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7079       switch (BO->getOpcode()) {
7080       case Instruction::SRem:
7081         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7082         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7083           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7084           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7085             Instruction *NewRem =
7086               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7087                                          BO->getName());
7088             InsertNewInstBefore(NewRem, ICI);
7089             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7090                                 Context->getNullValue(BO->getType()));
7091           }
7092         }
7093         break;
7094       case Instruction::Add:
7095         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7096         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7097           if (BO->hasOneUse())
7098             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7099                                 Context->getConstantExprSub(RHS, BOp1C));
7100         } else if (RHSV == 0) {
7101           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7102           // efficiently invertible, or if the add has just this one use.
7103           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7104           
7105           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7106             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7107           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7108             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7109           else if (BO->hasOneUse()) {
7110             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7111             InsertNewInstBefore(Neg, ICI);
7112             Neg->takeName(BO);
7113             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7114           }
7115         }
7116         break;
7117       case Instruction::Xor:
7118         // For the xor case, we can xor two constants together, eliminating
7119         // the explicit xor.
7120         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7121           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7122                               Context->getConstantExprXor(RHS, BOC));
7123         
7124         // FALLTHROUGH
7125       case Instruction::Sub:
7126         // Replace (([sub|xor] A, B) != 0) with (A != B)
7127         if (RHSV == 0)
7128           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7129                               BO->getOperand(1));
7130         break;
7131         
7132       case Instruction::Or:
7133         // If bits are being or'd in that are not present in the constant we
7134         // are comparing against, then the comparison could never succeed!
7135         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7136           Constant *NotCI = Context->getConstantExprNot(RHS);
7137           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7138             return ReplaceInstUsesWith(ICI,
7139                                        Context->getConstantInt(Type::Int1Ty, 
7140                                        isICMP_NE));
7141         }
7142         break;
7143         
7144       case Instruction::And:
7145         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7146           // If bits are being compared against that are and'd out, then the
7147           // comparison can never succeed!
7148           if ((RHSV & ~BOC->getValue()) != 0)
7149             return ReplaceInstUsesWith(ICI,
7150                                        Context->getConstantInt(Type::Int1Ty,
7151                                        isICMP_NE));
7152           
7153           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7154           if (RHS == BOC && RHSV.isPowerOf2())
7155             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7156                                 ICmpInst::ICMP_NE, LHSI,
7157                                 Context->getNullValue(RHS->getType()));
7158           
7159           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7160           if (BOC->getValue().isSignBit()) {
7161             Value *X = BO->getOperand(0);
7162             Constant *Zero = Context->getNullValue(X->getType());
7163             ICmpInst::Predicate pred = isICMP_NE ? 
7164               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7165             return new ICmpInst(*Context, pred, X, Zero);
7166           }
7167           
7168           // ((X & ~7) == 0) --> X < 8
7169           if (RHSV == 0 && isHighOnes(BOC)) {
7170             Value *X = BO->getOperand(0);
7171             Constant *NegX = Context->getConstantExprNeg(BOC);
7172             ICmpInst::Predicate pred = isICMP_NE ? 
7173               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7174             return new ICmpInst(*Context, pred, X, NegX);
7175           }
7176         }
7177       default: break;
7178       }
7179     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7180       // Handle icmp {eq|ne} <intrinsic>, intcst.
7181       if (II->getIntrinsicID() == Intrinsic::bswap) {
7182         AddToWorkList(II);
7183         ICI.setOperand(0, II->getOperand(1));
7184         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7185         return &ICI;
7186       }
7187     }
7188   }
7189   return 0;
7190 }
7191
7192 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7193 /// We only handle extending casts so far.
7194 ///
7195 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7196   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7197   Value *LHSCIOp        = LHSCI->getOperand(0);
7198   const Type *SrcTy     = LHSCIOp->getType();
7199   const Type *DestTy    = LHSCI->getType();
7200   Value *RHSCIOp;
7201
7202   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7203   // integer type is the same size as the pointer type.
7204   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7205       getTargetData().getPointerSizeInBits() == 
7206          cast<IntegerType>(DestTy)->getBitWidth()) {
7207     Value *RHSOp = 0;
7208     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7209       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7210     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7211       RHSOp = RHSC->getOperand(0);
7212       // If the pointer types don't match, insert a bitcast.
7213       if (LHSCIOp->getType() != RHSOp->getType())
7214         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7215     }
7216
7217     if (RHSOp)
7218       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7219   }
7220   
7221   // The code below only handles extension cast instructions, so far.
7222   // Enforce this.
7223   if (LHSCI->getOpcode() != Instruction::ZExt &&
7224       LHSCI->getOpcode() != Instruction::SExt)
7225     return 0;
7226
7227   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7228   bool isSignedCmp = ICI.isSignedPredicate();
7229
7230   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7231     // Not an extension from the same type?
7232     RHSCIOp = CI->getOperand(0);
7233     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7234       return 0;
7235     
7236     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7237     // and the other is a zext), then we can't handle this.
7238     if (CI->getOpcode() != LHSCI->getOpcode())
7239       return 0;
7240
7241     // Deal with equality cases early.
7242     if (ICI.isEquality())
7243       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7244
7245     // A signed comparison of sign extended values simplifies into a
7246     // signed comparison.
7247     if (isSignedCmp && isSignedExt)
7248       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7249
7250     // The other three cases all fold into an unsigned comparison.
7251     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7252   }
7253
7254   // If we aren't dealing with a constant on the RHS, exit early
7255   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7256   if (!CI)
7257     return 0;
7258
7259   // Compute the constant that would happen if we truncated to SrcTy then
7260   // reextended to DestTy.
7261   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7262   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7263                                                 Res1, DestTy);
7264
7265   // If the re-extended constant didn't change...
7266   if (Res2 == CI) {
7267     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7268     // For example, we might have:
7269     //    %A = sext i16 %X to i32
7270     //    %B = icmp ugt i32 %A, 1330
7271     // It is incorrect to transform this into 
7272     //    %B = icmp ugt i16 %X, 1330
7273     // because %A may have negative value. 
7274     //
7275     // However, we allow this when the compare is EQ/NE, because they are
7276     // signless.
7277     if (isSignedExt == isSignedCmp || ICI.isEquality())
7278       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7279     return 0;
7280   }
7281
7282   // The re-extended constant changed so the constant cannot be represented 
7283   // in the shorter type. Consequently, we cannot emit a simple comparison.
7284
7285   // First, handle some easy cases. We know the result cannot be equal at this
7286   // point so handle the ICI.isEquality() cases
7287   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7288     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7289   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7290     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7291
7292   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7293   // should have been folded away previously and not enter in here.
7294   Value *Result;
7295   if (isSignedCmp) {
7296     // We're performing a signed comparison.
7297     if (cast<ConstantInt>(CI)->getValue().isNegative())
7298       Result = Context->getConstantIntFalse();          // X < (small) --> false
7299     else
7300       Result = Context->getConstantIntTrue();           // X < (large) --> true
7301   } else {
7302     // We're performing an unsigned comparison.
7303     if (isSignedExt) {
7304       // We're performing an unsigned comp with a sign extended value.
7305       // This is true if the input is >= 0. [aka >s -1]
7306       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7307       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7308                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7309     } else {
7310       // Unsigned extend & unsigned compare -> always true.
7311       Result = Context->getConstantIntTrue();
7312     }
7313   }
7314
7315   // Finally, return the value computed.
7316   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7317       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7318     return ReplaceInstUsesWith(ICI, Result);
7319
7320   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7321           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7322          "ICmp should be folded!");
7323   if (Constant *CI = dyn_cast<Constant>(Result))
7324     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7325   return BinaryOperator::CreateNot(*Context, Result);
7326 }
7327
7328 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7329   return commonShiftTransforms(I);
7330 }
7331
7332 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7333   return commonShiftTransforms(I);
7334 }
7335
7336 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7337   if (Instruction *R = commonShiftTransforms(I))
7338     return R;
7339   
7340   Value *Op0 = I.getOperand(0);
7341   
7342   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7343   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7344     if (CSI->isAllOnesValue())
7345       return ReplaceInstUsesWith(I, CSI);
7346
7347   // See if we can turn a signed shr into an unsigned shr.
7348   if (MaskedValueIsZero(Op0,
7349                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7350     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7351
7352   // Arithmetic shifting an all-sign-bit value is a no-op.
7353   unsigned NumSignBits = ComputeNumSignBits(Op0);
7354   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7355     return ReplaceInstUsesWith(I, Op0);
7356
7357   return 0;
7358 }
7359
7360 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7361   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7362   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7363
7364   // shl X, 0 == X and shr X, 0 == X
7365   // shl 0, X == 0 and shr 0, X == 0
7366   if (Op1 == Context->getNullValue(Op1->getType()) ||
7367       Op0 == Context->getNullValue(Op0->getType()))
7368     return ReplaceInstUsesWith(I, Op0);
7369   
7370   if (isa<UndefValue>(Op0)) {            
7371     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7372       return ReplaceInstUsesWith(I, Op0);
7373     else                                    // undef << X -> 0, undef >>u X -> 0
7374       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7375   }
7376   if (isa<UndefValue>(Op1)) {
7377     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7378       return ReplaceInstUsesWith(I, Op0);          
7379     else                                     // X << undef, X >>u undef -> 0
7380       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7381   }
7382
7383   // See if we can fold away this shift.
7384   if (SimplifyDemandedInstructionBits(I))
7385     return &I;
7386
7387   // Try to fold constant and into select arguments.
7388   if (isa<Constant>(Op0))
7389     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7390       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7391         return R;
7392
7393   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7394     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7395       return Res;
7396   return 0;
7397 }
7398
7399 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7400                                                BinaryOperator &I) {
7401   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7402
7403   // See if we can simplify any instructions used by the instruction whose sole 
7404   // purpose is to compute bits we don't care about.
7405   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7406   
7407   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7408   // a signed shift.
7409   //
7410   if (Op1->uge(TypeBits)) {
7411     if (I.getOpcode() != Instruction::AShr)
7412       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7413     else {
7414       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7415       return &I;
7416     }
7417   }
7418   
7419   // ((X*C1) << C2) == (X * (C1 << C2))
7420   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7421     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7422       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7423         return BinaryOperator::CreateMul(BO->getOperand(0),
7424                                         Context->getConstantExprShl(BOOp, Op1));
7425   
7426   // Try to fold constant and into select arguments.
7427   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7428     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7429       return R;
7430   if (isa<PHINode>(Op0))
7431     if (Instruction *NV = FoldOpIntoPhi(I))
7432       return NV;
7433   
7434   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7435   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7436     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7437     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7438     // place.  Don't try to do this transformation in this case.  Also, we
7439     // require that the input operand is a shift-by-constant so that we have
7440     // confidence that the shifts will get folded together.  We could do this
7441     // xform in more cases, but it is unlikely to be profitable.
7442     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7443         isa<ConstantInt>(TrOp->getOperand(1))) {
7444       // Okay, we'll do this xform.  Make the shift of shift.
7445       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7446       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7447                                                 I.getName());
7448       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7449
7450       // For logical shifts, the truncation has the effect of making the high
7451       // part of the register be zeros.  Emulate this by inserting an AND to
7452       // clear the top bits as needed.  This 'and' will usually be zapped by
7453       // other xforms later if dead.
7454       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7455       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7456       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7457       
7458       // The mask we constructed says what the trunc would do if occurring
7459       // between the shifts.  We want to know the effect *after* the second
7460       // shift.  We know that it is a logical shift by a constant, so adjust the
7461       // mask as appropriate.
7462       if (I.getOpcode() == Instruction::Shl)
7463         MaskV <<= Op1->getZExtValue();
7464       else {
7465         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7466         MaskV = MaskV.lshr(Op1->getZExtValue());
7467       }
7468
7469       Instruction *And =
7470         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7471                                   TI->getName());
7472       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7473
7474       // Return the value truncated to the interesting size.
7475       return new TruncInst(And, I.getType());
7476     }
7477   }
7478   
7479   if (Op0->hasOneUse()) {
7480     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7481       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7482       Value *V1, *V2;
7483       ConstantInt *CC;
7484       switch (Op0BO->getOpcode()) {
7485         default: break;
7486         case Instruction::Add:
7487         case Instruction::And:
7488         case Instruction::Or:
7489         case Instruction::Xor: {
7490           // These operators commute.
7491           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7492           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7493               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7494                     m_Specific(Op1)), *Context)){
7495             Instruction *YS = BinaryOperator::CreateShl(
7496                                             Op0BO->getOperand(0), Op1,
7497                                             Op0BO->getName());
7498             InsertNewInstBefore(YS, I); // (Y << C)
7499             Instruction *X = 
7500               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7501                                      Op0BO->getOperand(1)->getName());
7502             InsertNewInstBefore(X, I);  // (X + (Y << C))
7503             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7504             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7505                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7506           }
7507           
7508           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7509           Value *Op0BOOp1 = Op0BO->getOperand(1);
7510           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7511               match(Op0BOOp1, 
7512                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7513                           m_ConstantInt(CC)), *Context) &&
7514               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7515             Instruction *YS = BinaryOperator::CreateShl(
7516                                                      Op0BO->getOperand(0), Op1,
7517                                                      Op0BO->getName());
7518             InsertNewInstBefore(YS, I); // (Y << C)
7519             Instruction *XM =
7520               BinaryOperator::CreateAnd(V1,
7521                                         Context->getConstantExprShl(CC, Op1),
7522                                         V1->getName()+".mask");
7523             InsertNewInstBefore(XM, I); // X & (CC << C)
7524             
7525             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7526           }
7527         }
7528           
7529         // FALL THROUGH.
7530         case Instruction::Sub: {
7531           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7532           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7533               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7534                     m_Specific(Op1)), *Context)){
7535             Instruction *YS = BinaryOperator::CreateShl(
7536                                                      Op0BO->getOperand(1), Op1,
7537                                                      Op0BO->getName());
7538             InsertNewInstBefore(YS, I); // (Y << C)
7539             Instruction *X =
7540               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7541                                      Op0BO->getOperand(0)->getName());
7542             InsertNewInstBefore(X, I);  // (X + (Y << C))
7543             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7544             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7545                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7546           }
7547           
7548           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7549           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7550               match(Op0BO->getOperand(0),
7551                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7552                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7553               cast<BinaryOperator>(Op0BO->getOperand(0))
7554                   ->getOperand(0)->hasOneUse()) {
7555             Instruction *YS = BinaryOperator::CreateShl(
7556                                                      Op0BO->getOperand(1), Op1,
7557                                                      Op0BO->getName());
7558             InsertNewInstBefore(YS, I); // (Y << C)
7559             Instruction *XM =
7560               BinaryOperator::CreateAnd(V1, 
7561                                         Context->getConstantExprShl(CC, Op1),
7562                                         V1->getName()+".mask");
7563             InsertNewInstBefore(XM, I); // X & (CC << C)
7564             
7565             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7566           }
7567           
7568           break;
7569         }
7570       }
7571       
7572       
7573       // If the operand is an bitwise operator with a constant RHS, and the
7574       // shift is the only use, we can pull it out of the shift.
7575       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7576         bool isValid = true;     // Valid only for And, Or, Xor
7577         bool highBitSet = false; // Transform if high bit of constant set?
7578         
7579         switch (Op0BO->getOpcode()) {
7580           default: isValid = false; break;   // Do not perform transform!
7581           case Instruction::Add:
7582             isValid = isLeftShift;
7583             break;
7584           case Instruction::Or:
7585           case Instruction::Xor:
7586             highBitSet = false;
7587             break;
7588           case Instruction::And:
7589             highBitSet = true;
7590             break;
7591         }
7592         
7593         // If this is a signed shift right, and the high bit is modified
7594         // by the logical operation, do not perform the transformation.
7595         // The highBitSet boolean indicates the value of the high bit of
7596         // the constant which would cause it to be modified for this
7597         // operation.
7598         //
7599         if (isValid && I.getOpcode() == Instruction::AShr)
7600           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7601         
7602         if (isValid) {
7603           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7604           
7605           Instruction *NewShift =
7606             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7607           InsertNewInstBefore(NewShift, I);
7608           NewShift->takeName(Op0BO);
7609           
7610           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7611                                         NewRHS);
7612         }
7613       }
7614     }
7615   }
7616   
7617   // Find out if this is a shift of a shift by a constant.
7618   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7619   if (ShiftOp && !ShiftOp->isShift())
7620     ShiftOp = 0;
7621   
7622   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7623     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7624     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7625     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7626     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7627     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7628     Value *X = ShiftOp->getOperand(0);
7629     
7630     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7631     
7632     const IntegerType *Ty = cast<IntegerType>(I.getType());
7633     
7634     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7635     if (I.getOpcode() == ShiftOp->getOpcode()) {
7636       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7637       // saturates.
7638       if (AmtSum >= TypeBits) {
7639         if (I.getOpcode() != Instruction::AShr)
7640           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7641         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7642       }
7643       
7644       return BinaryOperator::Create(I.getOpcode(), X,
7645                                     Context->getConstantInt(Ty, AmtSum));
7646     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7647                I.getOpcode() == Instruction::AShr) {
7648       if (AmtSum >= TypeBits)
7649         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7650       
7651       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7652       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7653     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7654                I.getOpcode() == Instruction::LShr) {
7655       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7656       if (AmtSum >= TypeBits)
7657         AmtSum = TypeBits-1;
7658       
7659       Instruction *Shift =
7660         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7661       InsertNewInstBefore(Shift, I);
7662
7663       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7664       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7665     }
7666     
7667     // Okay, if we get here, one shift must be left, and the other shift must be
7668     // right.  See if the amounts are equal.
7669     if (ShiftAmt1 == ShiftAmt2) {
7670       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7671       if (I.getOpcode() == Instruction::Shl) {
7672         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7673         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7674       }
7675       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7676       if (I.getOpcode() == Instruction::LShr) {
7677         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7678         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7679       }
7680       // We can simplify ((X << C) >>s C) into a trunc + sext.
7681       // NOTE: we could do this for any C, but that would make 'unusual' integer
7682       // types.  For now, just stick to ones well-supported by the code
7683       // generators.
7684       const Type *SExtType = 0;
7685       switch (Ty->getBitWidth() - ShiftAmt1) {
7686       case 1  :
7687       case 8  :
7688       case 16 :
7689       case 32 :
7690       case 64 :
7691       case 128:
7692         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7693         break;
7694       default: break;
7695       }
7696       if (SExtType) {
7697         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7698         InsertNewInstBefore(NewTrunc, I);
7699         return new SExtInst(NewTrunc, Ty);
7700       }
7701       // Otherwise, we can't handle it yet.
7702     } else if (ShiftAmt1 < ShiftAmt2) {
7703       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7704       
7705       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7706       if (I.getOpcode() == Instruction::Shl) {
7707         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7708                ShiftOp->getOpcode() == Instruction::AShr);
7709         Instruction *Shift =
7710           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7711         InsertNewInstBefore(Shift, I);
7712         
7713         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7714         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7715       }
7716       
7717       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7718       if (I.getOpcode() == Instruction::LShr) {
7719         assert(ShiftOp->getOpcode() == Instruction::Shl);
7720         Instruction *Shift =
7721           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7722         InsertNewInstBefore(Shift, I);
7723         
7724         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7725         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7726       }
7727       
7728       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7729     } else {
7730       assert(ShiftAmt2 < ShiftAmt1);
7731       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7732
7733       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7734       if (I.getOpcode() == Instruction::Shl) {
7735         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7736                ShiftOp->getOpcode() == Instruction::AShr);
7737         Instruction *Shift =
7738           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7739                                  Context->getConstantInt(Ty, ShiftDiff));
7740         InsertNewInstBefore(Shift, I);
7741         
7742         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7743         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7744       }
7745       
7746       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7747       if (I.getOpcode() == Instruction::LShr) {
7748         assert(ShiftOp->getOpcode() == Instruction::Shl);
7749         Instruction *Shift =
7750           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7751         InsertNewInstBefore(Shift, I);
7752         
7753         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7754         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7755       }
7756       
7757       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7758     }
7759   }
7760   return 0;
7761 }
7762
7763
7764 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7765 /// expression.  If so, decompose it, returning some value X, such that Val is
7766 /// X*Scale+Offset.
7767 ///
7768 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7769                                         int &Offset, LLVMContext *Context) {
7770   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7771   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7772     Offset = CI->getZExtValue();
7773     Scale  = 0;
7774     return Context->getConstantInt(Type::Int32Ty, 0);
7775   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7776     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7777       if (I->getOpcode() == Instruction::Shl) {
7778         // This is a value scaled by '1 << the shift amt'.
7779         Scale = 1U << RHS->getZExtValue();
7780         Offset = 0;
7781         return I->getOperand(0);
7782       } else if (I->getOpcode() == Instruction::Mul) {
7783         // This value is scaled by 'RHS'.
7784         Scale = RHS->getZExtValue();
7785         Offset = 0;
7786         return I->getOperand(0);
7787       } else if (I->getOpcode() == Instruction::Add) {
7788         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7789         // where C1 is divisible by C2.
7790         unsigned SubScale;
7791         Value *SubVal = 
7792           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7793                                     Offset, Context);
7794         Offset += RHS->getZExtValue();
7795         Scale = SubScale;
7796         return SubVal;
7797       }
7798     }
7799   }
7800
7801   // Otherwise, we can't look past this.
7802   Scale = 1;
7803   Offset = 0;
7804   return Val;
7805 }
7806
7807
7808 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7809 /// try to eliminate the cast by moving the type information into the alloc.
7810 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7811                                                    AllocationInst &AI) {
7812   const PointerType *PTy = cast<PointerType>(CI.getType());
7813   
7814   // Remove any uses of AI that are dead.
7815   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7816   
7817   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7818     Instruction *User = cast<Instruction>(*UI++);
7819     if (isInstructionTriviallyDead(User)) {
7820       while (UI != E && *UI == User)
7821         ++UI; // If this instruction uses AI more than once, don't break UI.
7822       
7823       ++NumDeadInst;
7824       DOUT << "IC: DCE: " << *User;
7825       EraseInstFromFunction(*User);
7826     }
7827   }
7828   
7829   // Get the type really allocated and the type casted to.
7830   const Type *AllocElTy = AI.getAllocatedType();
7831   const Type *CastElTy = PTy->getElementType();
7832   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7833
7834   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7835   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7836   if (CastElTyAlign < AllocElTyAlign) return 0;
7837
7838   // If the allocation has multiple uses, only promote it if we are strictly
7839   // increasing the alignment of the resultant allocation.  If we keep it the
7840   // same, we open the door to infinite loops of various kinds.  (A reference
7841   // from a dbg.declare doesn't count as a use for this purpose.)
7842   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7843       CastElTyAlign == AllocElTyAlign) return 0;
7844
7845   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7846   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7847   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7848
7849   // See if we can satisfy the modulus by pulling a scale out of the array
7850   // size argument.
7851   unsigned ArraySizeScale;
7852   int ArrayOffset;
7853   Value *NumElements = // See if the array size is a decomposable linear expr.
7854     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7855                               ArrayOffset, Context);
7856  
7857   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7858   // do the xform.
7859   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7860       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7861
7862   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7863   Value *Amt = 0;
7864   if (Scale == 1) {
7865     Amt = NumElements;
7866   } else {
7867     // If the allocation size is constant, form a constant mul expression
7868     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7869     if (isa<ConstantInt>(NumElements))
7870       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7871                                  cast<ConstantInt>(Amt));
7872     // otherwise multiply the amount and the number of elements
7873     else {
7874       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7875       Amt = InsertNewInstBefore(Tmp, AI);
7876     }
7877   }
7878   
7879   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7880     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7881     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7882     Amt = InsertNewInstBefore(Tmp, AI);
7883   }
7884   
7885   AllocationInst *New;
7886   if (isa<MallocInst>(AI))
7887     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7888   else
7889     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7890   InsertNewInstBefore(New, AI);
7891   New->takeName(&AI);
7892   
7893   // If the allocation has one real use plus a dbg.declare, just remove the
7894   // declare.
7895   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7896     EraseInstFromFunction(*DI);
7897   }
7898   // If the allocation has multiple real uses, insert a cast and change all
7899   // things that used it to use the new cast.  This will also hack on CI, but it
7900   // will die soon.
7901   else if (!AI.hasOneUse()) {
7902     AddUsesToWorkList(AI);
7903     // New is the allocation instruction, pointer typed. AI is the original
7904     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7905     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7906     InsertNewInstBefore(NewCast, AI);
7907     AI.replaceAllUsesWith(NewCast);
7908   }
7909   return ReplaceInstUsesWith(CI, New);
7910 }
7911
7912 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7913 /// and return it as type Ty without inserting any new casts and without
7914 /// changing the computed value.  This is used by code that tries to decide
7915 /// whether promoting or shrinking integer operations to wider or smaller types
7916 /// will allow us to eliminate a truncate or extend.
7917 ///
7918 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7919 /// extension operation if Ty is larger.
7920 ///
7921 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7922 /// should return true if trunc(V) can be computed by computing V in the smaller
7923 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7924 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7925 /// efficiently truncated.
7926 ///
7927 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7928 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7929 /// the final result.
7930 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7931                                               unsigned CastOpc,
7932                                               int &NumCastsRemoved){
7933   // We can always evaluate constants in another type.
7934   if (isa<Constant>(V))
7935     return true;
7936   
7937   Instruction *I = dyn_cast<Instruction>(V);
7938   if (!I) return false;
7939   
7940   const Type *OrigTy = V->getType();
7941   
7942   // If this is an extension or truncate, we can often eliminate it.
7943   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7944     // If this is a cast from the destination type, we can trivially eliminate
7945     // it, and this will remove a cast overall.
7946     if (I->getOperand(0)->getType() == Ty) {
7947       // If the first operand is itself a cast, and is eliminable, do not count
7948       // this as an eliminable cast.  We would prefer to eliminate those two
7949       // casts first.
7950       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7951         ++NumCastsRemoved;
7952       return true;
7953     }
7954   }
7955
7956   // We can't extend or shrink something that has multiple uses: doing so would
7957   // require duplicating the instruction in general, which isn't profitable.
7958   if (!I->hasOneUse()) return false;
7959
7960   unsigned Opc = I->getOpcode();
7961   switch (Opc) {
7962   case Instruction::Add:
7963   case Instruction::Sub:
7964   case Instruction::Mul:
7965   case Instruction::And:
7966   case Instruction::Or:
7967   case Instruction::Xor:
7968     // These operators can all arbitrarily be extended or truncated.
7969     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7970                                       NumCastsRemoved) &&
7971            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7972                                       NumCastsRemoved);
7973
7974   case Instruction::UDiv:
7975   case Instruction::URem: {
7976     // UDiv and URem can be truncated if all the truncated bits are zero.
7977     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978     uint32_t BitWidth = Ty->getScalarSizeInBits();
7979     if (BitWidth < OrigBitWidth) {
7980       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7981       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7982           MaskedValueIsZero(I->getOperand(1), Mask)) {
7983         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984                                           NumCastsRemoved) &&
7985                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7986                                           NumCastsRemoved);
7987       }
7988     }
7989     break;
7990   }
7991   case Instruction::Shl:
7992     // If we are truncating the result of this SHL, and if it's a shift of a
7993     // constant amount, we can always perform a SHL in a smaller type.
7994     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7995       uint32_t BitWidth = Ty->getScalarSizeInBits();
7996       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7997           CI->getLimitedValue(BitWidth) < BitWidth)
7998         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7999                                           NumCastsRemoved);
8000     }
8001     break;
8002   case Instruction::LShr:
8003     // If this is a truncate of a logical shr, we can truncate it to a smaller
8004     // lshr iff we know that the bits we would otherwise be shifting in are
8005     // already zeros.
8006     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8007       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8008       uint32_t BitWidth = Ty->getScalarSizeInBits();
8009       if (BitWidth < OrigBitWidth &&
8010           MaskedValueIsZero(I->getOperand(0),
8011             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8012           CI->getLimitedValue(BitWidth) < BitWidth) {
8013         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8014                                           NumCastsRemoved);
8015       }
8016     }
8017     break;
8018   case Instruction::ZExt:
8019   case Instruction::SExt:
8020   case Instruction::Trunc:
8021     // If this is the same kind of case as our original (e.g. zext+zext), we
8022     // can safely replace it.  Note that replacing it does not reduce the number
8023     // of casts in the input.
8024     if (Opc == CastOpc)
8025       return true;
8026
8027     // sext (zext ty1), ty2 -> zext ty2
8028     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8029       return true;
8030     break;
8031   case Instruction::Select: {
8032     SelectInst *SI = cast<SelectInst>(I);
8033     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8034                                       NumCastsRemoved) &&
8035            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8036                                       NumCastsRemoved);
8037   }
8038   case Instruction::PHI: {
8039     // We can change a phi if we can change all operands.
8040     PHINode *PN = cast<PHINode>(I);
8041     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8042       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8043                                       NumCastsRemoved))
8044         return false;
8045     return true;
8046   }
8047   default:
8048     // TODO: Can handle more cases here.
8049     break;
8050   }
8051   
8052   return false;
8053 }
8054
8055 /// EvaluateInDifferentType - Given an expression that 
8056 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8057 /// evaluate the expression.
8058 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8059                                              bool isSigned) {
8060   if (Constant *C = dyn_cast<Constant>(V))
8061     return Context->getConstantExprIntegerCast(C, Ty,
8062                                                isSigned /*Sext or ZExt*/);
8063
8064   // Otherwise, it must be an instruction.
8065   Instruction *I = cast<Instruction>(V);
8066   Instruction *Res = 0;
8067   unsigned Opc = I->getOpcode();
8068   switch (Opc) {
8069   case Instruction::Add:
8070   case Instruction::Sub:
8071   case Instruction::Mul:
8072   case Instruction::And:
8073   case Instruction::Or:
8074   case Instruction::Xor:
8075   case Instruction::AShr:
8076   case Instruction::LShr:
8077   case Instruction::Shl:
8078   case Instruction::UDiv:
8079   case Instruction::URem: {
8080     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8081     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8083     break;
8084   }    
8085   case Instruction::Trunc:
8086   case Instruction::ZExt:
8087   case Instruction::SExt:
8088     // If the source type of the cast is the type we're trying for then we can
8089     // just return the source.  There's no need to insert it because it is not
8090     // new.
8091     if (I->getOperand(0)->getType() == Ty)
8092       return I->getOperand(0);
8093     
8094     // Otherwise, must be the same type of cast, so just reinsert a new one.
8095     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8096                            Ty);
8097     break;
8098   case Instruction::Select: {
8099     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8100     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8101     Res = SelectInst::Create(I->getOperand(0), True, False);
8102     break;
8103   }
8104   case Instruction::PHI: {
8105     PHINode *OPN = cast<PHINode>(I);
8106     PHINode *NPN = PHINode::Create(Ty);
8107     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8108       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8109       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8110     }
8111     Res = NPN;
8112     break;
8113   }
8114   default: 
8115     // TODO: Can handle more cases here.
8116     llvm_unreachable("Unreachable!");
8117     break;
8118   }
8119   
8120   Res->takeName(I);
8121   return InsertNewInstBefore(Res, *I);
8122 }
8123
8124 /// @brief Implement the transforms common to all CastInst visitors.
8125 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8126   Value *Src = CI.getOperand(0);
8127
8128   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8129   // eliminate it now.
8130   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8131     if (Instruction::CastOps opc = 
8132         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8133       // The first cast (CSrc) is eliminable so we need to fix up or replace
8134       // the second cast (CI). CSrc will then have a good chance of being dead.
8135       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8136     }
8137   }
8138
8139   // If we are casting a select then fold the cast into the select
8140   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8141     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8142       return NV;
8143
8144   // If we are casting a PHI then fold the cast into the PHI
8145   if (isa<PHINode>(Src))
8146     if (Instruction *NV = FoldOpIntoPhi(CI))
8147       return NV;
8148   
8149   return 0;
8150 }
8151
8152 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8153 /// or not there is a sequence of GEP indices into the type that will land us at
8154 /// the specified offset.  If so, fill them into NewIndices and return the
8155 /// resultant element type, otherwise return null.
8156 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8157                                        SmallVectorImpl<Value*> &NewIndices,
8158                                        const TargetData *TD,
8159                                        LLVMContext *Context) {
8160   if (!Ty->isSized()) return 0;
8161   
8162   // Start with the index over the outer type.  Note that the type size
8163   // might be zero (even if the offset isn't zero) if the indexed type
8164   // is something like [0 x {int, int}]
8165   const Type *IntPtrTy = TD->getIntPtrType();
8166   int64_t FirstIdx = 0;
8167   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8168     FirstIdx = Offset/TySize;
8169     Offset -= FirstIdx*TySize;
8170     
8171     // Handle hosts where % returns negative instead of values [0..TySize).
8172     if (Offset < 0) {
8173       --FirstIdx;
8174       Offset += TySize;
8175       assert(Offset >= 0);
8176     }
8177     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8178   }
8179   
8180   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8181     
8182   // Index into the types.  If we fail, set OrigBase to null.
8183   while (Offset) {
8184     // Indexing into tail padding between struct/array elements.
8185     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8186       return 0;
8187     
8188     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8189       const StructLayout *SL = TD->getStructLayout(STy);
8190       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8191              "Offset must stay within the indexed type");
8192       
8193       unsigned Elt = SL->getElementContainingOffset(Offset);
8194       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8195       
8196       Offset -= SL->getElementOffset(Elt);
8197       Ty = STy->getElementType(Elt);
8198     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8199       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8200       assert(EltSize && "Cannot index into a zero-sized array");
8201       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8202       Offset %= EltSize;
8203       Ty = AT->getElementType();
8204     } else {
8205       // Otherwise, we can't index into the middle of this atomic type, bail.
8206       return 0;
8207     }
8208   }
8209   
8210   return Ty;
8211 }
8212
8213 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8214 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8215   Value *Src = CI.getOperand(0);
8216   
8217   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8218     // If casting the result of a getelementptr instruction with no offset, turn
8219     // this into a cast of the original pointer!
8220     if (GEP->hasAllZeroIndices()) {
8221       // Changing the cast operand is usually not a good idea but it is safe
8222       // here because the pointer operand is being replaced with another 
8223       // pointer operand so the opcode doesn't need to change.
8224       AddToWorkList(GEP);
8225       CI.setOperand(0, GEP->getOperand(0));
8226       return &CI;
8227     }
8228     
8229     // If the GEP has a single use, and the base pointer is a bitcast, and the
8230     // GEP computes a constant offset, see if we can convert these three
8231     // instructions into fewer.  This typically happens with unions and other
8232     // non-type-safe code.
8233     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8234       if (GEP->hasAllConstantIndices()) {
8235         // We are guaranteed to get a constant from EmitGEPOffset.
8236         ConstantInt *OffsetV =
8237                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8238         int64_t Offset = OffsetV->getSExtValue();
8239         
8240         // Get the base pointer input of the bitcast, and the type it points to.
8241         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8242         const Type *GEPIdxTy =
8243           cast<PointerType>(OrigBase->getType())->getElementType();
8244         SmallVector<Value*, 8> NewIndices;
8245         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8246           // If we were able to index down into an element, create the GEP
8247           // and bitcast the result.  This eliminates one bitcast, potentially
8248           // two.
8249           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8250                                                         NewIndices.begin(),
8251                                                         NewIndices.end(), "");
8252           InsertNewInstBefore(NGEP, CI);
8253           NGEP->takeName(GEP);
8254           
8255           if (isa<BitCastInst>(CI))
8256             return new BitCastInst(NGEP, CI.getType());
8257           assert(isa<PtrToIntInst>(CI));
8258           return new PtrToIntInst(NGEP, CI.getType());
8259         }
8260       }      
8261     }
8262   }
8263     
8264   return commonCastTransforms(CI);
8265 }
8266
8267 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8268 /// type like i42.  We don't want to introduce operations on random non-legal
8269 /// integer types where they don't already exist in the code.  In the future,
8270 /// we should consider making this based off target-data, so that 32-bit targets
8271 /// won't get i64 operations etc.
8272 static bool isSafeIntegerType(const Type *Ty) {
8273   switch (Ty->getPrimitiveSizeInBits()) {
8274   case 8:
8275   case 16:
8276   case 32:
8277   case 64:
8278     return true;
8279   default: 
8280     return false;
8281   }
8282 }
8283
8284 /// commonIntCastTransforms - This function implements the common transforms
8285 /// for trunc, zext, and sext.
8286 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8287   if (Instruction *Result = commonCastTransforms(CI))
8288     return Result;
8289
8290   Value *Src = CI.getOperand(0);
8291   const Type *SrcTy = Src->getType();
8292   const Type *DestTy = CI.getType();
8293   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8294   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8295
8296   // See if we can simplify any instructions used by the LHS whose sole 
8297   // purpose is to compute bits we don't care about.
8298   if (SimplifyDemandedInstructionBits(CI))
8299     return &CI;
8300
8301   // If the source isn't an instruction or has more than one use then we
8302   // can't do anything more. 
8303   Instruction *SrcI = dyn_cast<Instruction>(Src);
8304   if (!SrcI || !Src->hasOneUse())
8305     return 0;
8306
8307   // Attempt to propagate the cast into the instruction for int->int casts.
8308   int NumCastsRemoved = 0;
8309   // Only do this if the dest type is a simple type, don't convert the
8310   // expression tree to something weird like i93 unless the source is also
8311   // strange.
8312   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8313        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8314       CanEvaluateInDifferentType(SrcI, DestTy,
8315                                  CI.getOpcode(), NumCastsRemoved)) {
8316     // If this cast is a truncate, evaluting in a different type always
8317     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8318     // we need to do an AND to maintain the clear top-part of the computation,
8319     // so we require that the input have eliminated at least one cast.  If this
8320     // is a sign extension, we insert two new casts (to do the extension) so we
8321     // require that two casts have been eliminated.
8322     bool DoXForm = false;
8323     bool JustReplace = false;
8324     switch (CI.getOpcode()) {
8325     default:
8326       // All the others use floating point so we shouldn't actually 
8327       // get here because of the check above.
8328       llvm_unreachable("Unknown cast type");
8329     case Instruction::Trunc:
8330       DoXForm = true;
8331       break;
8332     case Instruction::ZExt: {
8333       DoXForm = NumCastsRemoved >= 1;
8334       if (!DoXForm && 0) {
8335         // If it's unnecessary to issue an AND to clear the high bits, it's
8336         // always profitable to do this xform.
8337         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8338         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8339         if (MaskedValueIsZero(TryRes, Mask))
8340           return ReplaceInstUsesWith(CI, TryRes);
8341         
8342         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8343           if (TryI->use_empty())
8344             EraseInstFromFunction(*TryI);
8345       }
8346       break;
8347     }
8348     case Instruction::SExt: {
8349       DoXForm = NumCastsRemoved >= 2;
8350       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8351         // If we do not have to emit the truncate + sext pair, then it's always
8352         // profitable to do this xform.
8353         //
8354         // It's not safe to eliminate the trunc + sext pair if one of the
8355         // eliminated cast is a truncate. e.g.
8356         // t2 = trunc i32 t1 to i16
8357         // t3 = sext i16 t2 to i32
8358         // !=
8359         // i32 t1
8360         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8361         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8362         if (NumSignBits > (DestBitSize - SrcBitSize))
8363           return ReplaceInstUsesWith(CI, TryRes);
8364         
8365         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8366           if (TryI->use_empty())
8367             EraseInstFromFunction(*TryI);
8368       }
8369       break;
8370     }
8371     }
8372     
8373     if (DoXForm) {
8374       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8375            << " cast: " << CI;
8376       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8377                                            CI.getOpcode() == Instruction::SExt);
8378       if (JustReplace)
8379         // Just replace this cast with the result.
8380         return ReplaceInstUsesWith(CI, Res);
8381
8382       assert(Res->getType() == DestTy);
8383       switch (CI.getOpcode()) {
8384       default: llvm_unreachable("Unknown cast type!");
8385       case Instruction::Trunc:
8386         // Just replace this cast with the result.
8387         return ReplaceInstUsesWith(CI, Res);
8388       case Instruction::ZExt: {
8389         assert(SrcBitSize < DestBitSize && "Not a zext?");
8390
8391         // If the high bits are already zero, just replace this cast with the
8392         // result.
8393         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8394         if (MaskedValueIsZero(Res, Mask))
8395           return ReplaceInstUsesWith(CI, Res);
8396
8397         // We need to emit an AND to clear the high bits.
8398         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8399                                                             SrcBitSize));
8400         return BinaryOperator::CreateAnd(Res, C);
8401       }
8402       case Instruction::SExt: {
8403         // If the high bits are already filled with sign bit, just replace this
8404         // cast with the result.
8405         unsigned NumSignBits = ComputeNumSignBits(Res);
8406         if (NumSignBits > (DestBitSize - SrcBitSize))
8407           return ReplaceInstUsesWith(CI, Res);
8408
8409         // We need to emit a cast to truncate, then a cast to sext.
8410         return CastInst::Create(Instruction::SExt,
8411             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8412                              CI), DestTy);
8413       }
8414       }
8415     }
8416   }
8417   
8418   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8419   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8420
8421   switch (SrcI->getOpcode()) {
8422   case Instruction::Add:
8423   case Instruction::Mul:
8424   case Instruction::And:
8425   case Instruction::Or:
8426   case Instruction::Xor:
8427     // If we are discarding information, rewrite.
8428     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8429       // Don't insert two casts unless at least one can be eliminated.
8430       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8431           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8432         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8433         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8434         return BinaryOperator::Create(
8435             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8436       }
8437     }
8438
8439     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8440     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8441         SrcI->getOpcode() == Instruction::Xor &&
8442         Op1 == Context->getConstantIntTrue() &&
8443         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8444       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8445       return BinaryOperator::CreateXor(New,
8446                                       Context->getConstantInt(CI.getType(), 1));
8447     }
8448     break;
8449
8450   case Instruction::Shl: {
8451     // Canonicalize trunc inside shl, if we can.
8452     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8453     if (CI && DestBitSize < SrcBitSize &&
8454         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8455       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8456       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8457       return BinaryOperator::CreateShl(Op0c, Op1c);
8458     }
8459     break;
8460   }
8461   }
8462   return 0;
8463 }
8464
8465 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8466   if (Instruction *Result = commonIntCastTransforms(CI))
8467     return Result;
8468   
8469   Value *Src = CI.getOperand(0);
8470   const Type *Ty = CI.getType();
8471   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8472   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8473
8474   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8475   if (DestBitWidth == 1 &&
8476       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8477     Constant *One = Context->getConstantInt(Src->getType(), 1);
8478     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8479     Value *Zero = Context->getNullValue(Src->getType());
8480     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8481   }
8482
8483   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8484   ConstantInt *ShAmtV = 0;
8485   Value *ShiftOp = 0;
8486   if (Src->hasOneUse() &&
8487       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8488     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8489     
8490     // Get a mask for the bits shifting in.
8491     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8492     if (MaskedValueIsZero(ShiftOp, Mask)) {
8493       if (ShAmt >= DestBitWidth)        // All zeros.
8494         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8495       
8496       // Okay, we can shrink this.  Truncate the input, then return a new
8497       // shift.
8498       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8499       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8500       return BinaryOperator::CreateLShr(V1, V2);
8501     }
8502   }
8503   
8504   return 0;
8505 }
8506
8507 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8508 /// in order to eliminate the icmp.
8509 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8510                                              bool DoXform) {
8511   // If we are just checking for a icmp eq of a single bit and zext'ing it
8512   // to an integer, then shift the bit to the appropriate place and then
8513   // cast to integer to avoid the comparison.
8514   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8515     const APInt &Op1CV = Op1C->getValue();
8516       
8517     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8518     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8519     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8520         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8521       if (!DoXform) return ICI;
8522
8523       Value *In = ICI->getOperand(0);
8524       Value *Sh = Context->getConstantInt(In->getType(),
8525                                    In->getType()->getScalarSizeInBits()-1);
8526       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8527                                                         In->getName()+".lobit"),
8528                                CI);
8529       if (In->getType() != CI.getType())
8530         In = CastInst::CreateIntegerCast(In, CI.getType(),
8531                                          false/*ZExt*/, "tmp", &CI);
8532
8533       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8534         Constant *One = Context->getConstantInt(In->getType(), 1);
8535         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8536                                                          In->getName()+".not"),
8537                                  CI);
8538       }
8539
8540       return ReplaceInstUsesWith(CI, In);
8541     }
8542       
8543       
8544       
8545     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8546     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8547     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8548     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8549     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8550     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8551     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8552     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8553     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8554         // This only works for EQ and NE
8555         ICI->isEquality()) {
8556       // If Op1C some other power of two, convert:
8557       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8558       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8559       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8560       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8561         
8562       APInt KnownZeroMask(~KnownZero);
8563       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8564         if (!DoXform) return ICI;
8565
8566         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8567         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8568           // (X&4) == 2 --> false
8569           // (X&4) != 2 --> true
8570           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8571           Res = Context->getConstantExprZExt(Res, CI.getType());
8572           return ReplaceInstUsesWith(CI, Res);
8573         }
8574           
8575         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8576         Value *In = ICI->getOperand(0);
8577         if (ShiftAmt) {
8578           // Perform a logical shr by shiftamt.
8579           // Insert the shift to put the result in the low bit.
8580           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8581                               Context->getConstantInt(In->getType(), ShiftAmt),
8582                                                    In->getName()+".lobit"), CI);
8583         }
8584           
8585         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8586           Constant *One = Context->getConstantInt(In->getType(), 1);
8587           In = BinaryOperator::CreateXor(In, One, "tmp");
8588           InsertNewInstBefore(cast<Instruction>(In), CI);
8589         }
8590           
8591         if (CI.getType() == In->getType())
8592           return ReplaceInstUsesWith(CI, In);
8593         else
8594           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8595       }
8596     }
8597   }
8598
8599   return 0;
8600 }
8601
8602 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8603   // If one of the common conversion will work ..
8604   if (Instruction *Result = commonIntCastTransforms(CI))
8605     return Result;
8606
8607   Value *Src = CI.getOperand(0);
8608
8609   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8610   // types and if the sizes are just right we can convert this into a logical
8611   // 'and' which will be much cheaper than the pair of casts.
8612   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8613     // Get the sizes of the types involved.  We know that the intermediate type
8614     // will be smaller than A or C, but don't know the relation between A and C.
8615     Value *A = CSrc->getOperand(0);
8616     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8617     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8618     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8619     // If we're actually extending zero bits, then if
8620     // SrcSize <  DstSize: zext(a & mask)
8621     // SrcSize == DstSize: a & mask
8622     // SrcSize  > DstSize: trunc(a) & mask
8623     if (SrcSize < DstSize) {
8624       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8625       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8626       Instruction *And =
8627         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8628       InsertNewInstBefore(And, CI);
8629       return new ZExtInst(And, CI.getType());
8630     } else if (SrcSize == DstSize) {
8631       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8632       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8633                                                            AndValue));
8634     } else if (SrcSize > DstSize) {
8635       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8636       InsertNewInstBefore(Trunc, CI);
8637       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8638       return BinaryOperator::CreateAnd(Trunc, 
8639                                        Context->getConstantInt(Trunc->getType(),
8640                                                                AndValue));
8641     }
8642   }
8643
8644   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8645     return transformZExtICmp(ICI, CI);
8646
8647   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8648   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8649     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8650     // of the (zext icmp) will be transformed.
8651     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8652     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8653     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8654         (transformZExtICmp(LHS, CI, false) ||
8655          transformZExtICmp(RHS, CI, false))) {
8656       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8657       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8658       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8659     }
8660   }
8661
8662   // zext(trunc(t) & C) -> (t & zext(C)).
8663   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8664     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8665       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8666         Value *TI0 = TI->getOperand(0);
8667         if (TI0->getType() == CI.getType())
8668           return
8669             BinaryOperator::CreateAnd(TI0,
8670                                 Context->getConstantExprZExt(C, CI.getType()));
8671       }
8672
8673   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8674   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8675     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8676       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8677         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8678             And->getOperand(1) == C)
8679           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8680             Value *TI0 = TI->getOperand(0);
8681             if (TI0->getType() == CI.getType()) {
8682               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8683               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8684               InsertNewInstBefore(NewAnd, *And);
8685               return BinaryOperator::CreateXor(NewAnd, ZC);
8686             }
8687           }
8688
8689   return 0;
8690 }
8691
8692 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8693   if (Instruction *I = commonIntCastTransforms(CI))
8694     return I;
8695   
8696   Value *Src = CI.getOperand(0);
8697   
8698   // Canonicalize sign-extend from i1 to a select.
8699   if (Src->getType() == Type::Int1Ty)
8700     return SelectInst::Create(Src,
8701                               Context->getAllOnesValue(CI.getType()),
8702                               Context->getNullValue(CI.getType()));
8703
8704   // See if the value being truncated is already sign extended.  If so, just
8705   // eliminate the trunc/sext pair.
8706   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8707     Value *Op = cast<User>(Src)->getOperand(0);
8708     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8709     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8710     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8711     unsigned NumSignBits = ComputeNumSignBits(Op);
8712
8713     if (OpBits == DestBits) {
8714       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8715       // bits, it is already ready.
8716       if (NumSignBits > DestBits-MidBits)
8717         return ReplaceInstUsesWith(CI, Op);
8718     } else if (OpBits < DestBits) {
8719       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8720       // bits, just sext from i32.
8721       if (NumSignBits > OpBits-MidBits)
8722         return new SExtInst(Op, CI.getType(), "tmp");
8723     } else {
8724       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8725       // bits, just truncate to i32.
8726       if (NumSignBits > OpBits-MidBits)
8727         return new TruncInst(Op, CI.getType(), "tmp");
8728     }
8729   }
8730
8731   // If the input is a shl/ashr pair of a same constant, then this is a sign
8732   // extension from a smaller value.  If we could trust arbitrary bitwidth
8733   // integers, we could turn this into a truncate to the smaller bit and then
8734   // use a sext for the whole extension.  Since we don't, look deeper and check
8735   // for a truncate.  If the source and dest are the same type, eliminate the
8736   // trunc and extend and just do shifts.  For example, turn:
8737   //   %a = trunc i32 %i to i8
8738   //   %b = shl i8 %a, 6
8739   //   %c = ashr i8 %b, 6
8740   //   %d = sext i8 %c to i32
8741   // into:
8742   //   %a = shl i32 %i, 30
8743   //   %d = ashr i32 %a, 30
8744   Value *A = 0;
8745   ConstantInt *BA = 0, *CA = 0;
8746   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8747                         m_ConstantInt(CA)), *Context) &&
8748       BA == CA && isa<TruncInst>(A)) {
8749     Value *I = cast<TruncInst>(A)->getOperand(0);
8750     if (I->getType() == CI.getType()) {
8751       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8752       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8753       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8754       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8755       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8756                                                         CI.getName()), CI);
8757       return BinaryOperator::CreateAShr(I, ShAmtV);
8758     }
8759   }
8760   
8761   return 0;
8762 }
8763
8764 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8765 /// in the specified FP type without changing its value.
8766 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8767                               LLVMContext *Context) {
8768   bool losesInfo;
8769   APFloat F = CFP->getValueAPF();
8770   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8771   if (!losesInfo)
8772     return Context->getConstantFP(F);
8773   return 0;
8774 }
8775
8776 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8777 /// through it until we get the source value.
8778 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8779   if (Instruction *I = dyn_cast<Instruction>(V))
8780     if (I->getOpcode() == Instruction::FPExt)
8781       return LookThroughFPExtensions(I->getOperand(0), Context);
8782   
8783   // If this value is a constant, return the constant in the smallest FP type
8784   // that can accurately represent it.  This allows us to turn
8785   // (float)((double)X+2.0) into x+2.0f.
8786   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8787     if (CFP->getType() == Type::PPC_FP128Ty)
8788       return V;  // No constant folding of this.
8789     // See if the value can be truncated to float and then reextended.
8790     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8791       return V;
8792     if (CFP->getType() == Type::DoubleTy)
8793       return V;  // Won't shrink.
8794     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8795       return V;
8796     // Don't try to shrink to various long double types.
8797   }
8798   
8799   return V;
8800 }
8801
8802 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8803   if (Instruction *I = commonCastTransforms(CI))
8804     return I;
8805   
8806   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8807   // smaller than the destination type, we can eliminate the truncate by doing
8808   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8809   // many builtins (sqrt, etc).
8810   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8811   if (OpI && OpI->hasOneUse()) {
8812     switch (OpI->getOpcode()) {
8813     default: break;
8814     case Instruction::FAdd:
8815     case Instruction::FSub:
8816     case Instruction::FMul:
8817     case Instruction::FDiv:
8818     case Instruction::FRem:
8819       const Type *SrcTy = OpI->getType();
8820       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8821       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8822       if (LHSTrunc->getType() != SrcTy && 
8823           RHSTrunc->getType() != SrcTy) {
8824         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8825         // If the source types were both smaller than the destination type of
8826         // the cast, do this xform.
8827         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8828             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8829           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8830                                       CI.getType(), CI);
8831           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8832                                       CI.getType(), CI);
8833           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8834         }
8835       }
8836       break;  
8837     }
8838   }
8839   return 0;
8840 }
8841
8842 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8843   return commonCastTransforms(CI);
8844 }
8845
8846 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8847   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8848   if (OpI == 0)
8849     return commonCastTransforms(FI);
8850
8851   // fptoui(uitofp(X)) --> X
8852   // fptoui(sitofp(X)) --> X
8853   // This is safe if the intermediate type has enough bits in its mantissa to
8854   // accurately represent all values of X.  For example, do not do this with
8855   // i64->float->i64.  This is also safe for sitofp case, because any negative
8856   // 'X' value would cause an undefined result for the fptoui. 
8857   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8858       OpI->getOperand(0)->getType() == FI.getType() &&
8859       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8860                     OpI->getType()->getFPMantissaWidth())
8861     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8862
8863   return commonCastTransforms(FI);
8864 }
8865
8866 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8867   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8868   if (OpI == 0)
8869     return commonCastTransforms(FI);
8870   
8871   // fptosi(sitofp(X)) --> X
8872   // fptosi(uitofp(X)) --> X
8873   // This is safe if the intermediate type has enough bits in its mantissa to
8874   // accurately represent all values of X.  For example, do not do this with
8875   // i64->float->i64.  This is also safe for sitofp case, because any negative
8876   // 'X' value would cause an undefined result for the fptoui. 
8877   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8878       OpI->getOperand(0)->getType() == FI.getType() &&
8879       (int)FI.getType()->getScalarSizeInBits() <=
8880                     OpI->getType()->getFPMantissaWidth())
8881     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8882   
8883   return commonCastTransforms(FI);
8884 }
8885
8886 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8887   return commonCastTransforms(CI);
8888 }
8889
8890 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8891   return commonCastTransforms(CI);
8892 }
8893
8894 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8895   // If the destination integer type is smaller than the intptr_t type for
8896   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8897   // trunc to be exposed to other transforms.  Don't do this for extending
8898   // ptrtoint's, because we don't know if the target sign or zero extends its
8899   // pointers.
8900   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8901     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8902                                                     TD->getIntPtrType(),
8903                                                     "tmp"), CI);
8904     return new TruncInst(P, CI.getType());
8905   }
8906   
8907   return commonPointerCastTransforms(CI);
8908 }
8909
8910 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8911   // If the source integer type is larger than the intptr_t type for
8912   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8913   // allows the trunc to be exposed to other transforms.  Don't do this for
8914   // extending inttoptr's, because we don't know if the target sign or zero
8915   // extends to pointers.
8916   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8917       TD->getPointerSizeInBits()) {
8918     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8919                                                  TD->getIntPtrType(),
8920                                                  "tmp"), CI);
8921     return new IntToPtrInst(P, CI.getType());
8922   }
8923   
8924   if (Instruction *I = commonCastTransforms(CI))
8925     return I;
8926   
8927   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8928   if (!DestPointee->isSized()) return 0;
8929
8930   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8931   ConstantInt *Cst;
8932   Value *X;
8933   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8934                                     m_ConstantInt(Cst)), *Context)) {
8935     // If the source and destination operands have the same type, see if this
8936     // is a single-index GEP.
8937     if (X->getType() == CI.getType()) {
8938       // Get the size of the pointee type.
8939       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8940
8941       // Convert the constant to intptr type.
8942       APInt Offset = Cst->getValue();
8943       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8944
8945       // If Offset is evenly divisible by Size, we can do this xform.
8946       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8947         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8948         GetElementPtrInst *GEP =
8949           GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8950         // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8951         // potentially overflow, in the absense of further analysis.
8952         cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8953         return GEP;
8954       }
8955     }
8956     // TODO: Could handle other cases, e.g. where add is indexing into field of
8957     // struct etc.
8958   } else if (CI.getOperand(0)->hasOneUse() &&
8959              match(CI.getOperand(0), m_Add(m_Value(X),
8960                    m_ConstantInt(Cst)), *Context)) {
8961     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8962     // "inttoptr+GEP" instead of "add+intptr".
8963     
8964     // Get the size of the pointee type.
8965     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8966     
8967     // Convert the constant to intptr type.
8968     APInt Offset = Cst->getValue();
8969     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8970     
8971     // If Offset is evenly divisible by Size, we can do this xform.
8972     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8973       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8974       
8975       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8976                                                             "tmp"), CI);
8977       GetElementPtrInst *GEP =
8978         GetElementPtrInst::Create(P, Context->getConstantInt(Offset), "tmp");
8979       // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8980       // potentially overflow, in the absense of further analysis.
8981       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8982       return GEP;
8983     }
8984   }
8985   return 0;
8986 }
8987
8988 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8989   // If the operands are integer typed then apply the integer transforms,
8990   // otherwise just apply the common ones.
8991   Value *Src = CI.getOperand(0);
8992   const Type *SrcTy = Src->getType();
8993   const Type *DestTy = CI.getType();
8994
8995   if (isa<PointerType>(SrcTy)) {
8996     if (Instruction *I = commonPointerCastTransforms(CI))
8997       return I;
8998   } else {
8999     if (Instruction *Result = commonCastTransforms(CI))
9000       return Result;
9001   }
9002
9003
9004   // Get rid of casts from one type to the same type. These are useless and can
9005   // be replaced by the operand.
9006   if (DestTy == Src->getType())
9007     return ReplaceInstUsesWith(CI, Src);
9008
9009   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9010     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9011     const Type *DstElTy = DstPTy->getElementType();
9012     const Type *SrcElTy = SrcPTy->getElementType();
9013     
9014     // If the address spaces don't match, don't eliminate the bitcast, which is
9015     // required for changing types.
9016     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9017       return 0;
9018     
9019     // If we are casting a malloc or alloca to a pointer to a type of the same
9020     // size, rewrite the allocation instruction to allocate the "right" type.
9021     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9022       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9023         return V;
9024     
9025     // If the source and destination are pointers, and this cast is equivalent
9026     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9027     // This can enhance SROA and other transforms that want type-safe pointers.
9028     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9029     unsigned NumZeros = 0;
9030     while (SrcElTy != DstElTy && 
9031            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9032            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9033       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9034       ++NumZeros;
9035     }
9036
9037     // If we found a path from the src to dest, create the getelementptr now.
9038     if (SrcElTy == DstElTy) {
9039       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9040       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9041                                        ((Instruction*) NULL));
9042     }
9043   }
9044
9045   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9046     if (SVI->hasOneUse()) {
9047       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9048       // a bitconvert to a vector with the same # elts.
9049       if (isa<VectorType>(DestTy) && 
9050           cast<VectorType>(DestTy)->getNumElements() ==
9051                 SVI->getType()->getNumElements() &&
9052           SVI->getType()->getNumElements() ==
9053             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9054         CastInst *Tmp;
9055         // If either of the operands is a cast from CI.getType(), then
9056         // evaluating the shuffle in the casted destination's type will allow
9057         // us to eliminate at least one cast.
9058         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9059              Tmp->getOperand(0)->getType() == DestTy) ||
9060             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9061              Tmp->getOperand(0)->getType() == DestTy)) {
9062           Value *LHS = InsertCastBefore(Instruction::BitCast,
9063                                         SVI->getOperand(0), DestTy, CI);
9064           Value *RHS = InsertCastBefore(Instruction::BitCast,
9065                                         SVI->getOperand(1), DestTy, CI);
9066           // Return a new shuffle vector.  Use the same element ID's, as we
9067           // know the vector types match #elts.
9068           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9069         }
9070       }
9071     }
9072   }
9073   return 0;
9074 }
9075
9076 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9077 ///   %C = or %A, %B
9078 ///   %D = select %cond, %C, %A
9079 /// into:
9080 ///   %C = select %cond, %B, 0
9081 ///   %D = or %A, %C
9082 ///
9083 /// Assuming that the specified instruction is an operand to the select, return
9084 /// a bitmask indicating which operands of this instruction are foldable if they
9085 /// equal the other incoming value of the select.
9086 ///
9087 static unsigned GetSelectFoldableOperands(Instruction *I) {
9088   switch (I->getOpcode()) {
9089   case Instruction::Add:
9090   case Instruction::Mul:
9091   case Instruction::And:
9092   case Instruction::Or:
9093   case Instruction::Xor:
9094     return 3;              // Can fold through either operand.
9095   case Instruction::Sub:   // Can only fold on the amount subtracted.
9096   case Instruction::Shl:   // Can only fold on the shift amount.
9097   case Instruction::LShr:
9098   case Instruction::AShr:
9099     return 1;
9100   default:
9101     return 0;              // Cannot fold
9102   }
9103 }
9104
9105 /// GetSelectFoldableConstant - For the same transformation as the previous
9106 /// function, return the identity constant that goes into the select.
9107 static Constant *GetSelectFoldableConstant(Instruction *I,
9108                                            LLVMContext *Context) {
9109   switch (I->getOpcode()) {
9110   default: llvm_unreachable("This cannot happen!");
9111   case Instruction::Add:
9112   case Instruction::Sub:
9113   case Instruction::Or:
9114   case Instruction::Xor:
9115   case Instruction::Shl:
9116   case Instruction::LShr:
9117   case Instruction::AShr:
9118     return Context->getNullValue(I->getType());
9119   case Instruction::And:
9120     return Context->getAllOnesValue(I->getType());
9121   case Instruction::Mul:
9122     return Context->getConstantInt(I->getType(), 1);
9123   }
9124 }
9125
9126 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9127 /// have the same opcode and only one use each.  Try to simplify this.
9128 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9129                                           Instruction *FI) {
9130   if (TI->getNumOperands() == 1) {
9131     // If this is a non-volatile load or a cast from the same type,
9132     // merge.
9133     if (TI->isCast()) {
9134       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9135         return 0;
9136     } else {
9137       return 0;  // unknown unary op.
9138     }
9139
9140     // Fold this by inserting a select from the input values.
9141     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9142                                            FI->getOperand(0), SI.getName()+".v");
9143     InsertNewInstBefore(NewSI, SI);
9144     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9145                             TI->getType());
9146   }
9147
9148   // Only handle binary operators here.
9149   if (!isa<BinaryOperator>(TI))
9150     return 0;
9151
9152   // Figure out if the operations have any operands in common.
9153   Value *MatchOp, *OtherOpT, *OtherOpF;
9154   bool MatchIsOpZero;
9155   if (TI->getOperand(0) == FI->getOperand(0)) {
9156     MatchOp  = TI->getOperand(0);
9157     OtherOpT = TI->getOperand(1);
9158     OtherOpF = FI->getOperand(1);
9159     MatchIsOpZero = true;
9160   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9161     MatchOp  = TI->getOperand(1);
9162     OtherOpT = TI->getOperand(0);
9163     OtherOpF = FI->getOperand(0);
9164     MatchIsOpZero = false;
9165   } else if (!TI->isCommutative()) {
9166     return 0;
9167   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9168     MatchOp  = TI->getOperand(0);
9169     OtherOpT = TI->getOperand(1);
9170     OtherOpF = FI->getOperand(0);
9171     MatchIsOpZero = true;
9172   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9173     MatchOp  = TI->getOperand(1);
9174     OtherOpT = TI->getOperand(0);
9175     OtherOpF = FI->getOperand(1);
9176     MatchIsOpZero = true;
9177   } else {
9178     return 0;
9179   }
9180
9181   // If we reach here, they do have operations in common.
9182   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9183                                          OtherOpF, SI.getName()+".v");
9184   InsertNewInstBefore(NewSI, SI);
9185
9186   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9187     if (MatchIsOpZero)
9188       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9189     else
9190       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9191   }
9192   llvm_unreachable("Shouldn't get here");
9193   return 0;
9194 }
9195
9196 static bool isSelect01(Constant *C1, Constant *C2) {
9197   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9198   if (!C1I)
9199     return false;
9200   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9201   if (!C2I)
9202     return false;
9203   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9204 }
9205
9206 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9207 /// facilitate further optimization.
9208 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9209                                             Value *FalseVal) {
9210   // See the comment above GetSelectFoldableOperands for a description of the
9211   // transformation we are doing here.
9212   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9213     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9214         !isa<Constant>(FalseVal)) {
9215       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9216         unsigned OpToFold = 0;
9217         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9218           OpToFold = 1;
9219         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9220           OpToFold = 2;
9221         }
9222
9223         if (OpToFold) {
9224           Constant *C = GetSelectFoldableConstant(TVI, Context);
9225           Value *OOp = TVI->getOperand(2-OpToFold);
9226           // Avoid creating select between 2 constants unless it's selecting
9227           // between 0 and 1.
9228           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9229             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9230             InsertNewInstBefore(NewSel, SI);
9231             NewSel->takeName(TVI);
9232             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9233               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9234             llvm_unreachable("Unknown instruction!!");
9235           }
9236         }
9237       }
9238     }
9239   }
9240
9241   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9242     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9243         !isa<Constant>(TrueVal)) {
9244       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9245         unsigned OpToFold = 0;
9246         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9247           OpToFold = 1;
9248         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9249           OpToFold = 2;
9250         }
9251
9252         if (OpToFold) {
9253           Constant *C = GetSelectFoldableConstant(FVI, Context);
9254           Value *OOp = FVI->getOperand(2-OpToFold);
9255           // Avoid creating select between 2 constants unless it's selecting
9256           // between 0 and 1.
9257           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9258             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9259             InsertNewInstBefore(NewSel, SI);
9260             NewSel->takeName(FVI);
9261             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9262               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9263             llvm_unreachable("Unknown instruction!!");
9264           }
9265         }
9266       }
9267     }
9268   }
9269
9270   return 0;
9271 }
9272
9273 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9274 /// ICmpInst as its first operand.
9275 ///
9276 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9277                                                    ICmpInst *ICI) {
9278   bool Changed = false;
9279   ICmpInst::Predicate Pred = ICI->getPredicate();
9280   Value *CmpLHS = ICI->getOperand(0);
9281   Value *CmpRHS = ICI->getOperand(1);
9282   Value *TrueVal = SI.getTrueValue();
9283   Value *FalseVal = SI.getFalseValue();
9284
9285   // Check cases where the comparison is with a constant that
9286   // can be adjusted to fit the min/max idiom. We may edit ICI in
9287   // place here, so make sure the select is the only user.
9288   if (ICI->hasOneUse())
9289     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9290       switch (Pred) {
9291       default: break;
9292       case ICmpInst::ICMP_ULT:
9293       case ICmpInst::ICMP_SLT: {
9294         // X < MIN ? T : F  -->  F
9295         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9296           return ReplaceInstUsesWith(SI, FalseVal);
9297         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9298         Constant *AdjustedRHS = SubOne(CI, Context);
9299         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9300             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9301           Pred = ICmpInst::getSwappedPredicate(Pred);
9302           CmpRHS = AdjustedRHS;
9303           std::swap(FalseVal, TrueVal);
9304           ICI->setPredicate(Pred);
9305           ICI->setOperand(1, CmpRHS);
9306           SI.setOperand(1, TrueVal);
9307           SI.setOperand(2, FalseVal);
9308           Changed = true;
9309         }
9310         break;
9311       }
9312       case ICmpInst::ICMP_UGT:
9313       case ICmpInst::ICMP_SGT: {
9314         // X > MAX ? T : F  -->  F
9315         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9316           return ReplaceInstUsesWith(SI, FalseVal);
9317         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9318         Constant *AdjustedRHS = AddOne(CI, Context);
9319         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9320             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9321           Pred = ICmpInst::getSwappedPredicate(Pred);
9322           CmpRHS = AdjustedRHS;
9323           std::swap(FalseVal, TrueVal);
9324           ICI->setPredicate(Pred);
9325           ICI->setOperand(1, CmpRHS);
9326           SI.setOperand(1, TrueVal);
9327           SI.setOperand(2, FalseVal);
9328           Changed = true;
9329         }
9330         break;
9331       }
9332       }
9333
9334       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9335       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9336       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9337       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9338           match(FalseVal, m_ConstantInt<0>(), *Context))
9339         Pred = ICI->getPredicate();
9340       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9341                match(FalseVal, m_ConstantInt<-1>(), *Context))
9342         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9343       
9344       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9345         // If we are just checking for a icmp eq of a single bit and zext'ing it
9346         // to an integer, then shift the bit to the appropriate place and then
9347         // cast to integer to avoid the comparison.
9348         const APInt &Op1CV = CI->getValue();
9349     
9350         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9351         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9352         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9353             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9354           Value *In = ICI->getOperand(0);
9355           Value *Sh = Context->getConstantInt(In->getType(),
9356                                        In->getType()->getScalarSizeInBits()-1);
9357           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9358                                                           In->getName()+".lobit"),
9359                                    *ICI);
9360           if (In->getType() != SI.getType())
9361             In = CastInst::CreateIntegerCast(In, SI.getType(),
9362                                              true/*SExt*/, "tmp", ICI);
9363     
9364           if (Pred == ICmpInst::ICMP_SGT)
9365             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9366                                        In->getName()+".not"), *ICI);
9367     
9368           return ReplaceInstUsesWith(SI, In);
9369         }
9370       }
9371     }
9372
9373   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9374     // Transform (X == Y) ? X : Y  -> Y
9375     if (Pred == ICmpInst::ICMP_EQ)
9376       return ReplaceInstUsesWith(SI, FalseVal);
9377     // Transform (X != Y) ? X : Y  -> X
9378     if (Pred == ICmpInst::ICMP_NE)
9379       return ReplaceInstUsesWith(SI, TrueVal);
9380     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9381
9382   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9383     // Transform (X == Y) ? Y : X  -> X
9384     if (Pred == ICmpInst::ICMP_EQ)
9385       return ReplaceInstUsesWith(SI, FalseVal);
9386     // Transform (X != Y) ? Y : X  -> Y
9387     if (Pred == ICmpInst::ICMP_NE)
9388       return ReplaceInstUsesWith(SI, TrueVal);
9389     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9390   }
9391
9392   /// NOTE: if we wanted to, this is where to detect integer ABS
9393
9394   return Changed ? &SI : 0;
9395 }
9396
9397 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9398   Value *CondVal = SI.getCondition();
9399   Value *TrueVal = SI.getTrueValue();
9400   Value *FalseVal = SI.getFalseValue();
9401
9402   // select true, X, Y  -> X
9403   // select false, X, Y -> Y
9404   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9405     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9406
9407   // select C, X, X -> X
9408   if (TrueVal == FalseVal)
9409     return ReplaceInstUsesWith(SI, TrueVal);
9410
9411   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9412     return ReplaceInstUsesWith(SI, FalseVal);
9413   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9414     return ReplaceInstUsesWith(SI, TrueVal);
9415   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9416     if (isa<Constant>(TrueVal))
9417       return ReplaceInstUsesWith(SI, TrueVal);
9418     else
9419       return ReplaceInstUsesWith(SI, FalseVal);
9420   }
9421
9422   if (SI.getType() == Type::Int1Ty) {
9423     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9424       if (C->getZExtValue()) {
9425         // Change: A = select B, true, C --> A = or B, C
9426         return BinaryOperator::CreateOr(CondVal, FalseVal);
9427       } else {
9428         // Change: A = select B, false, C --> A = and !B, C
9429         Value *NotCond =
9430           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9431                                              "not."+CondVal->getName()), SI);
9432         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9433       }
9434     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9435       if (C->getZExtValue() == false) {
9436         // Change: A = select B, C, false --> A = and B, C
9437         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9438       } else {
9439         // Change: A = select B, C, true --> A = or !B, C
9440         Value *NotCond =
9441           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9442                                              "not."+CondVal->getName()), SI);
9443         return BinaryOperator::CreateOr(NotCond, TrueVal);
9444       }
9445     }
9446     
9447     // select a, b, a  -> a&b
9448     // select a, a, b  -> a|b
9449     if (CondVal == TrueVal)
9450       return BinaryOperator::CreateOr(CondVal, FalseVal);
9451     else if (CondVal == FalseVal)
9452       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9453   }
9454
9455   // Selecting between two integer constants?
9456   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9457     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9458       // select C, 1, 0 -> zext C to int
9459       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9460         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9461       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9462         // select C, 0, 1 -> zext !C to int
9463         Value *NotCond =
9464           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9465                                                "not."+CondVal->getName()), SI);
9466         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9467       }
9468
9469       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9470         // If one of the constants is zero (we know they can't both be) and we
9471         // have an icmp instruction with zero, and we have an 'and' with the
9472         // non-constant value, eliminate this whole mess.  This corresponds to
9473         // cases like this: ((X & 27) ? 27 : 0)
9474         if (TrueValC->isZero() || FalseValC->isZero())
9475           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9476               cast<Constant>(IC->getOperand(1))->isNullValue())
9477             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9478               if (ICA->getOpcode() == Instruction::And &&
9479                   isa<ConstantInt>(ICA->getOperand(1)) &&
9480                   (ICA->getOperand(1) == TrueValC ||
9481                    ICA->getOperand(1) == FalseValC) &&
9482                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9483                 // Okay, now we know that everything is set up, we just don't
9484                 // know whether we have a icmp_ne or icmp_eq and whether the 
9485                 // true or false val is the zero.
9486                 bool ShouldNotVal = !TrueValC->isZero();
9487                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9488                 Value *V = ICA;
9489                 if (ShouldNotVal)
9490                   V = InsertNewInstBefore(BinaryOperator::Create(
9491                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9492                 return ReplaceInstUsesWith(SI, V);
9493               }
9494       }
9495     }
9496
9497   // See if we are selecting two values based on a comparison of the two values.
9498   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9499     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9500       // Transform (X == Y) ? X : Y  -> Y
9501       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9502         // This is not safe in general for floating point:  
9503         // consider X== -0, Y== +0.
9504         // It becomes safe if either operand is a nonzero constant.
9505         ConstantFP *CFPt, *CFPf;
9506         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9507               !CFPt->getValueAPF().isZero()) ||
9508             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9509              !CFPf->getValueAPF().isZero()))
9510         return ReplaceInstUsesWith(SI, FalseVal);
9511       }
9512       // Transform (X != Y) ? X : Y  -> X
9513       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9514         return ReplaceInstUsesWith(SI, TrueVal);
9515       // NOTE: if we wanted to, this is where to detect MIN/MAX
9516
9517     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9518       // Transform (X == Y) ? Y : X  -> X
9519       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9520         // This is not safe in general for floating point:  
9521         // consider X== -0, Y== +0.
9522         // It becomes safe if either operand is a nonzero constant.
9523         ConstantFP *CFPt, *CFPf;
9524         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9525               !CFPt->getValueAPF().isZero()) ||
9526             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9527              !CFPf->getValueAPF().isZero()))
9528           return ReplaceInstUsesWith(SI, FalseVal);
9529       }
9530       // Transform (X != Y) ? Y : X  -> Y
9531       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9532         return ReplaceInstUsesWith(SI, TrueVal);
9533       // NOTE: if we wanted to, this is where to detect MIN/MAX
9534     }
9535     // NOTE: if we wanted to, this is where to detect ABS
9536   }
9537
9538   // See if we are selecting two values based on a comparison of the two values.
9539   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9540     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9541       return Result;
9542
9543   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9544     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9545       if (TI->hasOneUse() && FI->hasOneUse()) {
9546         Instruction *AddOp = 0, *SubOp = 0;
9547
9548         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9549         if (TI->getOpcode() == FI->getOpcode())
9550           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9551             return IV;
9552
9553         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9554         // even legal for FP.
9555         if ((TI->getOpcode() == Instruction::Sub &&
9556              FI->getOpcode() == Instruction::Add) ||
9557             (TI->getOpcode() == Instruction::FSub &&
9558              FI->getOpcode() == Instruction::FAdd)) {
9559           AddOp = FI; SubOp = TI;
9560         } else if ((FI->getOpcode() == Instruction::Sub &&
9561                     TI->getOpcode() == Instruction::Add) ||
9562                    (FI->getOpcode() == Instruction::FSub &&
9563                     TI->getOpcode() == Instruction::FAdd)) {
9564           AddOp = TI; SubOp = FI;
9565         }
9566
9567         if (AddOp) {
9568           Value *OtherAddOp = 0;
9569           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9570             OtherAddOp = AddOp->getOperand(1);
9571           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9572             OtherAddOp = AddOp->getOperand(0);
9573           }
9574
9575           if (OtherAddOp) {
9576             // So at this point we know we have (Y -> OtherAddOp):
9577             //        select C, (add X, Y), (sub X, Z)
9578             Value *NegVal;  // Compute -Z
9579             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9580               NegVal = Context->getConstantExprNeg(C);
9581             } else {
9582               NegVal = InsertNewInstBefore(
9583                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9584                                               "tmp"), SI);
9585             }
9586
9587             Value *NewTrueOp = OtherAddOp;
9588             Value *NewFalseOp = NegVal;
9589             if (AddOp != TI)
9590               std::swap(NewTrueOp, NewFalseOp);
9591             Instruction *NewSel =
9592               SelectInst::Create(CondVal, NewTrueOp,
9593                                  NewFalseOp, SI.getName() + ".p");
9594
9595             NewSel = InsertNewInstBefore(NewSel, SI);
9596             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9597           }
9598         }
9599       }
9600
9601   // See if we can fold the select into one of our operands.
9602   if (SI.getType()->isInteger()) {
9603     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9604     if (FoldI)
9605       return FoldI;
9606   }
9607
9608   if (BinaryOperator::isNot(CondVal)) {
9609     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9610     SI.setOperand(1, FalseVal);
9611     SI.setOperand(2, TrueVal);
9612     return &SI;
9613   }
9614
9615   return 0;
9616 }
9617
9618 /// EnforceKnownAlignment - If the specified pointer points to an object that
9619 /// we control, modify the object's alignment to PrefAlign. This isn't
9620 /// often possible though. If alignment is important, a more reliable approach
9621 /// is to simply align all global variables and allocation instructions to
9622 /// their preferred alignment from the beginning.
9623 ///
9624 static unsigned EnforceKnownAlignment(Value *V,
9625                                       unsigned Align, unsigned PrefAlign) {
9626
9627   User *U = dyn_cast<User>(V);
9628   if (!U) return Align;
9629
9630   switch (Operator::getOpcode(U)) {
9631   default: break;
9632   case Instruction::BitCast:
9633     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9634   case Instruction::GetElementPtr: {
9635     // If all indexes are zero, it is just the alignment of the base pointer.
9636     bool AllZeroOperands = true;
9637     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9638       if (!isa<Constant>(*i) ||
9639           !cast<Constant>(*i)->isNullValue()) {
9640         AllZeroOperands = false;
9641         break;
9642       }
9643
9644     if (AllZeroOperands) {
9645       // Treat this like a bitcast.
9646       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9647     }
9648     break;
9649   }
9650   }
9651
9652   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9653     // If there is a large requested alignment and we can, bump up the alignment
9654     // of the global.
9655     if (!GV->isDeclaration()) {
9656       if (GV->getAlignment() >= PrefAlign)
9657         Align = GV->getAlignment();
9658       else {
9659         GV->setAlignment(PrefAlign);
9660         Align = PrefAlign;
9661       }
9662     }
9663   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9664     // If there is a requested alignment and if this is an alloca, round up.  We
9665     // don't do this for malloc, because some systems can't respect the request.
9666     if (isa<AllocaInst>(AI)) {
9667       if (AI->getAlignment() >= PrefAlign)
9668         Align = AI->getAlignment();
9669       else {
9670         AI->setAlignment(PrefAlign);
9671         Align = PrefAlign;
9672       }
9673     }
9674   }
9675
9676   return Align;
9677 }
9678
9679 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9680 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9681 /// and it is more than the alignment of the ultimate object, see if we can
9682 /// increase the alignment of the ultimate object, making this check succeed.
9683 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9684                                                   unsigned PrefAlign) {
9685   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9686                       sizeof(PrefAlign) * CHAR_BIT;
9687   APInt Mask = APInt::getAllOnesValue(BitWidth);
9688   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9689   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9690   unsigned TrailZ = KnownZero.countTrailingOnes();
9691   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9692
9693   if (PrefAlign > Align)
9694     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9695   
9696     // We don't need to make any adjustment.
9697   return Align;
9698 }
9699
9700 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9701   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9702   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9703   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9704   unsigned CopyAlign = MI->getAlignment();
9705
9706   if (CopyAlign < MinAlign) {
9707     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9708                                              MinAlign, false));
9709     return MI;
9710   }
9711   
9712   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9713   // load/store.
9714   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9715   if (MemOpLength == 0) return 0;
9716   
9717   // Source and destination pointer types are always "i8*" for intrinsic.  See
9718   // if the size is something we can handle with a single primitive load/store.
9719   // A single load+store correctly handles overlapping memory in the memmove
9720   // case.
9721   unsigned Size = MemOpLength->getZExtValue();
9722   if (Size == 0) return MI;  // Delete this mem transfer.
9723   
9724   if (Size > 8 || (Size&(Size-1)))
9725     return 0;  // If not 1/2/4/8 bytes, exit.
9726   
9727   // Use an integer load+store unless we can find something better.
9728   Type *NewPtrTy =
9729                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9730   
9731   // Memcpy forces the use of i8* for the source and destination.  That means
9732   // that if you're using memcpy to move one double around, you'll get a cast
9733   // from double* to i8*.  We'd much rather use a double load+store rather than
9734   // an i64 load+store, here because this improves the odds that the source or
9735   // dest address will be promotable.  See if we can find a better type than the
9736   // integer datatype.
9737   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9738     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9739     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9740       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9741       // down through these levels if so.
9742       while (!SrcETy->isSingleValueType()) {
9743         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9744           if (STy->getNumElements() == 1)
9745             SrcETy = STy->getElementType(0);
9746           else
9747             break;
9748         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9749           if (ATy->getNumElements() == 1)
9750             SrcETy = ATy->getElementType();
9751           else
9752             break;
9753         } else
9754           break;
9755       }
9756       
9757       if (SrcETy->isSingleValueType())
9758         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9759     }
9760   }
9761   
9762   
9763   // If the memcpy/memmove provides better alignment info than we can
9764   // infer, use it.
9765   SrcAlign = std::max(SrcAlign, CopyAlign);
9766   DstAlign = std::max(DstAlign, CopyAlign);
9767   
9768   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9769   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9770   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9771   InsertNewInstBefore(L, *MI);
9772   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9773
9774   // Set the size of the copy to 0, it will be deleted on the next iteration.
9775   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9776   return MI;
9777 }
9778
9779 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9780   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9781   if (MI->getAlignment() < Alignment) {
9782     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9783                                              Alignment, false));
9784     return MI;
9785   }
9786   
9787   // Extract the length and alignment and fill if they are constant.
9788   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9789   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9790   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9791     return 0;
9792   uint64_t Len = LenC->getZExtValue();
9793   Alignment = MI->getAlignment();
9794   
9795   // If the length is zero, this is a no-op
9796   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9797   
9798   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9799   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9800     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9801     
9802     Value *Dest = MI->getDest();
9803     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9804
9805     // Alignment 0 is identity for alignment 1 for memset, but not store.
9806     if (Alignment == 0) Alignment = 1;
9807     
9808     // Extract the fill value and store.
9809     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9810     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9811                                       Dest, false, Alignment), *MI);
9812     
9813     // Set the size of the copy to 0, it will be deleted on the next iteration.
9814     MI->setLength(Context->getNullValue(LenC->getType()));
9815     return MI;
9816   }
9817
9818   return 0;
9819 }
9820
9821
9822 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9823 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9824 /// the heavy lifting.
9825 ///
9826 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9827   // If the caller function is nounwind, mark the call as nounwind, even if the
9828   // callee isn't.
9829   if (CI.getParent()->getParent()->doesNotThrow() &&
9830       !CI.doesNotThrow()) {
9831     CI.setDoesNotThrow();
9832     return &CI;
9833   }
9834   
9835   
9836   
9837   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9838   if (!II) return visitCallSite(&CI);
9839   
9840   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9841   // visitCallSite.
9842   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9843     bool Changed = false;
9844
9845     // memmove/cpy/set of zero bytes is a noop.
9846     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9847       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9848
9849       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9850         if (CI->getZExtValue() == 1) {
9851           // Replace the instruction with just byte operations.  We would
9852           // transform other cases to loads/stores, but we don't know if
9853           // alignment is sufficient.
9854         }
9855     }
9856
9857     // If we have a memmove and the source operation is a constant global,
9858     // then the source and dest pointers can't alias, so we can change this
9859     // into a call to memcpy.
9860     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9861       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9862         if (GVSrc->isConstant()) {
9863           Module *M = CI.getParent()->getParent()->getParent();
9864           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9865           const Type *Tys[1];
9866           Tys[0] = CI.getOperand(3)->getType();
9867           CI.setOperand(0, 
9868                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9869           Changed = true;
9870         }
9871
9872       // memmove(x,x,size) -> noop.
9873       if (MMI->getSource() == MMI->getDest())
9874         return EraseInstFromFunction(CI);
9875     }
9876
9877     // If we can determine a pointer alignment that is bigger than currently
9878     // set, update the alignment.
9879     if (isa<MemTransferInst>(MI)) {
9880       if (Instruction *I = SimplifyMemTransfer(MI))
9881         return I;
9882     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9883       if (Instruction *I = SimplifyMemSet(MSI))
9884         return I;
9885     }
9886           
9887     if (Changed) return II;
9888   }
9889   
9890   switch (II->getIntrinsicID()) {
9891   default: break;
9892   case Intrinsic::bswap:
9893     // bswap(bswap(x)) -> x
9894     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9895       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9896         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9897     break;
9898   case Intrinsic::ppc_altivec_lvx:
9899   case Intrinsic::ppc_altivec_lvxl:
9900   case Intrinsic::x86_sse_loadu_ps:
9901   case Intrinsic::x86_sse2_loadu_pd:
9902   case Intrinsic::x86_sse2_loadu_dq:
9903     // Turn PPC lvx     -> load if the pointer is known aligned.
9904     // Turn X86 loadups -> load if the pointer is known aligned.
9905     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9906       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9907                                    Context->getPointerTypeUnqual(II->getType()),
9908                                        CI);
9909       return new LoadInst(Ptr);
9910     }
9911     break;
9912   case Intrinsic::ppc_altivec_stvx:
9913   case Intrinsic::ppc_altivec_stvxl:
9914     // Turn stvx -> store if the pointer is known aligned.
9915     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9916       const Type *OpPtrTy = 
9917         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9918       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9919       return new StoreInst(II->getOperand(1), Ptr);
9920     }
9921     break;
9922   case Intrinsic::x86_sse_storeu_ps:
9923   case Intrinsic::x86_sse2_storeu_pd:
9924   case Intrinsic::x86_sse2_storeu_dq:
9925     // Turn X86 storeu -> store if the pointer is known aligned.
9926     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9927       const Type *OpPtrTy = 
9928         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9929       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9930       return new StoreInst(II->getOperand(2), Ptr);
9931     }
9932     break;
9933     
9934   case Intrinsic::x86_sse_cvttss2si: {
9935     // These intrinsics only demands the 0th element of its input vector.  If
9936     // we can simplify the input based on that, do so now.
9937     unsigned VWidth =
9938       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9939     APInt DemandedElts(VWidth, 1);
9940     APInt UndefElts(VWidth, 0);
9941     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9942                                               UndefElts)) {
9943       II->setOperand(1, V);
9944       return II;
9945     }
9946     break;
9947   }
9948     
9949   case Intrinsic::ppc_altivec_vperm:
9950     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9951     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9952       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9953       
9954       // Check that all of the elements are integer constants or undefs.
9955       bool AllEltsOk = true;
9956       for (unsigned i = 0; i != 16; ++i) {
9957         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9958             !isa<UndefValue>(Mask->getOperand(i))) {
9959           AllEltsOk = false;
9960           break;
9961         }
9962       }
9963       
9964       if (AllEltsOk) {
9965         // Cast the input vectors to byte vectors.
9966         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9967         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9968         Value *Result = Context->getUndef(Op0->getType());
9969         
9970         // Only extract each element once.
9971         Value *ExtractedElts[32];
9972         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9973         
9974         for (unsigned i = 0; i != 16; ++i) {
9975           if (isa<UndefValue>(Mask->getOperand(i)))
9976             continue;
9977           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9978           Idx &= 31;  // Match the hardware behavior.
9979           
9980           if (ExtractedElts[Idx] == 0) {
9981             Instruction *Elt = 
9982               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9983                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9984             InsertNewInstBefore(Elt, CI);
9985             ExtractedElts[Idx] = Elt;
9986           }
9987         
9988           // Insert this value into the result vector.
9989           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9990                                Context->getConstantInt(Type::Int32Ty, i, false), 
9991                                "tmp");
9992           InsertNewInstBefore(cast<Instruction>(Result), CI);
9993         }
9994         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9995       }
9996     }
9997     break;
9998
9999   case Intrinsic::stackrestore: {
10000     // If the save is right next to the restore, remove the restore.  This can
10001     // happen when variable allocas are DCE'd.
10002     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10003       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10004         BasicBlock::iterator BI = SS;
10005         if (&*++BI == II)
10006           return EraseInstFromFunction(CI);
10007       }
10008     }
10009     
10010     // Scan down this block to see if there is another stack restore in the
10011     // same block without an intervening call/alloca.
10012     BasicBlock::iterator BI = II;
10013     TerminatorInst *TI = II->getParent()->getTerminator();
10014     bool CannotRemove = false;
10015     for (++BI; &*BI != TI; ++BI) {
10016       if (isa<AllocaInst>(BI)) {
10017         CannotRemove = true;
10018         break;
10019       }
10020       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10021         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10022           // If there is a stackrestore below this one, remove this one.
10023           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10024             return EraseInstFromFunction(CI);
10025           // Otherwise, ignore the intrinsic.
10026         } else {
10027           // If we found a non-intrinsic call, we can't remove the stack
10028           // restore.
10029           CannotRemove = true;
10030           break;
10031         }
10032       }
10033     }
10034     
10035     // If the stack restore is in a return/unwind block and if there are no
10036     // allocas or calls between the restore and the return, nuke the restore.
10037     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10038       return EraseInstFromFunction(CI);
10039     break;
10040   }
10041   }
10042
10043   return visitCallSite(II);
10044 }
10045
10046 // InvokeInst simplification
10047 //
10048 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10049   return visitCallSite(&II);
10050 }
10051
10052 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10053 /// passed through the varargs area, we can eliminate the use of the cast.
10054 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10055                                          const CastInst * const CI,
10056                                          const TargetData * const TD,
10057                                          const int ix) {
10058   if (!CI->isLosslessCast())
10059     return false;
10060
10061   // The size of ByVal arguments is derived from the type, so we
10062   // can't change to a type with a different size.  If the size were
10063   // passed explicitly we could avoid this check.
10064   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10065     return true;
10066
10067   const Type* SrcTy = 
10068             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10069   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10070   if (!SrcTy->isSized() || !DstTy->isSized())
10071     return false;
10072   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10073     return false;
10074   return true;
10075 }
10076
10077 // visitCallSite - Improvements for call and invoke instructions.
10078 //
10079 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10080   bool Changed = false;
10081
10082   // If the callee is a constexpr cast of a function, attempt to move the cast
10083   // to the arguments of the call/invoke.
10084   if (transformConstExprCastCall(CS)) return 0;
10085
10086   Value *Callee = CS.getCalledValue();
10087
10088   if (Function *CalleeF = dyn_cast<Function>(Callee))
10089     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10090       Instruction *OldCall = CS.getInstruction();
10091       // If the call and callee calling conventions don't match, this call must
10092       // be unreachable, as the call is undefined.
10093       new StoreInst(Context->getConstantIntTrue(),
10094                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10095                                   OldCall);
10096       if (!OldCall->use_empty())
10097         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10098       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10099         return EraseInstFromFunction(*OldCall);
10100       return 0;
10101     }
10102
10103   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10104     // This instruction is not reachable, just remove it.  We insert a store to
10105     // undef so that we know that this code is not reachable, despite the fact
10106     // that we can't modify the CFG here.
10107     new StoreInst(Context->getConstantIntTrue(),
10108                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10109                   CS.getInstruction());
10110
10111     if (!CS.getInstruction()->use_empty())
10112       CS.getInstruction()->
10113         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10114
10115     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10116       // Don't break the CFG, insert a dummy cond branch.
10117       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10118                          Context->getConstantIntTrue(), II);
10119     }
10120     return EraseInstFromFunction(*CS.getInstruction());
10121   }
10122
10123   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10124     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10125       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10126         return transformCallThroughTrampoline(CS);
10127
10128   const PointerType *PTy = cast<PointerType>(Callee->getType());
10129   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10130   if (FTy->isVarArg()) {
10131     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10132     // See if we can optimize any arguments passed through the varargs area of
10133     // the call.
10134     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10135            E = CS.arg_end(); I != E; ++I, ++ix) {
10136       CastInst *CI = dyn_cast<CastInst>(*I);
10137       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10138         *I = CI->getOperand(0);
10139         Changed = true;
10140       }
10141     }
10142   }
10143
10144   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10145     // Inline asm calls cannot throw - mark them 'nounwind'.
10146     CS.setDoesNotThrow();
10147     Changed = true;
10148   }
10149
10150   return Changed ? CS.getInstruction() : 0;
10151 }
10152
10153 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10154 // attempt to move the cast to the arguments of the call/invoke.
10155 //
10156 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10157   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10158   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10159   if (CE->getOpcode() != Instruction::BitCast || 
10160       !isa<Function>(CE->getOperand(0)))
10161     return false;
10162   Function *Callee = cast<Function>(CE->getOperand(0));
10163   Instruction *Caller = CS.getInstruction();
10164   const AttrListPtr &CallerPAL = CS.getAttributes();
10165
10166   // Okay, this is a cast from a function to a different type.  Unless doing so
10167   // would cause a type conversion of one of our arguments, change this call to
10168   // be a direct call with arguments casted to the appropriate types.
10169   //
10170   const FunctionType *FT = Callee->getFunctionType();
10171   const Type *OldRetTy = Caller->getType();
10172   const Type *NewRetTy = FT->getReturnType();
10173
10174   if (isa<StructType>(NewRetTy))
10175     return false; // TODO: Handle multiple return values.
10176
10177   // Check to see if we are changing the return type...
10178   if (OldRetTy != NewRetTy) {
10179     if (Callee->isDeclaration() &&
10180         // Conversion is ok if changing from one pointer type to another or from
10181         // a pointer to an integer of the same size.
10182         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10183           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10184       return false;   // Cannot transform this return value.
10185
10186     if (!Caller->use_empty() &&
10187         // void -> non-void is handled specially
10188         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10189       return false;   // Cannot transform this return value.
10190
10191     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10192       Attributes RAttrs = CallerPAL.getRetAttributes();
10193       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10194         return false;   // Attribute not compatible with transformed value.
10195     }
10196
10197     // If the callsite is an invoke instruction, and the return value is used by
10198     // a PHI node in a successor, we cannot change the return type of the call
10199     // because there is no place to put the cast instruction (without breaking
10200     // the critical edge).  Bail out in this case.
10201     if (!Caller->use_empty())
10202       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10203         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10204              UI != E; ++UI)
10205           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10206             if (PN->getParent() == II->getNormalDest() ||
10207                 PN->getParent() == II->getUnwindDest())
10208               return false;
10209   }
10210
10211   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10212   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10213
10214   CallSite::arg_iterator AI = CS.arg_begin();
10215   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10216     const Type *ParamTy = FT->getParamType(i);
10217     const Type *ActTy = (*AI)->getType();
10218
10219     if (!CastInst::isCastable(ActTy, ParamTy))
10220       return false;   // Cannot transform this parameter value.
10221
10222     if (CallerPAL.getParamAttributes(i + 1) 
10223         & Attribute::typeIncompatible(ParamTy))
10224       return false;   // Attribute not compatible with transformed value.
10225
10226     // Converting from one pointer type to another or between a pointer and an
10227     // integer of the same size is safe even if we do not have a body.
10228     bool isConvertible = ActTy == ParamTy ||
10229       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10230        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10231     if (Callee->isDeclaration() && !isConvertible) return false;
10232   }
10233
10234   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10235       Callee->isDeclaration())
10236     return false;   // Do not delete arguments unless we have a function body.
10237
10238   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10239       !CallerPAL.isEmpty())
10240     // In this case we have more arguments than the new function type, but we
10241     // won't be dropping them.  Check that these extra arguments have attributes
10242     // that are compatible with being a vararg call argument.
10243     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10244       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10245         break;
10246       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10247       if (PAttrs & Attribute::VarArgsIncompatible)
10248         return false;
10249     }
10250
10251   // Okay, we decided that this is a safe thing to do: go ahead and start
10252   // inserting cast instructions as necessary...
10253   std::vector<Value*> Args;
10254   Args.reserve(NumActualArgs);
10255   SmallVector<AttributeWithIndex, 8> attrVec;
10256   attrVec.reserve(NumCommonArgs);
10257
10258   // Get any return attributes.
10259   Attributes RAttrs = CallerPAL.getRetAttributes();
10260
10261   // If the return value is not being used, the type may not be compatible
10262   // with the existing attributes.  Wipe out any problematic attributes.
10263   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10264
10265   // Add the new return attributes.
10266   if (RAttrs)
10267     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10268
10269   AI = CS.arg_begin();
10270   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10271     const Type *ParamTy = FT->getParamType(i);
10272     if ((*AI)->getType() == ParamTy) {
10273       Args.push_back(*AI);
10274     } else {
10275       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10276           false, ParamTy, false);
10277       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10278       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10279     }
10280
10281     // Add any parameter attributes.
10282     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10283       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10284   }
10285
10286   // If the function takes more arguments than the call was taking, add them
10287   // now...
10288   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10289     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10290
10291   // If we are removing arguments to the function, emit an obnoxious warning...
10292   if (FT->getNumParams() < NumActualArgs) {
10293     if (!FT->isVarArg()) {
10294       cerr << "WARNING: While resolving call to function '"
10295            << Callee->getName() << "' arguments were dropped!\n";
10296     } else {
10297       // Add all of the arguments in their promoted form to the arg list...
10298       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10299         const Type *PTy = getPromotedType((*AI)->getType());
10300         if (PTy != (*AI)->getType()) {
10301           // Must promote to pass through va_arg area!
10302           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10303                                                                 PTy, false);
10304           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10305           InsertNewInstBefore(Cast, *Caller);
10306           Args.push_back(Cast);
10307         } else {
10308           Args.push_back(*AI);
10309         }
10310
10311         // Add any parameter attributes.
10312         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10313           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10314       }
10315     }
10316   }
10317
10318   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10319     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10320
10321   if (NewRetTy == Type::VoidTy)
10322     Caller->setName("");   // Void type should not have a name.
10323
10324   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10325
10326   Instruction *NC;
10327   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10328     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10329                             Args.begin(), Args.end(),
10330                             Caller->getName(), Caller);
10331     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10332     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10333   } else {
10334     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10335                           Caller->getName(), Caller);
10336     CallInst *CI = cast<CallInst>(Caller);
10337     if (CI->isTailCall())
10338       cast<CallInst>(NC)->setTailCall();
10339     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10340     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10341   }
10342
10343   // Insert a cast of the return type as necessary.
10344   Value *NV = NC;
10345   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10346     if (NV->getType() != Type::VoidTy) {
10347       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10348                                                             OldRetTy, false);
10349       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10350
10351       // If this is an invoke instruction, we should insert it after the first
10352       // non-phi, instruction in the normal successor block.
10353       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10354         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10355         InsertNewInstBefore(NC, *I);
10356       } else {
10357         // Otherwise, it's a call, just insert cast right after the call instr
10358         InsertNewInstBefore(NC, *Caller);
10359       }
10360       AddUsersToWorkList(*Caller);
10361     } else {
10362       NV = Context->getUndef(Caller->getType());
10363     }
10364   }
10365
10366   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10367     Caller->replaceAllUsesWith(NV);
10368   Caller->eraseFromParent();
10369   RemoveFromWorkList(Caller);
10370   return true;
10371 }
10372
10373 // transformCallThroughTrampoline - Turn a call to a function created by the
10374 // init_trampoline intrinsic into a direct call to the underlying function.
10375 //
10376 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10377   Value *Callee = CS.getCalledValue();
10378   const PointerType *PTy = cast<PointerType>(Callee->getType());
10379   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10380   const AttrListPtr &Attrs = CS.getAttributes();
10381
10382   // If the call already has the 'nest' attribute somewhere then give up -
10383   // otherwise 'nest' would occur twice after splicing in the chain.
10384   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10385     return 0;
10386
10387   IntrinsicInst *Tramp =
10388     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10389
10390   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10391   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10392   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10393
10394   const AttrListPtr &NestAttrs = NestF->getAttributes();
10395   if (!NestAttrs.isEmpty()) {
10396     unsigned NestIdx = 1;
10397     const Type *NestTy = 0;
10398     Attributes NestAttr = Attribute::None;
10399
10400     // Look for a parameter marked with the 'nest' attribute.
10401     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10402          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10403       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10404         // Record the parameter type and any other attributes.
10405         NestTy = *I;
10406         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10407         break;
10408       }
10409
10410     if (NestTy) {
10411       Instruction *Caller = CS.getInstruction();
10412       std::vector<Value*> NewArgs;
10413       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10414
10415       SmallVector<AttributeWithIndex, 8> NewAttrs;
10416       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10417
10418       // Insert the nest argument into the call argument list, which may
10419       // mean appending it.  Likewise for attributes.
10420
10421       // Add any result attributes.
10422       if (Attributes Attr = Attrs.getRetAttributes())
10423         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10424
10425       {
10426         unsigned Idx = 1;
10427         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10428         do {
10429           if (Idx == NestIdx) {
10430             // Add the chain argument and attributes.
10431             Value *NestVal = Tramp->getOperand(3);
10432             if (NestVal->getType() != NestTy)
10433               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10434             NewArgs.push_back(NestVal);
10435             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10436           }
10437
10438           if (I == E)
10439             break;
10440
10441           // Add the original argument and attributes.
10442           NewArgs.push_back(*I);
10443           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10444             NewAttrs.push_back
10445               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10446
10447           ++Idx, ++I;
10448         } while (1);
10449       }
10450
10451       // Add any function attributes.
10452       if (Attributes Attr = Attrs.getFnAttributes())
10453         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10454
10455       // The trampoline may have been bitcast to a bogus type (FTy).
10456       // Handle this by synthesizing a new function type, equal to FTy
10457       // with the chain parameter inserted.
10458
10459       std::vector<const Type*> NewTypes;
10460       NewTypes.reserve(FTy->getNumParams()+1);
10461
10462       // Insert the chain's type into the list of parameter types, which may
10463       // mean appending it.
10464       {
10465         unsigned Idx = 1;
10466         FunctionType::param_iterator I = FTy->param_begin(),
10467           E = FTy->param_end();
10468
10469         do {
10470           if (Idx == NestIdx)
10471             // Add the chain's type.
10472             NewTypes.push_back(NestTy);
10473
10474           if (I == E)
10475             break;
10476
10477           // Add the original type.
10478           NewTypes.push_back(*I);
10479
10480           ++Idx, ++I;
10481         } while (1);
10482       }
10483
10484       // Replace the trampoline call with a direct call.  Let the generic
10485       // code sort out any function type mismatches.
10486       FunctionType *NewFTy =
10487                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10488                                                 FTy->isVarArg());
10489       Constant *NewCallee =
10490         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10491         NestF : Context->getConstantExprBitCast(NestF, 
10492                                          Context->getPointerTypeUnqual(NewFTy));
10493       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10494
10495       Instruction *NewCaller;
10496       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10497         NewCaller = InvokeInst::Create(NewCallee,
10498                                        II->getNormalDest(), II->getUnwindDest(),
10499                                        NewArgs.begin(), NewArgs.end(),
10500                                        Caller->getName(), Caller);
10501         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10502         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10503       } else {
10504         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10505                                      Caller->getName(), Caller);
10506         if (cast<CallInst>(Caller)->isTailCall())
10507           cast<CallInst>(NewCaller)->setTailCall();
10508         cast<CallInst>(NewCaller)->
10509           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10510         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10511       }
10512       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10513         Caller->replaceAllUsesWith(NewCaller);
10514       Caller->eraseFromParent();
10515       RemoveFromWorkList(Caller);
10516       return 0;
10517     }
10518   }
10519
10520   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10521   // parameter, there is no need to adjust the argument list.  Let the generic
10522   // code sort out any function type mismatches.
10523   Constant *NewCallee =
10524     NestF->getType() == PTy ? NestF : 
10525                               Context->getConstantExprBitCast(NestF, PTy);
10526   CS.setCalledFunction(NewCallee);
10527   return CS.getInstruction();
10528 }
10529
10530 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10531 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10532 /// and a single binop.
10533 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10534   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10535   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10536   unsigned Opc = FirstInst->getOpcode();
10537   Value *LHSVal = FirstInst->getOperand(0);
10538   Value *RHSVal = FirstInst->getOperand(1);
10539     
10540   const Type *LHSType = LHSVal->getType();
10541   const Type *RHSType = RHSVal->getType();
10542   
10543   // Scan to see if all operands are the same opcode, all have one use, and all
10544   // kill their operands (i.e. the operands have one use).
10545   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10546     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10547     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10548         // Verify type of the LHS matches so we don't fold cmp's of different
10549         // types or GEP's with different index types.
10550         I->getOperand(0)->getType() != LHSType ||
10551         I->getOperand(1)->getType() != RHSType)
10552       return 0;
10553
10554     // If they are CmpInst instructions, check their predicates
10555     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10556       if (cast<CmpInst>(I)->getPredicate() !=
10557           cast<CmpInst>(FirstInst)->getPredicate())
10558         return 0;
10559     
10560     // Keep track of which operand needs a phi node.
10561     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10562     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10563   }
10564   
10565   // Otherwise, this is safe to transform!
10566   
10567   Value *InLHS = FirstInst->getOperand(0);
10568   Value *InRHS = FirstInst->getOperand(1);
10569   PHINode *NewLHS = 0, *NewRHS = 0;
10570   if (LHSVal == 0) {
10571     NewLHS = PHINode::Create(LHSType,
10572                              FirstInst->getOperand(0)->getName() + ".pn");
10573     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10574     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10575     InsertNewInstBefore(NewLHS, PN);
10576     LHSVal = NewLHS;
10577   }
10578   
10579   if (RHSVal == 0) {
10580     NewRHS = PHINode::Create(RHSType,
10581                              FirstInst->getOperand(1)->getName() + ".pn");
10582     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10583     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10584     InsertNewInstBefore(NewRHS, PN);
10585     RHSVal = NewRHS;
10586   }
10587   
10588   // Add all operands to the new PHIs.
10589   if (NewLHS || NewRHS) {
10590     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10591       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10592       if (NewLHS) {
10593         Value *NewInLHS = InInst->getOperand(0);
10594         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10595       }
10596       if (NewRHS) {
10597         Value *NewInRHS = InInst->getOperand(1);
10598         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10599       }
10600     }
10601   }
10602     
10603   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10604     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10605   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10606   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10607                          LHSVal, RHSVal);
10608 }
10609
10610 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10611   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10612   
10613   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10614                                         FirstInst->op_end());
10615   // This is true if all GEP bases are allocas and if all indices into them are
10616   // constants.
10617   bool AllBasePointersAreAllocas = true;
10618   
10619   // Scan to see if all operands are the same opcode, all have one use, and all
10620   // kill their operands (i.e. the operands have one use).
10621   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10622     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10623     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10624       GEP->getNumOperands() != FirstInst->getNumOperands())
10625       return 0;
10626
10627     // Keep track of whether or not all GEPs are of alloca pointers.
10628     if (AllBasePointersAreAllocas &&
10629         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10630          !GEP->hasAllConstantIndices()))
10631       AllBasePointersAreAllocas = false;
10632     
10633     // Compare the operand lists.
10634     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10635       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10636         continue;
10637       
10638       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10639       // if one of the PHIs has a constant for the index.  The index may be
10640       // substantially cheaper to compute for the constants, so making it a
10641       // variable index could pessimize the path.  This also handles the case
10642       // for struct indices, which must always be constant.
10643       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10644           isa<ConstantInt>(GEP->getOperand(op)))
10645         return 0;
10646       
10647       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10648         return 0;
10649       FixedOperands[op] = 0;  // Needs a PHI.
10650     }
10651   }
10652   
10653   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10654   // bother doing this transformation.  At best, this will just save a bit of
10655   // offset calculation, but all the predecessors will have to materialize the
10656   // stack address into a register anyway.  We'd actually rather *clone* the
10657   // load up into the predecessors so that we have a load of a gep of an alloca,
10658   // which can usually all be folded into the load.
10659   if (AllBasePointersAreAllocas)
10660     return 0;
10661   
10662   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10663   // that is variable.
10664   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10665   
10666   bool HasAnyPHIs = false;
10667   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10668     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10669     Value *FirstOp = FirstInst->getOperand(i);
10670     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10671                                      FirstOp->getName()+".pn");
10672     InsertNewInstBefore(NewPN, PN);
10673     
10674     NewPN->reserveOperandSpace(e);
10675     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10676     OperandPhis[i] = NewPN;
10677     FixedOperands[i] = NewPN;
10678     HasAnyPHIs = true;
10679   }
10680
10681   
10682   // Add all operands to the new PHIs.
10683   if (HasAnyPHIs) {
10684     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10685       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10686       BasicBlock *InBB = PN.getIncomingBlock(i);
10687       
10688       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10689         if (PHINode *OpPhi = OperandPhis[op])
10690           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10691     }
10692   }
10693   
10694   Value *Base = FixedOperands[0];
10695   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10696                                    FixedOperands.end());
10697 }
10698
10699
10700 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10701 /// sink the load out of the block that defines it.  This means that it must be
10702 /// obvious the value of the load is not changed from the point of the load to
10703 /// the end of the block it is in.
10704 ///
10705 /// Finally, it is safe, but not profitable, to sink a load targetting a
10706 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10707 /// to a register.
10708 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10709   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10710   
10711   for (++BBI; BBI != E; ++BBI)
10712     if (BBI->mayWriteToMemory())
10713       return false;
10714   
10715   // Check for non-address taken alloca.  If not address-taken already, it isn't
10716   // profitable to do this xform.
10717   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10718     bool isAddressTaken = false;
10719     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10720          UI != E; ++UI) {
10721       if (isa<LoadInst>(UI)) continue;
10722       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10723         // If storing TO the alloca, then the address isn't taken.
10724         if (SI->getOperand(1) == AI) continue;
10725       }
10726       isAddressTaken = true;
10727       break;
10728     }
10729     
10730     if (!isAddressTaken && AI->isStaticAlloca())
10731       return false;
10732   }
10733   
10734   // If this load is a load from a GEP with a constant offset from an alloca,
10735   // then we don't want to sink it.  In its present form, it will be
10736   // load [constant stack offset].  Sinking it will cause us to have to
10737   // materialize the stack addresses in each predecessor in a register only to
10738   // do a shared load from register in the successor.
10739   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10740     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10741       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10742         return false;
10743   
10744   return true;
10745 }
10746
10747
10748 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10749 // operator and they all are only used by the PHI, PHI together their
10750 // inputs, and do the operation once, to the result of the PHI.
10751 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10752   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10753
10754   // Scan the instruction, looking for input operations that can be folded away.
10755   // If all input operands to the phi are the same instruction (e.g. a cast from
10756   // the same type or "+42") we can pull the operation through the PHI, reducing
10757   // code size and simplifying code.
10758   Constant *ConstantOp = 0;
10759   const Type *CastSrcTy = 0;
10760   bool isVolatile = false;
10761   if (isa<CastInst>(FirstInst)) {
10762     CastSrcTy = FirstInst->getOperand(0)->getType();
10763   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10764     // Can fold binop, compare or shift here if the RHS is a constant, 
10765     // otherwise call FoldPHIArgBinOpIntoPHI.
10766     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10767     if (ConstantOp == 0)
10768       return FoldPHIArgBinOpIntoPHI(PN);
10769   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10770     isVolatile = LI->isVolatile();
10771     // We can't sink the load if the loaded value could be modified between the
10772     // load and the PHI.
10773     if (LI->getParent() != PN.getIncomingBlock(0) ||
10774         !isSafeAndProfitableToSinkLoad(LI))
10775       return 0;
10776     
10777     // If the PHI is of volatile loads and the load block has multiple
10778     // successors, sinking it would remove a load of the volatile value from
10779     // the path through the other successor.
10780     if (isVolatile &&
10781         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10782       return 0;
10783     
10784   } else if (isa<GetElementPtrInst>(FirstInst)) {
10785     return FoldPHIArgGEPIntoPHI(PN);
10786   } else {
10787     return 0;  // Cannot fold this operation.
10788   }
10789
10790   // Check to see if all arguments are the same operation.
10791   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10792     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10793     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10794     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10795       return 0;
10796     if (CastSrcTy) {
10797       if (I->getOperand(0)->getType() != CastSrcTy)
10798         return 0;  // Cast operation must match.
10799     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10800       // We can't sink the load if the loaded value could be modified between 
10801       // the load and the PHI.
10802       if (LI->isVolatile() != isVolatile ||
10803           LI->getParent() != PN.getIncomingBlock(i) ||
10804           !isSafeAndProfitableToSinkLoad(LI))
10805         return 0;
10806       
10807       // If the PHI is of volatile loads and the load block has multiple
10808       // successors, sinking it would remove a load of the volatile value from
10809       // the path through the other successor.
10810       if (isVolatile &&
10811           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10812         return 0;
10813       
10814     } else if (I->getOperand(1) != ConstantOp) {
10815       return 0;
10816     }
10817   }
10818
10819   // Okay, they are all the same operation.  Create a new PHI node of the
10820   // correct type, and PHI together all of the LHS's of the instructions.
10821   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10822                                    PN.getName()+".in");
10823   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10824
10825   Value *InVal = FirstInst->getOperand(0);
10826   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10827
10828   // Add all operands to the new PHI.
10829   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10830     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10831     if (NewInVal != InVal)
10832       InVal = 0;
10833     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10834   }
10835
10836   Value *PhiVal;
10837   if (InVal) {
10838     // The new PHI unions all of the same values together.  This is really
10839     // common, so we handle it intelligently here for compile-time speed.
10840     PhiVal = InVal;
10841     delete NewPN;
10842   } else {
10843     InsertNewInstBefore(NewPN, PN);
10844     PhiVal = NewPN;
10845   }
10846
10847   // Insert and return the new operation.
10848   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10849     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10850   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10851     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10852   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10853     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10854                            PhiVal, ConstantOp);
10855   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10856   
10857   // If this was a volatile load that we are merging, make sure to loop through
10858   // and mark all the input loads as non-volatile.  If we don't do this, we will
10859   // insert a new volatile load and the old ones will not be deletable.
10860   if (isVolatile)
10861     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10862       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10863   
10864   return new LoadInst(PhiVal, "", isVolatile);
10865 }
10866
10867 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10868 /// that is dead.
10869 static bool DeadPHICycle(PHINode *PN,
10870                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10871   if (PN->use_empty()) return true;
10872   if (!PN->hasOneUse()) return false;
10873
10874   // Remember this node, and if we find the cycle, return.
10875   if (!PotentiallyDeadPHIs.insert(PN))
10876     return true;
10877   
10878   // Don't scan crazily complex things.
10879   if (PotentiallyDeadPHIs.size() == 16)
10880     return false;
10881
10882   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10883     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10884
10885   return false;
10886 }
10887
10888 /// PHIsEqualValue - Return true if this phi node is always equal to
10889 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10890 ///   z = some value; x = phi (y, z); y = phi (x, z)
10891 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10892                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10893   // See if we already saw this PHI node.
10894   if (!ValueEqualPHIs.insert(PN))
10895     return true;
10896   
10897   // Don't scan crazily complex things.
10898   if (ValueEqualPHIs.size() == 16)
10899     return false;
10900  
10901   // Scan the operands to see if they are either phi nodes or are equal to
10902   // the value.
10903   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10904     Value *Op = PN->getIncomingValue(i);
10905     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10906       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10907         return false;
10908     } else if (Op != NonPhiInVal)
10909       return false;
10910   }
10911   
10912   return true;
10913 }
10914
10915
10916 // PHINode simplification
10917 //
10918 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10919   // If LCSSA is around, don't mess with Phi nodes
10920   if (MustPreserveLCSSA) return 0;
10921   
10922   if (Value *V = PN.hasConstantValue())
10923     return ReplaceInstUsesWith(PN, V);
10924
10925   // If all PHI operands are the same operation, pull them through the PHI,
10926   // reducing code size.
10927   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10928       isa<Instruction>(PN.getIncomingValue(1)) &&
10929       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10930       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10931       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10932       // than themselves more than once.
10933       PN.getIncomingValue(0)->hasOneUse())
10934     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10935       return Result;
10936
10937   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10938   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10939   // PHI)... break the cycle.
10940   if (PN.hasOneUse()) {
10941     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10942     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10943       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10944       PotentiallyDeadPHIs.insert(&PN);
10945       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10946         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10947     }
10948    
10949     // If this phi has a single use, and if that use just computes a value for
10950     // the next iteration of a loop, delete the phi.  This occurs with unused
10951     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10952     // common case here is good because the only other things that catch this
10953     // are induction variable analysis (sometimes) and ADCE, which is only run
10954     // late.
10955     if (PHIUser->hasOneUse() &&
10956         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10957         PHIUser->use_back() == &PN) {
10958       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10959     }
10960   }
10961
10962   // We sometimes end up with phi cycles that non-obviously end up being the
10963   // same value, for example:
10964   //   z = some value; x = phi (y, z); y = phi (x, z)
10965   // where the phi nodes don't necessarily need to be in the same block.  Do a
10966   // quick check to see if the PHI node only contains a single non-phi value, if
10967   // so, scan to see if the phi cycle is actually equal to that value.
10968   {
10969     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10970     // Scan for the first non-phi operand.
10971     while (InValNo != NumOperandVals && 
10972            isa<PHINode>(PN.getIncomingValue(InValNo)))
10973       ++InValNo;
10974
10975     if (InValNo != NumOperandVals) {
10976       Value *NonPhiInVal = PN.getOperand(InValNo);
10977       
10978       // Scan the rest of the operands to see if there are any conflicts, if so
10979       // there is no need to recursively scan other phis.
10980       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10981         Value *OpVal = PN.getIncomingValue(InValNo);
10982         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10983           break;
10984       }
10985       
10986       // If we scanned over all operands, then we have one unique value plus
10987       // phi values.  Scan PHI nodes to see if they all merge in each other or
10988       // the value.
10989       if (InValNo == NumOperandVals) {
10990         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10991         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10992           return ReplaceInstUsesWith(PN, NonPhiInVal);
10993       }
10994     }
10995   }
10996   return 0;
10997 }
10998
10999 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11000                                    Instruction *InsertPoint,
11001                                    InstCombiner *IC) {
11002   unsigned PtrSize = DTy->getScalarSizeInBits();
11003   unsigned VTySize = V->getType()->getScalarSizeInBits();
11004   // We must cast correctly to the pointer type. Ensure that we
11005   // sign extend the integer value if it is smaller as this is
11006   // used for address computation.
11007   Instruction::CastOps opcode = 
11008      (VTySize < PtrSize ? Instruction::SExt :
11009       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11010   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11011 }
11012
11013
11014 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11015   Value *PtrOp = GEP.getOperand(0);
11016   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11017   // If so, eliminate the noop.
11018   if (GEP.getNumOperands() == 1)
11019     return ReplaceInstUsesWith(GEP, PtrOp);
11020
11021   if (isa<UndefValue>(GEP.getOperand(0)))
11022     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11023
11024   bool HasZeroPointerIndex = false;
11025   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11026     HasZeroPointerIndex = C->isNullValue();
11027
11028   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11029     return ReplaceInstUsesWith(GEP, PtrOp);
11030
11031   // Eliminate unneeded casts for indices.
11032   bool MadeChange = false;
11033   
11034   gep_type_iterator GTI = gep_type_begin(GEP);
11035   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11036        i != e; ++i, ++GTI) {
11037     if (isa<SequentialType>(*GTI)) {
11038       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11039         if (CI->getOpcode() == Instruction::ZExt ||
11040             CI->getOpcode() == Instruction::SExt) {
11041           const Type *SrcTy = CI->getOperand(0)->getType();
11042           // We can eliminate a cast from i32 to i64 iff the target 
11043           // is a 32-bit pointer target.
11044           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11045             MadeChange = true;
11046             *i = CI->getOperand(0);
11047           }
11048         }
11049       }
11050       // If we are using a wider index than needed for this platform, shrink it
11051       // to what we need.  If narrower, sign-extend it to what we need.
11052       // If the incoming value needs a cast instruction,
11053       // insert it.  This explicit cast can make subsequent optimizations more
11054       // obvious.
11055       Value *Op = *i;
11056       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11057         if (Constant *C = dyn_cast<Constant>(Op)) {
11058           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11059           MadeChange = true;
11060         } else {
11061           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11062                                 GEP);
11063           *i = Op;
11064           MadeChange = true;
11065         }
11066       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11067         if (Constant *C = dyn_cast<Constant>(Op)) {
11068           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11069           MadeChange = true;
11070         } else {
11071           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11072                                 GEP);
11073           *i = Op;
11074           MadeChange = true;
11075         }
11076       }
11077     }
11078   }
11079   if (MadeChange) return &GEP;
11080
11081   // Combine Indices - If the source pointer to this getelementptr instruction
11082   // is a getelementptr instruction, combine the indices of the two
11083   // getelementptr instructions into a single instruction.
11084   //
11085   SmallVector<Value*, 8> SrcGEPOperands;
11086   if (User *Src = dyn_castGetElementPtr(PtrOp))
11087     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11088
11089   if (!SrcGEPOperands.empty()) {
11090     // Note that if our source is a gep chain itself that we wait for that
11091     // chain to be resolved before we perform this transformation.  This
11092     // avoids us creating a TON of code in some cases.
11093     //
11094     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11095         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11096       return 0;   // Wait until our source is folded to completion.
11097
11098     SmallVector<Value*, 8> Indices;
11099
11100     // Find out whether the last index in the source GEP is a sequential idx.
11101     bool EndsWithSequential = false;
11102     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11103            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11104       EndsWithSequential = !isa<StructType>(*I);
11105
11106     // Can we combine the two pointer arithmetics offsets?
11107     if (EndsWithSequential) {
11108       // Replace: gep (gep %P, long B), long A, ...
11109       // With:    T = long A+B; gep %P, T, ...
11110       //
11111       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11112       if (SO1 == Context->getNullValue(SO1->getType())) {
11113         Sum = GO1;
11114       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11115         Sum = SO1;
11116       } else {
11117         // If they aren't the same type, convert both to an integer of the
11118         // target's pointer size.
11119         if (SO1->getType() != GO1->getType()) {
11120           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11121             SO1 =
11122                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11123           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11124             GO1 =
11125                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11126           } else {
11127             unsigned PS = TD->getPointerSizeInBits();
11128             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11129               // Convert GO1 to SO1's type.
11130               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11131
11132             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11133               // Convert SO1 to GO1's type.
11134               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11135             } else {
11136               const Type *PT = TD->getIntPtrType();
11137               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11138               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11139             }
11140           }
11141         }
11142         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11143           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11144                                             cast<Constant>(GO1));
11145         else {
11146           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11147           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11148         }
11149       }
11150
11151       // Recycle the GEP we already have if possible.
11152       if (SrcGEPOperands.size() == 2) {
11153         GEP.setOperand(0, SrcGEPOperands[0]);
11154         GEP.setOperand(1, Sum);
11155         return &GEP;
11156       } else {
11157         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11158                        SrcGEPOperands.end()-1);
11159         Indices.push_back(Sum);
11160         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11161       }
11162     } else if (isa<Constant>(*GEP.idx_begin()) &&
11163                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11164                SrcGEPOperands.size() != 1) {
11165       // Otherwise we can do the fold if the first index of the GEP is a zero
11166       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11167                      SrcGEPOperands.end());
11168       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11169     }
11170
11171     if (!Indices.empty())
11172       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11173                                        Indices.end(), GEP.getName());
11174
11175   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11176     // GEP of global variable.  If all of the indices for this GEP are
11177     // constants, we can promote this to a constexpr instead of an instruction.
11178
11179     // Scan for nonconstants...
11180     SmallVector<Constant*, 8> Indices;
11181     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11182     for (; I != E && isa<Constant>(*I); ++I)
11183       Indices.push_back(cast<Constant>(*I));
11184
11185     if (I == E) {  // If they are all constants...
11186       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11187                                                     &Indices[0],Indices.size());
11188
11189       // Replace all uses of the GEP with the new constexpr...
11190       return ReplaceInstUsesWith(GEP, CE);
11191     }
11192   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11193     if (!isa<PointerType>(X->getType())) {
11194       // Not interesting.  Source pointer must be a cast from pointer.
11195     } else if (HasZeroPointerIndex) {
11196       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11197       // into     : GEP [10 x i8]* X, i32 0, ...
11198       //
11199       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11200       //           into     : GEP i8* X, ...
11201       // 
11202       // This occurs when the program declares an array extern like "int X[];"
11203       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11204       const PointerType *XTy = cast<PointerType>(X->getType());
11205       if (const ArrayType *CATy =
11206           dyn_cast<ArrayType>(CPTy->getElementType())) {
11207         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11208         if (CATy->getElementType() == XTy->getElementType()) {
11209           // -> GEP i8* X, ...
11210           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11211           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11212                                            GEP.getName());
11213         } else if (const ArrayType *XATy =
11214                  dyn_cast<ArrayType>(XTy->getElementType())) {
11215           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11216           if (CATy->getElementType() == XATy->getElementType()) {
11217             // -> GEP [10 x i8]* X, i32 0, ...
11218             // At this point, we know that the cast source type is a pointer
11219             // to an array of the same type as the destination pointer
11220             // array.  Because the array type is never stepped over (there
11221             // is a leading zero) we can fold the cast into this GEP.
11222             GEP.setOperand(0, X);
11223             return &GEP;
11224           }
11225         }
11226       }
11227     } else if (GEP.getNumOperands() == 2) {
11228       // Transform things like:
11229       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11230       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11231       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11232       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11233       if (isa<ArrayType>(SrcElTy) &&
11234           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11235           TD->getTypeAllocSize(ResElTy)) {
11236         Value *Idx[2];
11237         Idx[0] = Context->getNullValue(Type::Int32Ty);
11238         Idx[1] = GEP.getOperand(1);
11239         Value *V = InsertNewInstBefore(
11240                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11241         // V and GEP are both pointer types --> BitCast
11242         return new BitCastInst(V, GEP.getType());
11243       }
11244       
11245       // Transform things like:
11246       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11247       //   (where tmp = 8*tmp2) into:
11248       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11249       
11250       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11251         uint64_t ArrayEltSize =
11252             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11253         
11254         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11255         // allow either a mul, shift, or constant here.
11256         Value *NewIdx = 0;
11257         ConstantInt *Scale = 0;
11258         if (ArrayEltSize == 1) {
11259           NewIdx = GEP.getOperand(1);
11260           Scale = 
11261                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11262         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11263           NewIdx = Context->getConstantInt(CI->getType(), 1);
11264           Scale = CI;
11265         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11266           if (Inst->getOpcode() == Instruction::Shl &&
11267               isa<ConstantInt>(Inst->getOperand(1))) {
11268             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11269             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11270             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11271                                      1ULL << ShAmtVal);
11272             NewIdx = Inst->getOperand(0);
11273           } else if (Inst->getOpcode() == Instruction::Mul &&
11274                      isa<ConstantInt>(Inst->getOperand(1))) {
11275             Scale = cast<ConstantInt>(Inst->getOperand(1));
11276             NewIdx = Inst->getOperand(0);
11277           }
11278         }
11279         
11280         // If the index will be to exactly the right offset with the scale taken
11281         // out, perform the transformation. Note, we don't know whether Scale is
11282         // signed or not. We'll use unsigned version of division/modulo
11283         // operation after making sure Scale doesn't have the sign bit set.
11284         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11285             Scale->getZExtValue() % ArrayEltSize == 0) {
11286           Scale = Context->getConstantInt(Scale->getType(),
11287                                    Scale->getZExtValue() / ArrayEltSize);
11288           if (Scale->getZExtValue() != 1) {
11289             Constant *C =
11290                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11291                                                        false /*ZExt*/);
11292             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11293             NewIdx = InsertNewInstBefore(Sc, GEP);
11294           }
11295
11296           // Insert the new GEP instruction.
11297           Value *Idx[2];
11298           Idx[0] = Context->getNullValue(Type::Int32Ty);
11299           Idx[1] = NewIdx;
11300           Instruction *NewGEP =
11301             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11302           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11303           // The NewGEP must be pointer typed, so must the old one -> BitCast
11304           return new BitCastInst(NewGEP, GEP.getType());
11305         }
11306       }
11307     }
11308   }
11309   
11310   /// See if we can simplify:
11311   ///   X = bitcast A to B*
11312   ///   Y = gep X, <...constant indices...>
11313   /// into a gep of the original struct.  This is important for SROA and alias
11314   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11315   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11316     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11317       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11318       // a constant back from EmitGEPOffset.
11319       ConstantInt *OffsetV =
11320                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11321       int64_t Offset = OffsetV->getSExtValue();
11322       
11323       // If this GEP instruction doesn't move the pointer, just replace the GEP
11324       // with a bitcast of the real input to the dest type.
11325       if (Offset == 0) {
11326         // If the bitcast is of an allocation, and the allocation will be
11327         // converted to match the type of the cast, don't touch this.
11328         if (isa<AllocationInst>(BCI->getOperand(0))) {
11329           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11330           if (Instruction *I = visitBitCast(*BCI)) {
11331             if (I != BCI) {
11332               I->takeName(BCI);
11333               BCI->getParent()->getInstList().insert(BCI, I);
11334               ReplaceInstUsesWith(*BCI, I);
11335             }
11336             return &GEP;
11337           }
11338         }
11339         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11340       }
11341       
11342       // Otherwise, if the offset is non-zero, we need to find out if there is a
11343       // field at Offset in 'A's type.  If so, we can pull the cast through the
11344       // GEP.
11345       SmallVector<Value*, 8> NewIndices;
11346       const Type *InTy =
11347         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11348       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11349         Instruction *NGEP =
11350            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11351                                      NewIndices.end());
11352         if (NGEP->getType() == GEP.getType()) return NGEP;
11353         InsertNewInstBefore(NGEP, GEP);
11354         NGEP->takeName(&GEP);
11355         return new BitCastInst(NGEP, GEP.getType());
11356       }
11357     }
11358   }    
11359     
11360   return 0;
11361 }
11362
11363 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11364   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11365   if (AI.isArrayAllocation()) {  // Check C != 1
11366     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11367       const Type *NewTy = 
11368         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11369       AllocationInst *New = 0;
11370
11371       // Create and insert the replacement instruction...
11372       if (isa<MallocInst>(AI))
11373         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11374       else {
11375         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11376         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11377       }
11378
11379       InsertNewInstBefore(New, AI);
11380
11381       // Scan to the end of the allocation instructions, to skip over a block of
11382       // allocas if possible...also skip interleaved debug info
11383       //
11384       BasicBlock::iterator It = New;
11385       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11386
11387       // Now that I is pointing to the first non-allocation-inst in the block,
11388       // insert our getelementptr instruction...
11389       //
11390       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11391       Value *Idx[2];
11392       Idx[0] = NullIdx;
11393       Idx[1] = NullIdx;
11394       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11395                                            New->getName()+".sub", It);
11396
11397       // Now make everything use the getelementptr instead of the original
11398       // allocation.
11399       return ReplaceInstUsesWith(AI, V);
11400     } else if (isa<UndefValue>(AI.getArraySize())) {
11401       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11402     }
11403   }
11404
11405   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11406     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11407     // Note that we only do this for alloca's, because malloc should allocate
11408     // and return a unique pointer, even for a zero byte allocation.
11409     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11410       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11411
11412     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11413     if (AI.getAlignment() == 0)
11414       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11415   }
11416
11417   return 0;
11418 }
11419
11420 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11421   Value *Op = FI.getOperand(0);
11422
11423   // free undef -> unreachable.
11424   if (isa<UndefValue>(Op)) {
11425     // Insert a new store to null because we cannot modify the CFG here.
11426     new StoreInst(Context->getConstantIntTrue(),
11427            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11428     return EraseInstFromFunction(FI);
11429   }
11430   
11431   // If we have 'free null' delete the instruction.  This can happen in stl code
11432   // when lots of inlining happens.
11433   if (isa<ConstantPointerNull>(Op))
11434     return EraseInstFromFunction(FI);
11435   
11436   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11437   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11438     FI.setOperand(0, CI->getOperand(0));
11439     return &FI;
11440   }
11441   
11442   // Change free (gep X, 0,0,0,0) into free(X)
11443   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11444     if (GEPI->hasAllZeroIndices()) {
11445       AddToWorkList(GEPI);
11446       FI.setOperand(0, GEPI->getOperand(0));
11447       return &FI;
11448     }
11449   }
11450   
11451   // Change free(malloc) into nothing, if the malloc has a single use.
11452   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11453     if (MI->hasOneUse()) {
11454       EraseInstFromFunction(FI);
11455       return EraseInstFromFunction(*MI);
11456     }
11457
11458   return 0;
11459 }
11460
11461
11462 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11463 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11464                                         const TargetData *TD) {
11465   User *CI = cast<User>(LI.getOperand(0));
11466   Value *CastOp = CI->getOperand(0);
11467   LLVMContext *Context = IC.getContext();
11468
11469   if (TD) {
11470     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11471       // Instead of loading constant c string, use corresponding integer value
11472       // directly if string length is small enough.
11473       std::string Str;
11474       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11475         unsigned len = Str.length();
11476         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11477         unsigned numBits = Ty->getPrimitiveSizeInBits();
11478         // Replace LI with immediate integer store.
11479         if ((numBits >> 3) == len + 1) {
11480           APInt StrVal(numBits, 0);
11481           APInt SingleChar(numBits, 0);
11482           if (TD->isLittleEndian()) {
11483             for (signed i = len-1; i >= 0; i--) {
11484               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11485               StrVal = (StrVal << 8) | SingleChar;
11486             }
11487           } else {
11488             for (unsigned i = 0; i < len; i++) {
11489               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11490               StrVal = (StrVal << 8) | SingleChar;
11491             }
11492             // Append NULL at the end.
11493             SingleChar = 0;
11494             StrVal = (StrVal << 8) | SingleChar;
11495           }
11496           Value *NL = Context->getConstantInt(StrVal);
11497           return IC.ReplaceInstUsesWith(LI, NL);
11498         }
11499       }
11500     }
11501   }
11502
11503   const PointerType *DestTy = cast<PointerType>(CI->getType());
11504   const Type *DestPTy = DestTy->getElementType();
11505   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11506
11507     // If the address spaces don't match, don't eliminate the cast.
11508     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11509       return 0;
11510
11511     const Type *SrcPTy = SrcTy->getElementType();
11512
11513     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11514          isa<VectorType>(DestPTy)) {
11515       // If the source is an array, the code below will not succeed.  Check to
11516       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11517       // constants.
11518       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11519         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11520           if (ASrcTy->getNumElements() != 0) {
11521             Value *Idxs[2];
11522             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11523             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11524             SrcTy = cast<PointerType>(CastOp->getType());
11525             SrcPTy = SrcTy->getElementType();
11526           }
11527
11528       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11529             isa<VectorType>(SrcPTy)) &&
11530           // Do not allow turning this into a load of an integer, which is then
11531           // casted to a pointer, this pessimizes pointer analysis a lot.
11532           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11533           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11534                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11535
11536         // Okay, we are casting from one integer or pointer type to another of
11537         // the same size.  Instead of casting the pointer before the load, cast
11538         // the result of the loaded value.
11539         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11540                                                              CI->getName(),
11541                                                          LI.isVolatile()),LI);
11542         // Now cast the result of the load.
11543         return new BitCastInst(NewLoad, LI.getType());
11544       }
11545     }
11546   }
11547   return 0;
11548 }
11549
11550 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11551   Value *Op = LI.getOperand(0);
11552
11553   // Attempt to improve the alignment.
11554   unsigned KnownAlign =
11555     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11556   if (KnownAlign >
11557       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11558                                 LI.getAlignment()))
11559     LI.setAlignment(KnownAlign);
11560
11561   // load (cast X) --> cast (load X) iff safe
11562   if (isa<CastInst>(Op))
11563     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11564       return Res;
11565
11566   // None of the following transforms are legal for volatile loads.
11567   if (LI.isVolatile()) return 0;
11568   
11569   // Do really simple store-to-load forwarding and load CSE, to catch cases
11570   // where there are several consequtive memory accesses to the same location,
11571   // separated by a few arithmetic operations.
11572   BasicBlock::iterator BBI = &LI;
11573   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11574     return ReplaceInstUsesWith(LI, AvailableVal);
11575
11576   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11577     const Value *GEPI0 = GEPI->getOperand(0);
11578     // TODO: Consider a target hook for valid address spaces for this xform.
11579     if (isa<ConstantPointerNull>(GEPI0) &&
11580         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11581       // Insert a new store to null instruction before the load to indicate
11582       // that this code is not reachable.  We do this instead of inserting
11583       // an unreachable instruction directly because we cannot modify the
11584       // CFG.
11585       new StoreInst(Context->getUndef(LI.getType()),
11586                     Context->getNullValue(Op->getType()), &LI);
11587       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11588     }
11589   } 
11590
11591   if (Constant *C = dyn_cast<Constant>(Op)) {
11592     // load null/undef -> undef
11593     // TODO: Consider a target hook for valid address spaces for this xform.
11594     if (isa<UndefValue>(C) || (C->isNullValue() && 
11595         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11596       // Insert a new store to null instruction before the load to indicate that
11597       // this code is not reachable.  We do this instead of inserting an
11598       // unreachable instruction directly because we cannot modify the CFG.
11599       new StoreInst(Context->getUndef(LI.getType()),
11600                     Context->getNullValue(Op->getType()), &LI);
11601       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11602     }
11603
11604     // Instcombine load (constant global) into the value loaded.
11605     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11606       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11607         return ReplaceInstUsesWith(LI, GV->getInitializer());
11608
11609     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11610     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11611       if (CE->getOpcode() == Instruction::GetElementPtr) {
11612         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11613           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11614             if (Constant *V = 
11615                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11616                                                       Context))
11617               return ReplaceInstUsesWith(LI, V);
11618         if (CE->getOperand(0)->isNullValue()) {
11619           // Insert a new store to null instruction before the load to indicate
11620           // that this code is not reachable.  We do this instead of inserting
11621           // an unreachable instruction directly because we cannot modify the
11622           // CFG.
11623           new StoreInst(Context->getUndef(LI.getType()),
11624                         Context->getNullValue(Op->getType()), &LI);
11625           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11626         }
11627
11628       } else if (CE->isCast()) {
11629         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11630           return Res;
11631       }
11632     }
11633   }
11634     
11635   // If this load comes from anywhere in a constant global, and if the global
11636   // is all undef or zero, we know what it loads.
11637   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11638     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11639       if (GV->getInitializer()->isNullValue())
11640         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11641       else if (isa<UndefValue>(GV->getInitializer()))
11642         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11643     }
11644   }
11645
11646   if (Op->hasOneUse()) {
11647     // Change select and PHI nodes to select values instead of addresses: this
11648     // helps alias analysis out a lot, allows many others simplifications, and
11649     // exposes redundancy in the code.
11650     //
11651     // Note that we cannot do the transformation unless we know that the
11652     // introduced loads cannot trap!  Something like this is valid as long as
11653     // the condition is always false: load (select bool %C, int* null, int* %G),
11654     // but it would not be valid if we transformed it to load from null
11655     // unconditionally.
11656     //
11657     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11658       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11659       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11660           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11661         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11662                                      SI->getOperand(1)->getName()+".val"), LI);
11663         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11664                                      SI->getOperand(2)->getName()+".val"), LI);
11665         return SelectInst::Create(SI->getCondition(), V1, V2);
11666       }
11667
11668       // load (select (cond, null, P)) -> load P
11669       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11670         if (C->isNullValue()) {
11671           LI.setOperand(0, SI->getOperand(2));
11672           return &LI;
11673         }
11674
11675       // load (select (cond, P, null)) -> load P
11676       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11677         if (C->isNullValue()) {
11678           LI.setOperand(0, SI->getOperand(1));
11679           return &LI;
11680         }
11681     }
11682   }
11683   return 0;
11684 }
11685
11686 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11687 /// when possible.  This makes it generally easy to do alias analysis and/or
11688 /// SROA/mem2reg of the memory object.
11689 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11690   User *CI = cast<User>(SI.getOperand(1));
11691   Value *CastOp = CI->getOperand(0);
11692   LLVMContext *Context = IC.getContext();
11693
11694   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11695   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11696   if (SrcTy == 0) return 0;
11697   
11698   const Type *SrcPTy = SrcTy->getElementType();
11699
11700   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11701     return 0;
11702   
11703   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11704   /// to its first element.  This allows us to handle things like:
11705   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11706   /// on 32-bit hosts.
11707   SmallVector<Value*, 4> NewGEPIndices;
11708   
11709   // If the source is an array, the code below will not succeed.  Check to
11710   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11711   // constants.
11712   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11713     // Index through pointer.
11714     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11715     NewGEPIndices.push_back(Zero);
11716     
11717     while (1) {
11718       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11719         if (!STy->getNumElements()) /* Struct can be empty {} */
11720           break;
11721         NewGEPIndices.push_back(Zero);
11722         SrcPTy = STy->getElementType(0);
11723       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11724         NewGEPIndices.push_back(Zero);
11725         SrcPTy = ATy->getElementType();
11726       } else {
11727         break;
11728       }
11729     }
11730     
11731     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11732   }
11733
11734   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11735     return 0;
11736   
11737   // If the pointers point into different address spaces or if they point to
11738   // values with different sizes, we can't do the transformation.
11739   if (SrcTy->getAddressSpace() != 
11740         cast<PointerType>(CI->getType())->getAddressSpace() ||
11741       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11742       IC.getTargetData().getTypeSizeInBits(DestPTy))
11743     return 0;
11744
11745   // Okay, we are casting from one integer or pointer type to another of
11746   // the same size.  Instead of casting the pointer before 
11747   // the store, cast the value to be stored.
11748   Value *NewCast;
11749   Value *SIOp0 = SI.getOperand(0);
11750   Instruction::CastOps opcode = Instruction::BitCast;
11751   const Type* CastSrcTy = SIOp0->getType();
11752   const Type* CastDstTy = SrcPTy;
11753   if (isa<PointerType>(CastDstTy)) {
11754     if (CastSrcTy->isInteger())
11755       opcode = Instruction::IntToPtr;
11756   } else if (isa<IntegerType>(CastDstTy)) {
11757     if (isa<PointerType>(SIOp0->getType()))
11758       opcode = Instruction::PtrToInt;
11759   }
11760   
11761   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11762   // emit a GEP to index into its first field.
11763   if (!NewGEPIndices.empty()) {
11764     if (Constant *C = dyn_cast<Constant>(CastOp))
11765       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11766                                               NewGEPIndices.size());
11767     else
11768       CastOp = IC.InsertNewInstBefore(
11769               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11770                                         NewGEPIndices.end()), SI);
11771   }
11772   
11773   if (Constant *C = dyn_cast<Constant>(SIOp0))
11774     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11775   else
11776     NewCast = IC.InsertNewInstBefore(
11777       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11778       SI);
11779   return new StoreInst(NewCast, CastOp);
11780 }
11781
11782 /// equivalentAddressValues - Test if A and B will obviously have the same
11783 /// value. This includes recognizing that %t0 and %t1 will have the same
11784 /// value in code like this:
11785 ///   %t0 = getelementptr \@a, 0, 3
11786 ///   store i32 0, i32* %t0
11787 ///   %t1 = getelementptr \@a, 0, 3
11788 ///   %t2 = load i32* %t1
11789 ///
11790 static bool equivalentAddressValues(Value *A, Value *B) {
11791   // Test if the values are trivially equivalent.
11792   if (A == B) return true;
11793   
11794   // Test if the values come form identical arithmetic instructions.
11795   if (isa<BinaryOperator>(A) ||
11796       isa<CastInst>(A) ||
11797       isa<PHINode>(A) ||
11798       isa<GetElementPtrInst>(A))
11799     if (Instruction *BI = dyn_cast<Instruction>(B))
11800       if (cast<Instruction>(A)->isIdenticalTo(BI))
11801         return true;
11802   
11803   // Otherwise they may not be equivalent.
11804   return false;
11805 }
11806
11807 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11808 // return the llvm.dbg.declare.
11809 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11810   if (!V->hasNUses(2))
11811     return 0;
11812   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11813        UI != E; ++UI) {
11814     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11815       return DI;
11816     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11817       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11818         return DI;
11819       }
11820   }
11821   return 0;
11822 }
11823
11824 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11825   Value *Val = SI.getOperand(0);
11826   Value *Ptr = SI.getOperand(1);
11827
11828   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11829     EraseInstFromFunction(SI);
11830     ++NumCombined;
11831     return 0;
11832   }
11833   
11834   // If the RHS is an alloca with a single use, zapify the store, making the
11835   // alloca dead.
11836   // If the RHS is an alloca with a two uses, the other one being a 
11837   // llvm.dbg.declare, zapify the store and the declare, making the
11838   // alloca dead.  We must do this to prevent declare's from affecting
11839   // codegen.
11840   if (!SI.isVolatile()) {
11841     if (Ptr->hasOneUse()) {
11842       if (isa<AllocaInst>(Ptr)) {
11843         EraseInstFromFunction(SI);
11844         ++NumCombined;
11845         return 0;
11846       }
11847       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11848         if (isa<AllocaInst>(GEP->getOperand(0))) {
11849           if (GEP->getOperand(0)->hasOneUse()) {
11850             EraseInstFromFunction(SI);
11851             ++NumCombined;
11852             return 0;
11853           }
11854           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11855             EraseInstFromFunction(*DI);
11856             EraseInstFromFunction(SI);
11857             ++NumCombined;
11858             return 0;
11859           }
11860         }
11861       }
11862     }
11863     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11864       EraseInstFromFunction(*DI);
11865       EraseInstFromFunction(SI);
11866       ++NumCombined;
11867       return 0;
11868     }
11869   }
11870
11871   // Attempt to improve the alignment.
11872   unsigned KnownAlign =
11873     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11874   if (KnownAlign >
11875       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11876                                 SI.getAlignment()))
11877     SI.setAlignment(KnownAlign);
11878
11879   // Do really simple DSE, to catch cases where there are several consecutive
11880   // stores to the same location, separated by a few arithmetic operations. This
11881   // situation often occurs with bitfield accesses.
11882   BasicBlock::iterator BBI = &SI;
11883   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11884        --ScanInsts) {
11885     --BBI;
11886     // Don't count debug info directives, lest they affect codegen,
11887     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11888     // It is necessary for correctness to skip those that feed into a
11889     // llvm.dbg.declare, as these are not present when debugging is off.
11890     if (isa<DbgInfoIntrinsic>(BBI) ||
11891         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11892       ScanInsts++;
11893       continue;
11894     }    
11895     
11896     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11897       // Prev store isn't volatile, and stores to the same location?
11898       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11899                                                           SI.getOperand(1))) {
11900         ++NumDeadStore;
11901         ++BBI;
11902         EraseInstFromFunction(*PrevSI);
11903         continue;
11904       }
11905       break;
11906     }
11907     
11908     // If this is a load, we have to stop.  However, if the loaded value is from
11909     // the pointer we're loading and is producing the pointer we're storing,
11910     // then *this* store is dead (X = load P; store X -> P).
11911     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11912       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11913           !SI.isVolatile()) {
11914         EraseInstFromFunction(SI);
11915         ++NumCombined;
11916         return 0;
11917       }
11918       // Otherwise, this is a load from some other location.  Stores before it
11919       // may not be dead.
11920       break;
11921     }
11922     
11923     // Don't skip over loads or things that can modify memory.
11924     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11925       break;
11926   }
11927   
11928   
11929   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11930
11931   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11932   if (isa<ConstantPointerNull>(Ptr) &&
11933       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11934     if (!isa<UndefValue>(Val)) {
11935       SI.setOperand(0, Context->getUndef(Val->getType()));
11936       if (Instruction *U = dyn_cast<Instruction>(Val))
11937         AddToWorkList(U);  // Dropped a use.
11938       ++NumCombined;
11939     }
11940     return 0;  // Do not modify these!
11941   }
11942
11943   // store undef, Ptr -> noop
11944   if (isa<UndefValue>(Val)) {
11945     EraseInstFromFunction(SI);
11946     ++NumCombined;
11947     return 0;
11948   }
11949
11950   // If the pointer destination is a cast, see if we can fold the cast into the
11951   // source instead.
11952   if (isa<CastInst>(Ptr))
11953     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11954       return Res;
11955   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11956     if (CE->isCast())
11957       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11958         return Res;
11959
11960   
11961   // If this store is the last instruction in the basic block (possibly
11962   // excepting debug info instructions and the pointer bitcasts that feed
11963   // into them), and if the block ends with an unconditional branch, try
11964   // to move it to the successor block.
11965   BBI = &SI; 
11966   do {
11967     ++BBI;
11968   } while (isa<DbgInfoIntrinsic>(BBI) ||
11969            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11970   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11971     if (BI->isUnconditional())
11972       if (SimplifyStoreAtEndOfBlock(SI))
11973         return 0;  // xform done!
11974   
11975   return 0;
11976 }
11977
11978 /// SimplifyStoreAtEndOfBlock - Turn things like:
11979 ///   if () { *P = v1; } else { *P = v2 }
11980 /// into a phi node with a store in the successor.
11981 ///
11982 /// Simplify things like:
11983 ///   *P = v1; if () { *P = v2; }
11984 /// into a phi node with a store in the successor.
11985 ///
11986 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11987   BasicBlock *StoreBB = SI.getParent();
11988   
11989   // Check to see if the successor block has exactly two incoming edges.  If
11990   // so, see if the other predecessor contains a store to the same location.
11991   // if so, insert a PHI node (if needed) and move the stores down.
11992   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11993   
11994   // Determine whether Dest has exactly two predecessors and, if so, compute
11995   // the other predecessor.
11996   pred_iterator PI = pred_begin(DestBB);
11997   BasicBlock *OtherBB = 0;
11998   if (*PI != StoreBB)
11999     OtherBB = *PI;
12000   ++PI;
12001   if (PI == pred_end(DestBB))
12002     return false;
12003   
12004   if (*PI != StoreBB) {
12005     if (OtherBB)
12006       return false;
12007     OtherBB = *PI;
12008   }
12009   if (++PI != pred_end(DestBB))
12010     return false;
12011
12012   // Bail out if all the relevant blocks aren't distinct (this can happen,
12013   // for example, if SI is in an infinite loop)
12014   if (StoreBB == DestBB || OtherBB == DestBB)
12015     return false;
12016
12017   // Verify that the other block ends in a branch and is not otherwise empty.
12018   BasicBlock::iterator BBI = OtherBB->getTerminator();
12019   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12020   if (!OtherBr || BBI == OtherBB->begin())
12021     return false;
12022   
12023   // If the other block ends in an unconditional branch, check for the 'if then
12024   // else' case.  there is an instruction before the branch.
12025   StoreInst *OtherStore = 0;
12026   if (OtherBr->isUnconditional()) {
12027     --BBI;
12028     // Skip over debugging info.
12029     while (isa<DbgInfoIntrinsic>(BBI) ||
12030            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12031       if (BBI==OtherBB->begin())
12032         return false;
12033       --BBI;
12034     }
12035     // If this isn't a store, or isn't a store to the same location, bail out.
12036     OtherStore = dyn_cast<StoreInst>(BBI);
12037     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12038       return false;
12039   } else {
12040     // Otherwise, the other block ended with a conditional branch. If one of the
12041     // destinations is StoreBB, then we have the if/then case.
12042     if (OtherBr->getSuccessor(0) != StoreBB && 
12043         OtherBr->getSuccessor(1) != StoreBB)
12044       return false;
12045     
12046     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12047     // if/then triangle.  See if there is a store to the same ptr as SI that
12048     // lives in OtherBB.
12049     for (;; --BBI) {
12050       // Check to see if we find the matching store.
12051       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12052         if (OtherStore->getOperand(1) != SI.getOperand(1))
12053           return false;
12054         break;
12055       }
12056       // If we find something that may be using or overwriting the stored
12057       // value, or if we run out of instructions, we can't do the xform.
12058       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12059           BBI == OtherBB->begin())
12060         return false;
12061     }
12062     
12063     // In order to eliminate the store in OtherBr, we have to
12064     // make sure nothing reads or overwrites the stored value in
12065     // StoreBB.
12066     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12067       // FIXME: This should really be AA driven.
12068       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12069         return false;
12070     }
12071   }
12072   
12073   // Insert a PHI node now if we need it.
12074   Value *MergedVal = OtherStore->getOperand(0);
12075   if (MergedVal != SI.getOperand(0)) {
12076     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12077     PN->reserveOperandSpace(2);
12078     PN->addIncoming(SI.getOperand(0), SI.getParent());
12079     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12080     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12081   }
12082   
12083   // Advance to a place where it is safe to insert the new store and
12084   // insert it.
12085   BBI = DestBB->getFirstNonPHI();
12086   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12087                                     OtherStore->isVolatile()), *BBI);
12088   
12089   // Nuke the old stores.
12090   EraseInstFromFunction(SI);
12091   EraseInstFromFunction(*OtherStore);
12092   ++NumCombined;
12093   return true;
12094 }
12095
12096
12097 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12098   // Change br (not X), label True, label False to: br X, label False, True
12099   Value *X = 0;
12100   BasicBlock *TrueDest;
12101   BasicBlock *FalseDest;
12102   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12103       !isa<Constant>(X)) {
12104     // Swap Destinations and condition...
12105     BI.setCondition(X);
12106     BI.setSuccessor(0, FalseDest);
12107     BI.setSuccessor(1, TrueDest);
12108     return &BI;
12109   }
12110
12111   // Cannonicalize fcmp_one -> fcmp_oeq
12112   FCmpInst::Predicate FPred; Value *Y;
12113   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12114                              TrueDest, FalseDest), *Context))
12115     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12116          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12117       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12118       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12119       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12120       NewSCC->takeName(I);
12121       // Swap Destinations and condition...
12122       BI.setCondition(NewSCC);
12123       BI.setSuccessor(0, FalseDest);
12124       BI.setSuccessor(1, TrueDest);
12125       RemoveFromWorkList(I);
12126       I->eraseFromParent();
12127       AddToWorkList(NewSCC);
12128       return &BI;
12129     }
12130
12131   // Cannonicalize icmp_ne -> icmp_eq
12132   ICmpInst::Predicate IPred;
12133   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12134                       TrueDest, FalseDest), *Context))
12135     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12136          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12137          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12138       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12139       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12140       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12141       NewSCC->takeName(I);
12142       // Swap Destinations and condition...
12143       BI.setCondition(NewSCC);
12144       BI.setSuccessor(0, FalseDest);
12145       BI.setSuccessor(1, TrueDest);
12146       RemoveFromWorkList(I);
12147       I->eraseFromParent();;
12148       AddToWorkList(NewSCC);
12149       return &BI;
12150     }
12151
12152   return 0;
12153 }
12154
12155 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12156   Value *Cond = SI.getCondition();
12157   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12158     if (I->getOpcode() == Instruction::Add)
12159       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12160         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12161         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12162           SI.setOperand(i,
12163                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12164                                                 AddRHS));
12165         SI.setOperand(0, I->getOperand(0));
12166         AddToWorkList(I);
12167         return &SI;
12168       }
12169   }
12170   return 0;
12171 }
12172
12173 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12174   Value *Agg = EV.getAggregateOperand();
12175
12176   if (!EV.hasIndices())
12177     return ReplaceInstUsesWith(EV, Agg);
12178
12179   if (Constant *C = dyn_cast<Constant>(Agg)) {
12180     if (isa<UndefValue>(C))
12181       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12182       
12183     if (isa<ConstantAggregateZero>(C))
12184       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12185
12186     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12187       // Extract the element indexed by the first index out of the constant
12188       Value *V = C->getOperand(*EV.idx_begin());
12189       if (EV.getNumIndices() > 1)
12190         // Extract the remaining indices out of the constant indexed by the
12191         // first index
12192         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12193       else
12194         return ReplaceInstUsesWith(EV, V);
12195     }
12196     return 0; // Can't handle other constants
12197   } 
12198   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12199     // We're extracting from an insertvalue instruction, compare the indices
12200     const unsigned *exti, *exte, *insi, *inse;
12201     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12202          exte = EV.idx_end(), inse = IV->idx_end();
12203          exti != exte && insi != inse;
12204          ++exti, ++insi) {
12205       if (*insi != *exti)
12206         // The insert and extract both reference distinctly different elements.
12207         // This means the extract is not influenced by the insert, and we can
12208         // replace the aggregate operand of the extract with the aggregate
12209         // operand of the insert. i.e., replace
12210         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12211         // %E = extractvalue { i32, { i32 } } %I, 0
12212         // with
12213         // %E = extractvalue { i32, { i32 } } %A, 0
12214         return ExtractValueInst::Create(IV->getAggregateOperand(),
12215                                         EV.idx_begin(), EV.idx_end());
12216     }
12217     if (exti == exte && insi == inse)
12218       // Both iterators are at the end: Index lists are identical. Replace
12219       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12220       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12221       // with "i32 42"
12222       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12223     if (exti == exte) {
12224       // The extract list is a prefix of the insert list. i.e. replace
12225       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12226       // %E = extractvalue { i32, { i32 } } %I, 1
12227       // with
12228       // %X = extractvalue { i32, { i32 } } %A, 1
12229       // %E = insertvalue { i32 } %X, i32 42, 0
12230       // by switching the order of the insert and extract (though the
12231       // insertvalue should be left in, since it may have other uses).
12232       Value *NewEV = InsertNewInstBefore(
12233         ExtractValueInst::Create(IV->getAggregateOperand(),
12234                                  EV.idx_begin(), EV.idx_end()),
12235         EV);
12236       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12237                                      insi, inse);
12238     }
12239     if (insi == inse)
12240       // The insert list is a prefix of the extract list
12241       // We can simply remove the common indices from the extract and make it
12242       // operate on the inserted value instead of the insertvalue result.
12243       // i.e., replace
12244       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12245       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12246       // with
12247       // %E extractvalue { i32 } { i32 42 }, 0
12248       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12249                                       exti, exte);
12250   }
12251   // Can't simplify extracts from other values. Note that nested extracts are
12252   // already simplified implicitely by the above (extract ( extract (insert) )
12253   // will be translated into extract ( insert ( extract ) ) first and then just
12254   // the value inserted, if appropriate).
12255   return 0;
12256 }
12257
12258 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12259 /// is to leave as a vector operation.
12260 static bool CheapToScalarize(Value *V, bool isConstant) {
12261   if (isa<ConstantAggregateZero>(V)) 
12262     return true;
12263   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12264     if (isConstant) return true;
12265     // If all elts are the same, we can extract.
12266     Constant *Op0 = C->getOperand(0);
12267     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12268       if (C->getOperand(i) != Op0)
12269         return false;
12270     return true;
12271   }
12272   Instruction *I = dyn_cast<Instruction>(V);
12273   if (!I) return false;
12274   
12275   // Insert element gets simplified to the inserted element or is deleted if
12276   // this is constant idx extract element and its a constant idx insertelt.
12277   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12278       isa<ConstantInt>(I->getOperand(2)))
12279     return true;
12280   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12281     return true;
12282   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12283     if (BO->hasOneUse() &&
12284         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12285          CheapToScalarize(BO->getOperand(1), isConstant)))
12286       return true;
12287   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12288     if (CI->hasOneUse() &&
12289         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12290          CheapToScalarize(CI->getOperand(1), isConstant)))
12291       return true;
12292   
12293   return false;
12294 }
12295
12296 /// Read and decode a shufflevector mask.
12297 ///
12298 /// It turns undef elements into values that are larger than the number of
12299 /// elements in the input.
12300 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12301   unsigned NElts = SVI->getType()->getNumElements();
12302   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12303     return std::vector<unsigned>(NElts, 0);
12304   if (isa<UndefValue>(SVI->getOperand(2)))
12305     return std::vector<unsigned>(NElts, 2*NElts);
12306
12307   std::vector<unsigned> Result;
12308   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12309   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12310     if (isa<UndefValue>(*i))
12311       Result.push_back(NElts*2);  // undef -> 8
12312     else
12313       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12314   return Result;
12315 }
12316
12317 /// FindScalarElement - Given a vector and an element number, see if the scalar
12318 /// value is already around as a register, for example if it were inserted then
12319 /// extracted from the vector.
12320 static Value *FindScalarElement(Value *V, unsigned EltNo,
12321                                 LLVMContext *Context) {
12322   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12323   const VectorType *PTy = cast<VectorType>(V->getType());
12324   unsigned Width = PTy->getNumElements();
12325   if (EltNo >= Width)  // Out of range access.
12326     return Context->getUndef(PTy->getElementType());
12327   
12328   if (isa<UndefValue>(V))
12329     return Context->getUndef(PTy->getElementType());
12330   else if (isa<ConstantAggregateZero>(V))
12331     return Context->getNullValue(PTy->getElementType());
12332   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12333     return CP->getOperand(EltNo);
12334   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12335     // If this is an insert to a variable element, we don't know what it is.
12336     if (!isa<ConstantInt>(III->getOperand(2))) 
12337       return 0;
12338     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12339     
12340     // If this is an insert to the element we are looking for, return the
12341     // inserted value.
12342     if (EltNo == IIElt) 
12343       return III->getOperand(1);
12344     
12345     // Otherwise, the insertelement doesn't modify the value, recurse on its
12346     // vector input.
12347     return FindScalarElement(III->getOperand(0), EltNo, Context);
12348   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12349     unsigned LHSWidth =
12350       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12351     unsigned InEl = getShuffleMask(SVI)[EltNo];
12352     if (InEl < LHSWidth)
12353       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12354     else if (InEl < LHSWidth*2)
12355       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12356     else
12357       return Context->getUndef(PTy->getElementType());
12358   }
12359   
12360   // Otherwise, we don't know.
12361   return 0;
12362 }
12363
12364 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12365   // If vector val is undef, replace extract with scalar undef.
12366   if (isa<UndefValue>(EI.getOperand(0)))
12367     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12368
12369   // If vector val is constant 0, replace extract with scalar 0.
12370   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12371     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12372   
12373   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12374     // If vector val is constant with all elements the same, replace EI with
12375     // that element. When the elements are not identical, we cannot replace yet
12376     // (we do that below, but only when the index is constant).
12377     Constant *op0 = C->getOperand(0);
12378     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12379       if (C->getOperand(i) != op0) {
12380         op0 = 0; 
12381         break;
12382       }
12383     if (op0)
12384       return ReplaceInstUsesWith(EI, op0);
12385   }
12386   
12387   // If extracting a specified index from the vector, see if we can recursively
12388   // find a previously computed scalar that was inserted into the vector.
12389   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12390     unsigned IndexVal = IdxC->getZExtValue();
12391     unsigned VectorWidth = 
12392       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12393       
12394     // If this is extracting an invalid index, turn this into undef, to avoid
12395     // crashing the code below.
12396     if (IndexVal >= VectorWidth)
12397       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12398     
12399     // This instruction only demands the single element from the input vector.
12400     // If the input vector has a single use, simplify it based on this use
12401     // property.
12402     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12403       APInt UndefElts(VectorWidth, 0);
12404       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12405       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12406                                                 DemandedMask, UndefElts)) {
12407         EI.setOperand(0, V);
12408         return &EI;
12409       }
12410     }
12411     
12412     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12413       return ReplaceInstUsesWith(EI, Elt);
12414     
12415     // If the this extractelement is directly using a bitcast from a vector of
12416     // the same number of elements, see if we can find the source element from
12417     // it.  In this case, we will end up needing to bitcast the scalars.
12418     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12419       if (const VectorType *VT = 
12420               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12421         if (VT->getNumElements() == VectorWidth)
12422           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12423                                              IndexVal, Context))
12424             return new BitCastInst(Elt, EI.getType());
12425     }
12426   }
12427   
12428   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12429     if (I->hasOneUse()) {
12430       // Push extractelement into predecessor operation if legal and
12431       // profitable to do so
12432       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12433         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12434         if (CheapToScalarize(BO, isConstantElt)) {
12435           ExtractElementInst *newEI0 = 
12436             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12437                                    EI.getName()+".lhs");
12438           ExtractElementInst *newEI1 =
12439             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12440                                    EI.getName()+".rhs");
12441           InsertNewInstBefore(newEI0, EI);
12442           InsertNewInstBefore(newEI1, EI);
12443           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12444         }
12445       } else if (isa<LoadInst>(I)) {
12446         unsigned AS = 
12447           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12448         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12449                                   Context->getPointerType(EI.getType(), AS),EI);
12450         GetElementPtrInst *GEP =
12451           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12452         InsertNewInstBefore(GEP, EI);
12453         return new LoadInst(GEP);
12454       }
12455     }
12456     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12457       // Extracting the inserted element?
12458       if (IE->getOperand(2) == EI.getOperand(1))
12459         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12460       // If the inserted and extracted elements are constants, they must not
12461       // be the same value, extract from the pre-inserted value instead.
12462       if (isa<Constant>(IE->getOperand(2)) &&
12463           isa<Constant>(EI.getOperand(1))) {
12464         AddUsesToWorkList(EI);
12465         EI.setOperand(0, IE->getOperand(0));
12466         return &EI;
12467       }
12468     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12469       // If this is extracting an element from a shufflevector, figure out where
12470       // it came from and extract from the appropriate input element instead.
12471       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12472         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12473         Value *Src;
12474         unsigned LHSWidth =
12475           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12476
12477         if (SrcIdx < LHSWidth)
12478           Src = SVI->getOperand(0);
12479         else if (SrcIdx < LHSWidth*2) {
12480           SrcIdx -= LHSWidth;
12481           Src = SVI->getOperand(1);
12482         } else {
12483           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12484         }
12485         return new ExtractElementInst(Src,
12486                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12487       }
12488     }
12489   }
12490   return 0;
12491 }
12492
12493 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12494 /// elements from either LHS or RHS, return the shuffle mask and true. 
12495 /// Otherwise, return false.
12496 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12497                                          std::vector<Constant*> &Mask,
12498                                          LLVMContext *Context) {
12499   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12500          "Invalid CollectSingleShuffleElements");
12501   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12502
12503   if (isa<UndefValue>(V)) {
12504     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12505     return true;
12506   } else if (V == LHS) {
12507     for (unsigned i = 0; i != NumElts; ++i)
12508       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12509     return true;
12510   } else if (V == RHS) {
12511     for (unsigned i = 0; i != NumElts; ++i)
12512       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12513     return true;
12514   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12515     // If this is an insert of an extract from some other vector, include it.
12516     Value *VecOp    = IEI->getOperand(0);
12517     Value *ScalarOp = IEI->getOperand(1);
12518     Value *IdxOp    = IEI->getOperand(2);
12519     
12520     if (!isa<ConstantInt>(IdxOp))
12521       return false;
12522     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12523     
12524     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12525       // Okay, we can handle this if the vector we are insertinting into is
12526       // transitively ok.
12527       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12528         // If so, update the mask to reflect the inserted undef.
12529         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12530         return true;
12531       }      
12532     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12533       if (isa<ConstantInt>(EI->getOperand(1)) &&
12534           EI->getOperand(0)->getType() == V->getType()) {
12535         unsigned ExtractedIdx =
12536           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12537         
12538         // This must be extracting from either LHS or RHS.
12539         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12540           // Okay, we can handle this if the vector we are insertinting into is
12541           // transitively ok.
12542           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12543             // If so, update the mask to reflect the inserted value.
12544             if (EI->getOperand(0) == LHS) {
12545               Mask[InsertedIdx % NumElts] = 
12546                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12547             } else {
12548               assert(EI->getOperand(0) == RHS);
12549               Mask[InsertedIdx % NumElts] = 
12550                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12551               
12552             }
12553             return true;
12554           }
12555         }
12556       }
12557     }
12558   }
12559   // TODO: Handle shufflevector here!
12560   
12561   return false;
12562 }
12563
12564 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12565 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12566 /// that computes V and the LHS value of the shuffle.
12567 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12568                                      Value *&RHS, LLVMContext *Context) {
12569   assert(isa<VectorType>(V->getType()) && 
12570          (RHS == 0 || V->getType() == RHS->getType()) &&
12571          "Invalid shuffle!");
12572   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12573
12574   if (isa<UndefValue>(V)) {
12575     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12576     return V;
12577   } else if (isa<ConstantAggregateZero>(V)) {
12578     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12579     return V;
12580   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12581     // If this is an insert of an extract from some other vector, include it.
12582     Value *VecOp    = IEI->getOperand(0);
12583     Value *ScalarOp = IEI->getOperand(1);
12584     Value *IdxOp    = IEI->getOperand(2);
12585     
12586     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12587       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12588           EI->getOperand(0)->getType() == V->getType()) {
12589         unsigned ExtractedIdx =
12590           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12591         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12592         
12593         // Either the extracted from or inserted into vector must be RHSVec,
12594         // otherwise we'd end up with a shuffle of three inputs.
12595         if (EI->getOperand(0) == RHS || RHS == 0) {
12596           RHS = EI->getOperand(0);
12597           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12598           Mask[InsertedIdx % NumElts] = 
12599             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12600           return V;
12601         }
12602         
12603         if (VecOp == RHS) {
12604           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12605                                             RHS, Context);
12606           // Everything but the extracted element is replaced with the RHS.
12607           for (unsigned i = 0; i != NumElts; ++i) {
12608             if (i != InsertedIdx)
12609               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12610           }
12611           return V;
12612         }
12613         
12614         // If this insertelement is a chain that comes from exactly these two
12615         // vectors, return the vector and the effective shuffle.
12616         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12617                                          Context))
12618           return EI->getOperand(0);
12619         
12620       }
12621     }
12622   }
12623   // TODO: Handle shufflevector here!
12624   
12625   // Otherwise, can't do anything fancy.  Return an identity vector.
12626   for (unsigned i = 0; i != NumElts; ++i)
12627     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12628   return V;
12629 }
12630
12631 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12632   Value *VecOp    = IE.getOperand(0);
12633   Value *ScalarOp = IE.getOperand(1);
12634   Value *IdxOp    = IE.getOperand(2);
12635   
12636   // Inserting an undef or into an undefined place, remove this.
12637   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12638     ReplaceInstUsesWith(IE, VecOp);
12639   
12640   // If the inserted element was extracted from some other vector, and if the 
12641   // indexes are constant, try to turn this into a shufflevector operation.
12642   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12643     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12644         EI->getOperand(0)->getType() == IE.getType()) {
12645       unsigned NumVectorElts = IE.getType()->getNumElements();
12646       unsigned ExtractedIdx =
12647         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12648       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12649       
12650       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12651         return ReplaceInstUsesWith(IE, VecOp);
12652       
12653       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12654         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12655       
12656       // If we are extracting a value from a vector, then inserting it right
12657       // back into the same place, just use the input vector.
12658       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12659         return ReplaceInstUsesWith(IE, VecOp);      
12660       
12661       // We could theoretically do this for ANY input.  However, doing so could
12662       // turn chains of insertelement instructions into a chain of shufflevector
12663       // instructions, and right now we do not merge shufflevectors.  As such,
12664       // only do this in a situation where it is clear that there is benefit.
12665       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12666         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12667         // the values of VecOp, except then one read from EIOp0.
12668         // Build a new shuffle mask.
12669         std::vector<Constant*> Mask;
12670         if (isa<UndefValue>(VecOp))
12671           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12672         else {
12673           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12674           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12675                                                        NumVectorElts));
12676         } 
12677         Mask[InsertedIdx] = 
12678                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12679         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12680                                      Context->getConstantVector(Mask));
12681       }
12682       
12683       // If this insertelement isn't used by some other insertelement, turn it
12684       // (and any insertelements it points to), into one big shuffle.
12685       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12686         std::vector<Constant*> Mask;
12687         Value *RHS = 0;
12688         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12689         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12690         // We now have a shuffle of LHS, RHS, Mask.
12691         return new ShuffleVectorInst(LHS, RHS,
12692                                      Context->getConstantVector(Mask));
12693       }
12694     }
12695   }
12696
12697   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12698   APInt UndefElts(VWidth, 0);
12699   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12700   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12701     return &IE;
12702
12703   return 0;
12704 }
12705
12706
12707 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12708   Value *LHS = SVI.getOperand(0);
12709   Value *RHS = SVI.getOperand(1);
12710   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12711
12712   bool MadeChange = false;
12713
12714   // Undefined shuffle mask -> undefined value.
12715   if (isa<UndefValue>(SVI.getOperand(2)))
12716     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12717
12718   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12719
12720   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12721     return 0;
12722
12723   APInt UndefElts(VWidth, 0);
12724   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12725   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12726     LHS = SVI.getOperand(0);
12727     RHS = SVI.getOperand(1);
12728     MadeChange = true;
12729   }
12730   
12731   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12732   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12733   if (LHS == RHS || isa<UndefValue>(LHS)) {
12734     if (isa<UndefValue>(LHS) && LHS == RHS) {
12735       // shuffle(undef,undef,mask) -> undef.
12736       return ReplaceInstUsesWith(SVI, LHS);
12737     }
12738     
12739     // Remap any references to RHS to use LHS.
12740     std::vector<Constant*> Elts;
12741     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12742       if (Mask[i] >= 2*e)
12743         Elts.push_back(Context->getUndef(Type::Int32Ty));
12744       else {
12745         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12746             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12747           Mask[i] = 2*e;     // Turn into undef.
12748           Elts.push_back(Context->getUndef(Type::Int32Ty));
12749         } else {
12750           Mask[i] = Mask[i] % e;  // Force to LHS.
12751           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12752         }
12753       }
12754     }
12755     SVI.setOperand(0, SVI.getOperand(1));
12756     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12757     SVI.setOperand(2, Context->getConstantVector(Elts));
12758     LHS = SVI.getOperand(0);
12759     RHS = SVI.getOperand(1);
12760     MadeChange = true;
12761   }
12762   
12763   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12764   bool isLHSID = true, isRHSID = true;
12765     
12766   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12767     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12768     // Is this an identity shuffle of the LHS value?
12769     isLHSID &= (Mask[i] == i);
12770       
12771     // Is this an identity shuffle of the RHS value?
12772     isRHSID &= (Mask[i]-e == i);
12773   }
12774
12775   // Eliminate identity shuffles.
12776   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12777   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12778   
12779   // If the LHS is a shufflevector itself, see if we can combine it with this
12780   // one without producing an unusual shuffle.  Here we are really conservative:
12781   // we are absolutely afraid of producing a shuffle mask not in the input
12782   // program, because the code gen may not be smart enough to turn a merged
12783   // shuffle into two specific shuffles: it may produce worse code.  As such,
12784   // we only merge two shuffles if the result is one of the two input shuffle
12785   // masks.  In this case, merging the shuffles just removes one instruction,
12786   // which we know is safe.  This is good for things like turning:
12787   // (splat(splat)) -> splat.
12788   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12789     if (isa<UndefValue>(RHS)) {
12790       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12791
12792       std::vector<unsigned> NewMask;
12793       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12794         if (Mask[i] >= 2*e)
12795           NewMask.push_back(2*e);
12796         else
12797           NewMask.push_back(LHSMask[Mask[i]]);
12798       
12799       // If the result mask is equal to the src shuffle or this shuffle mask, do
12800       // the replacement.
12801       if (NewMask == LHSMask || NewMask == Mask) {
12802         unsigned LHSInNElts =
12803           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12804         std::vector<Constant*> Elts;
12805         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12806           if (NewMask[i] >= LHSInNElts*2) {
12807             Elts.push_back(Context->getUndef(Type::Int32Ty));
12808           } else {
12809             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12810           }
12811         }
12812         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12813                                      LHSSVI->getOperand(1),
12814                                      Context->getConstantVector(Elts));
12815       }
12816     }
12817   }
12818
12819   return MadeChange ? &SVI : 0;
12820 }
12821
12822
12823
12824
12825 /// TryToSinkInstruction - Try to move the specified instruction from its
12826 /// current block into the beginning of DestBlock, which can only happen if it's
12827 /// safe to move the instruction past all of the instructions between it and the
12828 /// end of its block.
12829 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12830   assert(I->hasOneUse() && "Invariants didn't hold!");
12831
12832   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12833   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12834     return false;
12835
12836   // Do not sink alloca instructions out of the entry block.
12837   if (isa<AllocaInst>(I) && I->getParent() ==
12838         &DestBlock->getParent()->getEntryBlock())
12839     return false;
12840
12841   // We can only sink load instructions if there is nothing between the load and
12842   // the end of block that could change the value.
12843   if (I->mayReadFromMemory()) {
12844     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12845          Scan != E; ++Scan)
12846       if (Scan->mayWriteToMemory())
12847         return false;
12848   }
12849
12850   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12851
12852   CopyPrecedingStopPoint(I, InsertPos);
12853   I->moveBefore(InsertPos);
12854   ++NumSunkInst;
12855   return true;
12856 }
12857
12858
12859 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12860 /// all reachable code to the worklist.
12861 ///
12862 /// This has a couple of tricks to make the code faster and more powerful.  In
12863 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12864 /// them to the worklist (this significantly speeds up instcombine on code where
12865 /// many instructions are dead or constant).  Additionally, if we find a branch
12866 /// whose condition is a known constant, we only visit the reachable successors.
12867 ///
12868 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12869                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12870                                        InstCombiner &IC,
12871                                        const TargetData *TD) {
12872   SmallVector<BasicBlock*, 256> Worklist;
12873   Worklist.push_back(BB);
12874
12875   while (!Worklist.empty()) {
12876     BB = Worklist.back();
12877     Worklist.pop_back();
12878     
12879     // We have now visited this block!  If we've already been here, ignore it.
12880     if (!Visited.insert(BB)) continue;
12881
12882     DbgInfoIntrinsic *DBI_Prev = NULL;
12883     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12884       Instruction *Inst = BBI++;
12885       
12886       // DCE instruction if trivially dead.
12887       if (isInstructionTriviallyDead(Inst)) {
12888         ++NumDeadInst;
12889         DOUT << "IC: DCE: " << *Inst;
12890         Inst->eraseFromParent();
12891         continue;
12892       }
12893       
12894       // ConstantProp instruction if trivially constant.
12895       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12896         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12897         Inst->replaceAllUsesWith(C);
12898         ++NumConstProp;
12899         Inst->eraseFromParent();
12900         continue;
12901       }
12902      
12903       // If there are two consecutive llvm.dbg.stoppoint calls then
12904       // it is likely that the optimizer deleted code in between these
12905       // two intrinsics. 
12906       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12907       if (DBI_Next) {
12908         if (DBI_Prev
12909             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12910             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12911           IC.RemoveFromWorkList(DBI_Prev);
12912           DBI_Prev->eraseFromParent();
12913         }
12914         DBI_Prev = DBI_Next;
12915       } else {
12916         DBI_Prev = 0;
12917       }
12918
12919       IC.AddToWorkList(Inst);
12920     }
12921
12922     // Recursively visit successors.  If this is a branch or switch on a
12923     // constant, only visit the reachable successor.
12924     TerminatorInst *TI = BB->getTerminator();
12925     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12926       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12927         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12928         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12929         Worklist.push_back(ReachableBB);
12930         continue;
12931       }
12932     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12933       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12934         // See if this is an explicit destination.
12935         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12936           if (SI->getCaseValue(i) == Cond) {
12937             BasicBlock *ReachableBB = SI->getSuccessor(i);
12938             Worklist.push_back(ReachableBB);
12939             continue;
12940           }
12941         
12942         // Otherwise it is the default destination.
12943         Worklist.push_back(SI->getSuccessor(0));
12944         continue;
12945       }
12946     }
12947     
12948     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12949       Worklist.push_back(TI->getSuccessor(i));
12950   }
12951 }
12952
12953 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12954   bool Changed = false;
12955   TD = &getAnalysis<TargetData>();
12956   
12957   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12958              << F.getNameStr() << "\n");
12959
12960   {
12961     // Do a depth-first traversal of the function, populate the worklist with
12962     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12963     // track of which blocks we visit.
12964     SmallPtrSet<BasicBlock*, 64> Visited;
12965     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12966
12967     // Do a quick scan over the function.  If we find any blocks that are
12968     // unreachable, remove any instructions inside of them.  This prevents
12969     // the instcombine code from having to deal with some bad special cases.
12970     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12971       if (!Visited.count(BB)) {
12972         Instruction *Term = BB->getTerminator();
12973         while (Term != BB->begin()) {   // Remove instrs bottom-up
12974           BasicBlock::iterator I = Term; --I;
12975
12976           DOUT << "IC: DCE: " << *I;
12977           // A debug intrinsic shouldn't force another iteration if we weren't
12978           // going to do one without it.
12979           if (!isa<DbgInfoIntrinsic>(I)) {
12980             ++NumDeadInst;
12981             Changed = true;
12982           }
12983           if (!I->use_empty())
12984             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12985           I->eraseFromParent();
12986         }
12987       }
12988   }
12989
12990   while (!Worklist.empty()) {
12991     Instruction *I = RemoveOneFromWorkList();
12992     if (I == 0) continue;  // skip null values.
12993
12994     // Check to see if we can DCE the instruction.
12995     if (isInstructionTriviallyDead(I)) {
12996       // Add operands to the worklist.
12997       if (I->getNumOperands() < 4)
12998         AddUsesToWorkList(*I);
12999       ++NumDeadInst;
13000
13001       DOUT << "IC: DCE: " << *I;
13002
13003       I->eraseFromParent();
13004       RemoveFromWorkList(I);
13005       Changed = true;
13006       continue;
13007     }
13008
13009     // Instruction isn't dead, see if we can constant propagate it.
13010     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13011       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13012
13013       // Add operands to the worklist.
13014       AddUsesToWorkList(*I);
13015       ReplaceInstUsesWith(*I, C);
13016
13017       ++NumConstProp;
13018       I->eraseFromParent();
13019       RemoveFromWorkList(I);
13020       Changed = true;
13021       continue;
13022     }
13023
13024     if (TD) {
13025       // See if we can constant fold its operands.
13026       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13027         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13028           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13029                                   F.getContext(), TD))
13030             if (NewC != CE) {
13031               i->set(NewC);
13032               Changed = true;
13033             }
13034     }
13035
13036     // See if we can trivially sink this instruction to a successor basic block.
13037     if (I->hasOneUse()) {
13038       BasicBlock *BB = I->getParent();
13039       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13040       if (UserParent != BB) {
13041         bool UserIsSuccessor = false;
13042         // See if the user is one of our successors.
13043         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13044           if (*SI == UserParent) {
13045             UserIsSuccessor = true;
13046             break;
13047           }
13048
13049         // If the user is one of our immediate successors, and if that successor
13050         // only has us as a predecessors (we'd have to split the critical edge
13051         // otherwise), we can keep going.
13052         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13053             next(pred_begin(UserParent)) == pred_end(UserParent))
13054           // Okay, the CFG is simple enough, try to sink this instruction.
13055           Changed |= TryToSinkInstruction(I, UserParent);
13056       }
13057     }
13058
13059     // Now that we have an instruction, try combining it to simplify it...
13060 #ifndef NDEBUG
13061     std::string OrigI;
13062 #endif
13063     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13064     if (Instruction *Result = visit(*I)) {
13065       ++NumCombined;
13066       // Should we replace the old instruction with a new one?
13067       if (Result != I) {
13068         DOUT << "IC: Old = " << *I
13069              << "    New = " << *Result;
13070
13071         // Everything uses the new instruction now.
13072         I->replaceAllUsesWith(Result);
13073
13074         // Push the new instruction and any users onto the worklist.
13075         AddToWorkList(Result);
13076         AddUsersToWorkList(*Result);
13077
13078         // Move the name to the new instruction first.
13079         Result->takeName(I);
13080
13081         // Insert the new instruction into the basic block...
13082         BasicBlock *InstParent = I->getParent();
13083         BasicBlock::iterator InsertPos = I;
13084
13085         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13086           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13087             ++InsertPos;
13088
13089         InstParent->getInstList().insert(InsertPos, Result);
13090
13091         // Make sure that we reprocess all operands now that we reduced their
13092         // use counts.
13093         AddUsesToWorkList(*I);
13094
13095         // Instructions can end up on the worklist more than once.  Make sure
13096         // we do not process an instruction that has been deleted.
13097         RemoveFromWorkList(I);
13098
13099         // Erase the old instruction.
13100         InstParent->getInstList().erase(I);
13101       } else {
13102 #ifndef NDEBUG
13103         DOUT << "IC: Mod = " << OrigI
13104              << "    New = " << *I;
13105 #endif
13106
13107         // If the instruction was modified, it's possible that it is now dead.
13108         // if so, remove it.
13109         if (isInstructionTriviallyDead(I)) {
13110           // Make sure we process all operands now that we are reducing their
13111           // use counts.
13112           AddUsesToWorkList(*I);
13113
13114           // Instructions may end up in the worklist more than once.  Erase all
13115           // occurrences of this instruction.
13116           RemoveFromWorkList(I);
13117           I->eraseFromParent();
13118         } else {
13119           AddToWorkList(I);
13120           AddUsersToWorkList(*I);
13121         }
13122       }
13123       Changed = true;
13124     }
13125   }
13126
13127   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13128     
13129   // Do an explicit clear, this shrinks the map if needed.
13130   WorklistMap.clear();
13131   return Changed;
13132 }
13133
13134
13135 bool InstCombiner::runOnFunction(Function &F) {
13136   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13137   
13138   bool EverMadeChange = false;
13139
13140   // Iterate while there is work to do.
13141   unsigned Iteration = 0;
13142   while (DoOneIteration(F, Iteration++))
13143     EverMadeChange = true;
13144   return EverMadeChange;
13145 }
13146
13147 FunctionPass *llvm::createInstructionCombiningPass() {
13148   return new InstCombiner();
13149 }