merge a check into a place where it is simpler.
[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/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *visitOr (BinaryOperator &I);
186     Instruction *visitXor(BinaryOperator &I);
187     Instruction *visitShl(BinaryOperator &I);
188     Instruction *visitAShr(BinaryOperator &I);
189     Instruction *visitLShr(BinaryOperator &I);
190     Instruction *commonShiftTransforms(BinaryOperator &I);
191     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
192                                       Constant *RHSC);
193     Instruction *visitFCmpInst(FCmpInst &I);
194     Instruction *visitICmpInst(ICmpInst &I);
195     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
196     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
197                                                 Instruction *LHS,
198                                                 ConstantInt *RHS);
199     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
200                                 ConstantInt *DivRHS);
201
202     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
203                              ICmpInst::Predicate Cond, Instruction &I);
204     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
205                                      BinaryOperator &I);
206     Instruction *commonCastTransforms(CastInst &CI);
207     Instruction *commonIntCastTransforms(CastInst &CI);
208     Instruction *commonPointerCastTransforms(CastInst &CI);
209     Instruction *visitTrunc(TruncInst &CI);
210     Instruction *visitZExt(ZExtInst &CI);
211     Instruction *visitSExt(SExtInst &CI);
212     Instruction *visitFPTrunc(FPTruncInst &CI);
213     Instruction *visitFPExt(CastInst &CI);
214     Instruction *visitFPToUI(FPToUIInst &FI);
215     Instruction *visitFPToSI(FPToSIInst &FI);
216     Instruction *visitUIToFP(CastInst &CI);
217     Instruction *visitSIToFP(CastInst &CI);
218     Instruction *visitPtrToInt(CastInst &CI);
219     Instruction *visitIntToPtr(IntToPtrInst &CI);
220     Instruction *visitBitCast(BitCastInst &CI);
221     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
222                                 Instruction *FI);
223     Instruction *visitSelectInst(SelectInst &SI);
224     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
225     Instruction *visitCallInst(CallInst &CI);
226     Instruction *visitInvokeInst(InvokeInst &II);
227     Instruction *visitPHINode(PHINode &PN);
228     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
229     Instruction *visitAllocationInst(AllocationInst &AI);
230     Instruction *visitFreeInst(FreeInst &FI);
231     Instruction *visitLoadInst(LoadInst &LI);
232     Instruction *visitStoreInst(StoreInst &SI);
233     Instruction *visitBranchInst(BranchInst &BI);
234     Instruction *visitSwitchInst(SwitchInst &SI);
235     Instruction *visitInsertElementInst(InsertElementInst &IE);
236     Instruction *visitExtractElementInst(ExtractElementInst &EI);
237     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
238     Instruction *visitExtractValueInst(ExtractValueInst &EV);
239
240     // visitInstruction - Specify what to return for unhandled instructions...
241     Instruction *visitInstruction(Instruction &I) { return 0; }
242
243   private:
244     Instruction *visitCallSite(CallSite CS);
245     bool transformConstExprCastCall(CallSite CS);
246     Instruction *transformCallThroughTrampoline(CallSite CS);
247     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
248                                    bool DoXform = true);
249     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
250
251   public:
252     // InsertNewInstBefore - insert an instruction New before instruction Old
253     // in the program.  Add the new instruction to the worklist.
254     //
255     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
256       assert(New && New->getParent() == 0 &&
257              "New instruction already inserted into a basic block!");
258       BasicBlock *BB = Old.getParent();
259       BB->getInstList().insert(&Old, New);  // Insert inst
260       AddToWorkList(New);
261       return New;
262     }
263
264     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
265     /// This also adds the cast to the worklist.  Finally, this returns the
266     /// cast.
267     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
268                             Instruction &Pos) {
269       if (V->getType() == Ty) return V;
270
271       if (Constant *CV = dyn_cast<Constant>(V))
272         return ConstantExpr::getCast(opc, CV, Ty);
273       
274       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
275       AddToWorkList(C);
276       return C;
277     }
278         
279     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
280       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
281     }
282
283
284     // ReplaceInstUsesWith - This method is to be used when an instruction is
285     // found to be dead, replacable with another preexisting expression.  Here
286     // we add all uses of I to the worklist, replace all uses of I with the new
287     // value, then return I, so that the inst combiner will know that I was
288     // modified.
289     //
290     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
291       AddUsersToWorkList(I);         // Add all modified instrs to worklist
292       if (&I != V) {
293         I.replaceAllUsesWith(V);
294         return &I;
295       } else {
296         // If we are replacing the instruction with itself, this must be in a
297         // segment of unreachable code, so just clobber the instruction.
298         I.replaceAllUsesWith(UndefValue::get(I.getType()));
299         return &I;
300       }
301     }
302
303     // UpdateValueUsesWith - This method is to be used when an value is
304     // found to be replacable with another preexisting expression or was
305     // updated.  Here we add all uses of I to the worklist, replace all uses of
306     // I with the new value (unless the instruction was just updated), then
307     // return true, so that the inst combiner will know that I was modified.
308     //
309     bool UpdateValueUsesWith(Value *Old, Value *New) {
310       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
311       if (Old != New)
312         Old->replaceAllUsesWith(New);
313       if (Instruction *I = dyn_cast<Instruction>(Old))
314         AddToWorkList(I);
315       if (Instruction *I = dyn_cast<Instruction>(New))
316         AddToWorkList(I);
317       return true;
318     }
319     
320     // EraseInstFromFunction - When dealing with an instruction that has side
321     // effects or produces a void value, we can't rely on DCE to delete the
322     // instruction.  Instead, visit methods should return the value returned by
323     // this function.
324     Instruction *EraseInstFromFunction(Instruction &I) {
325       assert(I.use_empty() && "Cannot erase instruction that is used!");
326       AddUsesToWorkList(I);
327       RemoveFromWorkList(&I);
328       I.eraseFromParent();
329       return 0;  // Don't do anything with FI
330     }
331         
332     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333                            APInt &KnownOne, unsigned Depth = 0) const {
334       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335     }
336     
337     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
338                            unsigned Depth = 0) const {
339       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340     }
341     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342       return llvm::ComputeNumSignBits(Op, TD, Depth);
343     }
344
345   private:
346     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
347     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
348     /// casts that are known to not do anything...
349     ///
350     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
351                                    Value *V, const Type *DestTy,
352                                    Instruction *InsertBefore);
353
354     /// SimplifyCommutative - This performs a few simplifications for 
355     /// commutative operators.
356     bool SimplifyCommutative(BinaryOperator &I);
357
358     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
359     /// most-complex to least-complex order.
360     bool SimplifyCompare(CmpInst &I);
361
362     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
363     /// on the demanded bits.
364     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
365                               APInt& KnownZero, APInt& KnownOne,
366                               unsigned Depth = 0);
367
368     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
369                                       uint64_t &UndefElts, unsigned Depth = 0);
370       
371     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
372     // PHI node as operand #0, see if we can fold the instruction into the PHI
373     // (which is only possible if all operands to the PHI are constants).
374     Instruction *FoldOpIntoPhi(Instruction &I);
375
376     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
377     // operator and they all are only used by the PHI, PHI together their
378     // inputs, and do the operation once, to the result of the PHI.
379     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
380     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
381     
382     
383     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
384                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
385     
386     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
387                               bool isSub, Instruction &I);
388     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
389                                  bool isSigned, bool Inside, Instruction &IB);
390     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
391     Instruction *MatchBSwap(BinaryOperator &I);
392     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
393     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
394     Instruction *SimplifyMemSet(MemSetInst *MI);
395
396
397     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
398
399     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
400                                     unsigned CastOpc,
401                                     int &NumCastsRemoved);
402     unsigned GetOrEnforceKnownAlignment(Value *V,
403                                         unsigned PrefAlign = 0);
404
405   };
406 }
407
408 char InstCombiner::ID = 0;
409 static RegisterPass<InstCombiner>
410 X("instcombine", "Combine redundant instructions");
411
412 // getComplexity:  Assign a complexity or rank value to LLVM Values...
413 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
414 static unsigned getComplexity(Value *V) {
415   if (isa<Instruction>(V)) {
416     if (BinaryOperator::isNeg(V) || 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   return Instruction::CastOps(
489       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
490                                      DstTy, TD->getIntPtrType()));
491 }
492
493 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
494 /// in any code being generated.  It does not require codegen if V is simple
495 /// enough or if the cast can be folded into other casts.
496 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
497                               const Type *Ty, TargetData *TD) {
498   if (V->getType() == Ty || isa<Constant>(V)) return false;
499   
500   // If this is another cast that can be eliminated, it isn't codegen either.
501   if (const CastInst *CI = dyn_cast<CastInst>(V))
502     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
503       return false;
504   return true;
505 }
506
507 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
508 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
509 /// casts that are known to not do anything...
510 ///
511 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
512                                              Value *V, const Type *DestTy,
513                                              Instruction *InsertBefore) {
514   if (V->getType() == DestTy) return V;
515   if (Constant *C = dyn_cast<Constant>(V))
516     return ConstantExpr::getCast(opcode, C, DestTy);
517   
518   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
519 }
520
521 // SimplifyCommutative - This performs a few simplifications for commutative
522 // operators:
523 //
524 //  1. Order operands such that they are listed from right (least complex) to
525 //     left (most complex).  This puts constants before unary operators before
526 //     binary operators.
527 //
528 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
529 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
530 //
531 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
532   bool Changed = false;
533   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
534     Changed = !I.swapOperands();
535
536   if (!I.isAssociative()) return Changed;
537   Instruction::BinaryOps Opcode = I.getOpcode();
538   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
539     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
540       if (isa<Constant>(I.getOperand(1))) {
541         Constant *Folded = ConstantExpr::get(I.getOpcode(),
542                                              cast<Constant>(I.getOperand(1)),
543                                              cast<Constant>(Op->getOperand(1)));
544         I.setOperand(0, Op->getOperand(0));
545         I.setOperand(1, Folded);
546         return true;
547       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
548         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
549             isOnlyUse(Op) && isOnlyUse(Op1)) {
550           Constant *C1 = cast<Constant>(Op->getOperand(1));
551           Constant *C2 = cast<Constant>(Op1->getOperand(1));
552
553           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
554           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
555           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
556                                                     Op1->getOperand(0),
557                                                     Op1->getName(), &I);
558           AddToWorkList(New);
559           I.setOperand(0, New);
560           I.setOperand(1, Folded);
561           return true;
562         }
563     }
564   return Changed;
565 }
566
567 /// SimplifyCompare - For a CmpInst this function just orders the operands
568 /// so that theyare listed from right (least complex) to left (most complex).
569 /// This puts constants before unary operators before binary operators.
570 bool InstCombiner::SimplifyCompare(CmpInst &I) {
571   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
572     return false;
573   I.swapOperands();
574   // Compare instructions are not associative so there's nothing else we can do.
575   return true;
576 }
577
578 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
579 // if the LHS is a constant zero (which is the 'negate' form).
580 //
581 static inline Value *dyn_castNegVal(Value *V) {
582   if (BinaryOperator::isNeg(V))
583     return BinaryOperator::getNegArgument(V);
584
585   // Constants can be considered to be negated values if they can be folded.
586   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
587     return ConstantExpr::getNeg(C);
588
589   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
590     if (C->getType()->getElementType()->isInteger())
591       return ConstantExpr::getNeg(C);
592
593   return 0;
594 }
595
596 static inline Value *dyn_castNotVal(Value *V) {
597   if (BinaryOperator::isNot(V))
598     return BinaryOperator::getNotArgument(V);
599
600   // Constants can be considered to be not'ed values...
601   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
602     return ConstantInt::get(~C->getValue());
603   return 0;
604 }
605
606 // dyn_castFoldableMul - If this value is a multiply that can be folded into
607 // other computations (because it has a constant operand), return the
608 // non-constant operand of the multiply, and set CST to point to the multiplier.
609 // Otherwise, return null.
610 //
611 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
612   if (V->hasOneUse() && V->getType()->isInteger())
613     if (Instruction *I = dyn_cast<Instruction>(V)) {
614       if (I->getOpcode() == Instruction::Mul)
615         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
616           return I->getOperand(0);
617       if (I->getOpcode() == Instruction::Shl)
618         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
619           // The multiplier is really 1 << CST.
620           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
621           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
622           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
623           return I->getOperand(0);
624         }
625     }
626   return 0;
627 }
628
629 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
630 /// expression, return it.
631 static User *dyn_castGetElementPtr(Value *V) {
632   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
633   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634     if (CE->getOpcode() == Instruction::GetElementPtr)
635       return cast<User>(V);
636   return false;
637 }
638
639 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
640 /// opcode value. Otherwise return UserOp1.
641 static unsigned getOpcode(const Value *V) {
642   if (const Instruction *I = dyn_cast<Instruction>(V))
643     return I->getOpcode();
644   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
645     return CE->getOpcode();
646   // Use UserOp1 to mean there's no opcode.
647   return Instruction::UserOp1;
648 }
649
650 /// AddOne - Add one to a ConstantInt
651 static ConstantInt *AddOne(ConstantInt *C) {
652   APInt Val(C->getValue());
653   return ConstantInt::get(++Val);
654 }
655 /// SubOne - Subtract one from a ConstantInt
656 static ConstantInt *SubOne(ConstantInt *C) {
657   APInt Val(C->getValue());
658   return ConstantInt::get(--Val);
659 }
660 /// Add - Add two ConstantInts together
661 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
662   return ConstantInt::get(C1->getValue() + C2->getValue());
663 }
664 /// And - Bitwise AND two ConstantInts together
665 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
666   return ConstantInt::get(C1->getValue() & C2->getValue());
667 }
668 /// Subtract - Subtract one ConstantInt from another
669 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
670   return ConstantInt::get(C1->getValue() - C2->getValue());
671 }
672 /// Multiply - Multiply two ConstantInts together
673 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
674   return ConstantInt::get(C1->getValue() * C2->getValue());
675 }
676 /// MultiplyOverflows - True if the multiply can not be expressed in an int
677 /// this size.
678 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
679   uint32_t W = C1->getBitWidth();
680   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681   if (sign) {
682     LHSExt.sext(W * 2);
683     RHSExt.sext(W * 2);
684   } else {
685     LHSExt.zext(W * 2);
686     RHSExt.zext(W * 2);
687   }
688
689   APInt MulExt = LHSExt * RHSExt;
690
691   if (sign) {
692     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694     return MulExt.slt(Min) || MulExt.sgt(Max);
695   } else 
696     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
697 }
698
699
700 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
701 /// specified instruction is a constant integer.  If so, check to see if there
702 /// are any bits set in the constant that are not demanded.  If so, shrink the
703 /// constant and return true.
704 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
705                                    APInt Demanded) {
706   assert(I && "No instruction?");
707   assert(OpNo < I->getNumOperands() && "Operand index too large");
708
709   // If the operand is not a constant integer, nothing to do.
710   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711   if (!OpC) return false;
712
713   // If there are no bits set that aren't demanded, nothing to do.
714   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715   if ((~Demanded & OpC->getValue()) == 0)
716     return false;
717
718   // This instruction is producing bits that are not demanded. Shrink the RHS.
719   Demanded &= OpC->getValue();
720   I->setOperand(OpNo, ConstantInt::get(Demanded));
721   return true;
722 }
723
724 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
725 // set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
727 // min/max.
728 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
729                                                    const APInt& KnownZero,
730                                                    const APInt& KnownOne,
731                                                    APInt& Min, APInt& Max) {
732   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
733   assert(KnownZero.getBitWidth() == BitWidth && 
734          KnownOne.getBitWidth() == BitWidth &&
735          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
736          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
737   APInt UnknownBits = ~(KnownZero|KnownOne);
738
739   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
740   // bit if it is unknown.
741   Min = KnownOne;
742   Max = KnownOne|UnknownBits;
743   
744   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
745     Min.set(BitWidth-1);
746     Max.clear(BitWidth-1);
747   }
748 }
749
750 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
751 // a set of known zero and one bits, compute the maximum and minimum values that
752 // could have the specified known zero and known one bits, returning them in
753 // min/max.
754 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
755                                                      const APInt &KnownZero,
756                                                      const APInt &KnownOne,
757                                                      APInt &Min, APInt &Max) {
758   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
759   assert(KnownZero.getBitWidth() == BitWidth && 
760          KnownOne.getBitWidth() == BitWidth &&
761          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
762          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
763   APInt UnknownBits = ~(KnownZero|KnownOne);
764   
765   // The minimum value is when the unknown bits are all zeros.
766   Min = KnownOne;
767   // The maximum value is when the unknown bits are all ones.
768   Max = KnownOne|UnknownBits;
769 }
770
771 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
772 /// value based on the demanded bits. When this function is called, it is known
773 /// that only the bits set in DemandedMask of the result of V are ever used
774 /// downstream. Consequently, depending on the mask and V, it may be possible
775 /// to replace V with a constant or one of its operands. In such cases, this
776 /// function does the replacement and returns true. In all other cases, it
777 /// returns false after analyzing the expression and setting KnownOne and known
778 /// to be one in the expression. KnownZero contains all the bits that are known
779 /// to be zero in the expression. These are provided to potentially allow the
780 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
781 /// the expression. KnownOne and KnownZero always follow the invariant that 
782 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
783 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
784 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
785 /// and KnownOne must all be the same.
786 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
787                                         APInt& KnownZero, APInt& KnownOne,
788                                         unsigned Depth) {
789   assert(V != 0 && "Null pointer of Value???");
790   assert(Depth <= 6 && "Limit Search Depth");
791   uint32_t BitWidth = DemandedMask.getBitWidth();
792   const IntegerType *VTy = cast<IntegerType>(V->getType());
793   assert(VTy->getBitWidth() == BitWidth && 
794          KnownZero.getBitWidth() == BitWidth && 
795          KnownOne.getBitWidth() == BitWidth &&
796          "Value *V, DemandedMask, KnownZero and KnownOne \
797           must have same BitWidth");
798   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
799     // We know all of the bits for a constant!
800     KnownOne = CI->getValue() & DemandedMask;
801     KnownZero = ~KnownOne & DemandedMask;
802     return false;
803   }
804   
805   KnownZero.clear(); 
806   KnownOne.clear();
807   if (!V->hasOneUse()) {    // Other users may use these bits.
808     if (Depth != 0) {       // Not at the root.
809       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
810       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
811       return false;
812     }
813     // If this is the root being simplified, allow it to have multiple uses,
814     // just set the DemandedMask to all bits.
815     DemandedMask = APInt::getAllOnesValue(BitWidth);
816   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
817     if (V != UndefValue::get(VTy))
818       return UpdateValueUsesWith(V, UndefValue::get(VTy));
819     return false;
820   } else if (Depth == 6) {        // Limit search depth.
821     return false;
822   }
823   
824   Instruction *I = dyn_cast<Instruction>(V);
825   if (!I) return false;        // Only analyze instructions.
826
827   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
828   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
829   switch (I->getOpcode()) {
830   default:
831     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
832     break;
833   case Instruction::And:
834     // If either the LHS or the RHS are Zero, the result is zero.
835     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
836                              RHSKnownZero, RHSKnownOne, Depth+1))
837       return true;
838     assert((RHSKnownZero & RHSKnownOne) == 0 && 
839            "Bits known to be one AND zero?"); 
840
841     // If something is known zero on the RHS, the bits aren't demanded on the
842     // LHS.
843     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844                              LHSKnownZero, LHSKnownOne, Depth+1))
845       return true;
846     assert((LHSKnownZero & LHSKnownOne) == 0 && 
847            "Bits known to be one AND zero?"); 
848
849     // If all of the demanded bits are known 1 on one side, return the other.
850     // These bits cannot contribute to the result of the 'and'.
851     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
852         (DemandedMask & ~LHSKnownZero))
853       return UpdateValueUsesWith(I, I->getOperand(0));
854     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
855         (DemandedMask & ~RHSKnownZero))
856       return UpdateValueUsesWith(I, I->getOperand(1));
857     
858     // If all of the demanded bits in the inputs are known zeros, return zero.
859     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
860       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
861       
862     // If the RHS is a constant, see if we can simplify it.
863     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
864       return UpdateValueUsesWith(I, I);
865       
866     // Output known-1 bits are only known if set in both the LHS & RHS.
867     RHSKnownOne &= LHSKnownOne;
868     // Output known-0 are known to be clear if zero in either the LHS | RHS.
869     RHSKnownZero |= LHSKnownZero;
870     break;
871   case Instruction::Or:
872     // If either the LHS or the RHS are One, the result is One.
873     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
874                              RHSKnownZero, RHSKnownOne, Depth+1))
875       return true;
876     assert((RHSKnownZero & RHSKnownOne) == 0 && 
877            "Bits known to be one AND zero?"); 
878     // If something is known one on the RHS, the bits aren't demanded on the
879     // LHS.
880     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
881                              LHSKnownZero, LHSKnownOne, Depth+1))
882       return true;
883     assert((LHSKnownZero & LHSKnownOne) == 0 && 
884            "Bits known to be one AND zero?"); 
885     
886     // If all of the demanded bits are known zero on one side, return the other.
887     // These bits cannot contribute to the result of the 'or'.
888     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
889         (DemandedMask & ~LHSKnownOne))
890       return UpdateValueUsesWith(I, I->getOperand(0));
891     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
892         (DemandedMask & ~RHSKnownOne))
893       return UpdateValueUsesWith(I, I->getOperand(1));
894
895     // If all of the potentially set bits on one side are known to be set on
896     // the other side, just use the 'other' side.
897     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
898         (DemandedMask & (~RHSKnownZero)))
899       return UpdateValueUsesWith(I, I->getOperand(0));
900     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
901         (DemandedMask & (~LHSKnownZero)))
902       return UpdateValueUsesWith(I, I->getOperand(1));
903         
904     // If the RHS is a constant, see if we can simplify it.
905     if (ShrinkDemandedConstant(I, 1, DemandedMask))
906       return UpdateValueUsesWith(I, I);
907           
908     // Output known-0 bits are only known if clear in both the LHS & RHS.
909     RHSKnownZero &= LHSKnownZero;
910     // Output known-1 are known to be set if set in either the LHS | RHS.
911     RHSKnownOne |= LHSKnownOne;
912     break;
913   case Instruction::Xor: {
914     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
915                              RHSKnownZero, RHSKnownOne, Depth+1))
916       return true;
917     assert((RHSKnownZero & RHSKnownOne) == 0 && 
918            "Bits known to be one AND zero?"); 
919     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
920                              LHSKnownZero, LHSKnownOne, Depth+1))
921       return true;
922     assert((LHSKnownZero & LHSKnownOne) == 0 && 
923            "Bits known to be one AND zero?"); 
924     
925     // If all of the demanded bits are known zero on one side, return the other.
926     // These bits cannot contribute to the result of the 'xor'.
927     if ((DemandedMask & RHSKnownZero) == DemandedMask)
928       return UpdateValueUsesWith(I, I->getOperand(0));
929     if ((DemandedMask & LHSKnownZero) == DemandedMask)
930       return UpdateValueUsesWith(I, I->getOperand(1));
931     
932     // Output known-0 bits are known if clear or set in both the LHS & RHS.
933     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
934                          (RHSKnownOne & LHSKnownOne);
935     // Output known-1 are known to be set if set in only one of the LHS, RHS.
936     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
937                         (RHSKnownOne & LHSKnownZero);
938     
939     // If all of the demanded bits are known to be zero on one side or the
940     // other, turn this into an *inclusive* or.
941     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
942     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
943       Instruction *Or =
944         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
945                                  I->getName());
946       InsertNewInstBefore(Or, *I);
947       return UpdateValueUsesWith(I, Or);
948     }
949     
950     // If all of the demanded bits on one side are known, and all of the set
951     // bits on that side are also known to be set on the other side, turn this
952     // into an AND, as we know the bits will be cleared.
953     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
954     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
955       // all known
956       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
957         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
958         Instruction *And = 
959           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
960         InsertNewInstBefore(And, *I);
961         return UpdateValueUsesWith(I, And);
962       }
963     }
964     
965     // If the RHS is a constant, see if we can simplify it.
966     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask))
968       return UpdateValueUsesWith(I, I);
969     
970     RHSKnownZero = KnownZeroOut;
971     RHSKnownOne  = KnownOneOut;
972     break;
973   }
974   case Instruction::Select:
975     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
976                              RHSKnownZero, RHSKnownOne, Depth+1))
977       return true;
978     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return true;
981     assert((RHSKnownZero & RHSKnownOne) == 0 && 
982            "Bits known to be one AND zero?"); 
983     assert((LHSKnownZero & LHSKnownOne) == 0 && 
984            "Bits known to be one AND zero?"); 
985     
986     // If the operands are constants, see if we can simplify them.
987     if (ShrinkDemandedConstant(I, 1, DemandedMask))
988       return UpdateValueUsesWith(I, I);
989     if (ShrinkDemandedConstant(I, 2, DemandedMask))
990       return UpdateValueUsesWith(I, I);
991     
992     // Only known if known in both the LHS and RHS.
993     RHSKnownOne &= LHSKnownOne;
994     RHSKnownZero &= LHSKnownZero;
995     break;
996   case Instruction::Trunc: {
997     uint32_t truncBf = 
998       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
999     DemandedMask.zext(truncBf);
1000     RHSKnownZero.zext(truncBf);
1001     RHSKnownOne.zext(truncBf);
1002     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1003                              RHSKnownZero, RHSKnownOne, Depth+1))
1004       return true;
1005     DemandedMask.trunc(BitWidth);
1006     RHSKnownZero.trunc(BitWidth);
1007     RHSKnownOne.trunc(BitWidth);
1008     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1009            "Bits known to be one AND zero?"); 
1010     break;
1011   }
1012   case Instruction::BitCast:
1013     if (!I->getOperand(0)->getType()->isInteger())
1014       return false;
1015       
1016     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1017                              RHSKnownZero, RHSKnownOne, Depth+1))
1018       return true;
1019     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1020            "Bits known to be one AND zero?"); 
1021     break;
1022   case Instruction::ZExt: {
1023     // Compute the bits in the result that are not present in the input.
1024     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1025     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1026     
1027     DemandedMask.trunc(SrcBitWidth);
1028     RHSKnownZero.trunc(SrcBitWidth);
1029     RHSKnownOne.trunc(SrcBitWidth);
1030     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1031                              RHSKnownZero, RHSKnownOne, Depth+1))
1032       return true;
1033     DemandedMask.zext(BitWidth);
1034     RHSKnownZero.zext(BitWidth);
1035     RHSKnownOne.zext(BitWidth);
1036     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1037            "Bits known to be one AND zero?"); 
1038     // The top bits are known to be zero.
1039     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1040     break;
1041   }
1042   case Instruction::SExt: {
1043     // Compute the bits in the result that are not present in the input.
1044     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1045     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1046     
1047     APInt InputDemandedBits = DemandedMask & 
1048                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1049
1050     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1051     // If any of the sign extended bits are demanded, we know that the sign
1052     // bit is demanded.
1053     if ((NewBits & DemandedMask) != 0)
1054       InputDemandedBits.set(SrcBitWidth-1);
1055       
1056     InputDemandedBits.trunc(SrcBitWidth);
1057     RHSKnownZero.trunc(SrcBitWidth);
1058     RHSKnownOne.trunc(SrcBitWidth);
1059     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1060                              RHSKnownZero, RHSKnownOne, Depth+1))
1061       return true;
1062     InputDemandedBits.zext(BitWidth);
1063     RHSKnownZero.zext(BitWidth);
1064     RHSKnownOne.zext(BitWidth);
1065     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1066            "Bits known to be one AND zero?"); 
1067       
1068     // If the sign bit of the input is known set or clear, then we know the
1069     // top bits of the result.
1070
1071     // If the input sign bit is known zero, or if the NewBits are not demanded
1072     // convert this into a zero extension.
1073     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1074     {
1075       // Convert to ZExt cast
1076       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1077       return UpdateValueUsesWith(I, NewCast);
1078     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1079       RHSKnownOne |= NewBits;
1080     }
1081     break;
1082   }
1083   case Instruction::Add: {
1084     // Figure out what the input bits are.  If the top bits of the and result
1085     // are not demanded, then the add doesn't demand them from its input
1086     // either.
1087     uint32_t NLZ = DemandedMask.countLeadingZeros();
1088       
1089     // If there is a constant on the RHS, there are a variety of xformations
1090     // we can do.
1091     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1092       // If null, this should be simplified elsewhere.  Some of the xforms here
1093       // won't work if the RHS is zero.
1094       if (RHS->isZero())
1095         break;
1096       
1097       // If the top bit of the output is demanded, demand everything from the
1098       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1099       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1100
1101       // Find information about known zero/one bits in the input.
1102       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1103                                LHSKnownZero, LHSKnownOne, Depth+1))
1104         return true;
1105
1106       // If the RHS of the add has bits set that can't affect the input, reduce
1107       // the constant.
1108       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1109         return UpdateValueUsesWith(I, I);
1110       
1111       // Avoid excess work.
1112       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1113         break;
1114       
1115       // Turn it into OR if input bits are zero.
1116       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1117         Instruction *Or =
1118           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1119                                    I->getName());
1120         InsertNewInstBefore(Or, *I);
1121         return UpdateValueUsesWith(I, Or);
1122       }
1123       
1124       // We can say something about the output known-zero and known-one bits,
1125       // depending on potential carries from the input constant and the
1126       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1127       // bits set and the RHS constant is 0x01001, then we know we have a known
1128       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1129       
1130       // To compute this, we first compute the potential carry bits.  These are
1131       // the bits which may be modified.  I'm not aware of a better way to do
1132       // this scan.
1133       const APInt& RHSVal = RHS->getValue();
1134       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1135       
1136       // Now that we know which bits have carries, compute the known-1/0 sets.
1137       
1138       // Bits are known one if they are known zero in one operand and one in the
1139       // other, and there is no input carry.
1140       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1141                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1142       
1143       // Bits are known zero if they are known zero in both operands and there
1144       // is no input carry.
1145       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1146     } else {
1147       // If the high-bits of this ADD are not demanded, then it does not demand
1148       // the high bits of its LHS or RHS.
1149       if (DemandedMask[BitWidth-1] == 0) {
1150         // Right fill the mask of bits for this ADD to demand the most
1151         // significant bit and all those below it.
1152         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1153         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1154                                  LHSKnownZero, LHSKnownOne, Depth+1))
1155           return true;
1156         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1157                                  LHSKnownZero, LHSKnownOne, Depth+1))
1158           return true;
1159       }
1160     }
1161     break;
1162   }
1163   case Instruction::Sub:
1164     // If the high-bits of this SUB are not demanded, then it does not demand
1165     // the high bits of its LHS or RHS.
1166     if (DemandedMask[BitWidth-1] == 0) {
1167       // Right fill the mask of bits for this SUB to demand the most
1168       // significant bit and all those below it.
1169       uint32_t NLZ = DemandedMask.countLeadingZeros();
1170       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1171       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1172                                LHSKnownZero, LHSKnownOne, Depth+1))
1173         return true;
1174       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1175                                LHSKnownZero, LHSKnownOne, Depth+1))
1176         return true;
1177     }
1178     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1179     // the known zeros and ones.
1180     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1181     break;
1182   case Instruction::Shl:
1183     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1184       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1185       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1186       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1187                                RHSKnownZero, RHSKnownOne, Depth+1))
1188         return true;
1189       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1190              "Bits known to be one AND zero?"); 
1191       RHSKnownZero <<= ShiftAmt;
1192       RHSKnownOne  <<= ShiftAmt;
1193       // low bits known zero.
1194       if (ShiftAmt)
1195         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1196     }
1197     break;
1198   case Instruction::LShr:
1199     // For a logical shift right
1200     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1201       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1202       
1203       // Unsigned shift right.
1204       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1205       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1206                                RHSKnownZero, RHSKnownOne, Depth+1))
1207         return true;
1208       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1209              "Bits known to be one AND zero?"); 
1210       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1211       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1212       if (ShiftAmt) {
1213         // Compute the new bits that are at the top now.
1214         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1215         RHSKnownZero |= HighBits;  // high bits known zero.
1216       }
1217     }
1218     break;
1219   case Instruction::AShr:
1220     // If this is an arithmetic shift right and only the low-bit is set, we can
1221     // always convert this into a logical shr, even if the shift amount is
1222     // variable.  The low bit of the shift cannot be an input sign bit unless
1223     // the shift amount is >= the size of the datatype, which is undefined.
1224     if (DemandedMask == 1) {
1225       // Perform the logical shift right.
1226       Value *NewVal = BinaryOperator::CreateLShr(
1227                         I->getOperand(0), I->getOperand(1), I->getName());
1228       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1229       return UpdateValueUsesWith(I, NewVal);
1230     }    
1231
1232     // If the sign bit is the only bit demanded by this ashr, then there is no
1233     // need to do it, the shift doesn't change the high bit.
1234     if (DemandedMask.isSignBit())
1235       return UpdateValueUsesWith(I, I->getOperand(0));
1236     
1237     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1238       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1239       
1240       // Signed shift right.
1241       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1242       // If any of the "high bits" are demanded, we should set the sign bit as
1243       // demanded.
1244       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1245         DemandedMaskIn.set(BitWidth-1);
1246       if (SimplifyDemandedBits(I->getOperand(0),
1247                                DemandedMaskIn,
1248                                RHSKnownZero, RHSKnownOne, Depth+1))
1249         return true;
1250       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1251              "Bits known to be one AND zero?"); 
1252       // Compute the new bits that are at the top now.
1253       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1254       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1255       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1256         
1257       // Handle the sign bits.
1258       APInt SignBit(APInt::getSignBit(BitWidth));
1259       // Adjust to where it is now in the mask.
1260       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1261         
1262       // If the input sign bit is known to be zero, or if none of the top bits
1263       // are demanded, turn this into an unsigned shift right.
1264       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1265           (HighBits & ~DemandedMask) == HighBits) {
1266         // Perform the logical shift right.
1267         Value *NewVal = BinaryOperator::CreateLShr(
1268                           I->getOperand(0), SA, I->getName());
1269         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1270         return UpdateValueUsesWith(I, NewVal);
1271       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1272         RHSKnownOne |= HighBits;
1273       }
1274     }
1275     break;
1276   case Instruction::SRem:
1277     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1278       APInt RA = Rem->getValue().abs();
1279       if (RA.isPowerOf2()) {
1280         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1281           return UpdateValueUsesWith(I, I->getOperand(0));
1282
1283         APInt LowBits = RA - 1;
1284         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1285         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1286                                  LHSKnownZero, LHSKnownOne, Depth+1))
1287           return true;
1288
1289         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1290           LHSKnownZero |= ~LowBits;
1291
1292         KnownZero |= LHSKnownZero & DemandedMask;
1293
1294         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1295       }
1296     }
1297     break;
1298   case Instruction::URem: {
1299     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1300     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1301     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1302                              KnownZero2, KnownOne2, Depth+1))
1303       return true;
1304
1305     uint32_t Leaders = KnownZero2.countLeadingOnes();
1306     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1307                              KnownZero2, KnownOne2, Depth+1))
1308       return true;
1309
1310     Leaders = std::max(Leaders,
1311                        KnownZero2.countLeadingOnes());
1312     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1313     break;
1314   }
1315   case Instruction::Call:
1316     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1317       switch (II->getIntrinsicID()) {
1318       default: break;
1319       case Intrinsic::bswap: {
1320         // If the only bits demanded come from one byte of the bswap result,
1321         // just shift the input byte into position to eliminate the bswap.
1322         unsigned NLZ = DemandedMask.countLeadingZeros();
1323         unsigned NTZ = DemandedMask.countTrailingZeros();
1324           
1325         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1326         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1327         // have 14 leading zeros, round to 8.
1328         NLZ &= ~7;
1329         NTZ &= ~7;
1330         // If we need exactly one byte, we can do this transformation.
1331         if (BitWidth-NLZ-NTZ == 8) {
1332           unsigned ResultBit = NTZ;
1333           unsigned InputBit = BitWidth-NTZ-8;
1334           
1335           // Replace this with either a left or right shift to get the byte into
1336           // the right place.
1337           Instruction *NewVal;
1338           if (InputBit > ResultBit)
1339             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1340                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1341           else
1342             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1343                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1344           NewVal->takeName(I);
1345           InsertNewInstBefore(NewVal, *I);
1346           return UpdateValueUsesWith(I, NewVal);
1347         }
1348           
1349         // TODO: Could compute known zero/one bits based on the input.
1350         break;
1351       }
1352       }
1353     }
1354     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1355     break;
1356   }
1357   
1358   // If the client is only demanding bits that we know, return the known
1359   // constant.
1360   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1361     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1362   return false;
1363 }
1364
1365
1366 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1367 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1368 /// actually used by the caller.  This method analyzes which elements of the
1369 /// operand are undef and returns that information in UndefElts.
1370 ///
1371 /// If the information about demanded elements can be used to simplify the
1372 /// operation, the operation is simplified, then the resultant value is
1373 /// returned.  This returns null if no change was made.
1374 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1375                                                 uint64_t &UndefElts,
1376                                                 unsigned Depth) {
1377   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1378   assert(VWidth <= 64 && "Vector too wide to analyze!");
1379   uint64_t EltMask = ~0ULL >> (64-VWidth);
1380   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1381
1382   if (isa<UndefValue>(V)) {
1383     // If the entire vector is undefined, just return this info.
1384     UndefElts = EltMask;
1385     return 0;
1386   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1387     UndefElts = EltMask;
1388     return UndefValue::get(V->getType());
1389   }
1390
1391   UndefElts = 0;
1392   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1393     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1394     Constant *Undef = UndefValue::get(EltTy);
1395
1396     std::vector<Constant*> Elts;
1397     for (unsigned i = 0; i != VWidth; ++i)
1398       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1399         Elts.push_back(Undef);
1400         UndefElts |= (1ULL << i);
1401       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1402         Elts.push_back(Undef);
1403         UndefElts |= (1ULL << i);
1404       } else {                               // Otherwise, defined.
1405         Elts.push_back(CP->getOperand(i));
1406       }
1407
1408     // If we changed the constant, return it.
1409     Constant *NewCP = ConstantVector::get(Elts);
1410     return NewCP != CP ? NewCP : 0;
1411   } else if (isa<ConstantAggregateZero>(V)) {
1412     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1413     // set to undef.
1414     
1415     // Check if this is identity. If so, return 0 since we are not simplifying
1416     // anything.
1417     if (DemandedElts == ((1ULL << VWidth) -1))
1418       return 0;
1419     
1420     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1421     Constant *Zero = Constant::getNullValue(EltTy);
1422     Constant *Undef = UndefValue::get(EltTy);
1423     std::vector<Constant*> Elts;
1424     for (unsigned i = 0; i != VWidth; ++i)
1425       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1426     UndefElts = DemandedElts ^ EltMask;
1427     return ConstantVector::get(Elts);
1428   }
1429   
1430   // Limit search depth.
1431   if (Depth == 10)
1432     return false;
1433
1434   // If multiple users are using the root value, procede with
1435   // simplification conservatively assuming that all elements
1436   // are needed.
1437   if (!V->hasOneUse()) {
1438     // Quit if we find multiple users of a non-root value though.
1439     // They'll be handled when it's their turn to be visited by
1440     // the main instcombine process.
1441     if (Depth != 0)
1442       // TODO: Just compute the UndefElts information recursively.
1443       return false;
1444
1445     // Conservatively assume that all elements are needed.
1446     DemandedElts = EltMask;
1447   }
1448   
1449   Instruction *I = dyn_cast<Instruction>(V);
1450   if (!I) return false;        // Only analyze instructions.
1451   
1452   bool MadeChange = false;
1453   uint64_t UndefElts2;
1454   Value *TmpV;
1455   switch (I->getOpcode()) {
1456   default: break;
1457     
1458   case Instruction::InsertElement: {
1459     // If this is a variable index, we don't know which element it overwrites.
1460     // demand exactly the same input as we produce.
1461     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1462     if (Idx == 0) {
1463       // Note that we can't propagate undef elt info, because we don't know
1464       // which elt is getting updated.
1465       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1466                                         UndefElts2, Depth+1);
1467       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1468       break;
1469     }
1470     
1471     // If this is inserting an element that isn't demanded, remove this
1472     // insertelement.
1473     unsigned IdxNo = Idx->getZExtValue();
1474     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1475       return AddSoonDeadInstToWorklist(*I, 0);
1476     
1477     // Otherwise, the element inserted overwrites whatever was there, so the
1478     // input demanded set is simpler than the output set.
1479     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1480                                       DemandedElts & ~(1ULL << IdxNo),
1481                                       UndefElts, Depth+1);
1482     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1483
1484     // The inserted element is defined.
1485     UndefElts &= ~(1ULL << IdxNo);
1486     break;
1487   }
1488   case Instruction::ShuffleVector: {
1489     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1490     uint64_t LHSVWidth =
1491       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1492     uint64_t LeftDemanded = 0, RightDemanded = 0;
1493     for (unsigned i = 0; i < VWidth; i++) {
1494       if (DemandedElts & (1ULL << i)) {
1495         unsigned MaskVal = Shuffle->getMaskValue(i);
1496         if (MaskVal != -1u) {
1497           assert(MaskVal < LHSVWidth * 2 &&
1498                  "shufflevector mask index out of range!");
1499           if (MaskVal < LHSVWidth)
1500             LeftDemanded |= 1ULL << MaskVal;
1501           else
1502             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1503         }
1504       }
1505     }
1506
1507     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1508                                       UndefElts2, Depth+1);
1509     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1510
1511     uint64_t UndefElts3;
1512     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1513                                       UndefElts3, Depth+1);
1514     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1515
1516     bool NewUndefElts = false;
1517     for (unsigned i = 0; i < VWidth; i++) {
1518       unsigned MaskVal = Shuffle->getMaskValue(i);
1519       if (MaskVal == -1u) {
1520         uint64_t NewBit = 1ULL << i;
1521         UndefElts |= NewBit;
1522       } else if (MaskVal < LHSVWidth) {
1523         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1524         NewUndefElts |= NewBit;
1525         UndefElts |= NewBit;
1526       } else {
1527         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1528         NewUndefElts |= NewBit;
1529         UndefElts |= NewBit;
1530       }
1531     }
1532
1533     if (NewUndefElts) {
1534       // Add additional discovered undefs.
1535       std::vector<Constant*> Elts;
1536       for (unsigned i = 0; i < VWidth; ++i) {
1537         if (UndefElts & (1ULL << i))
1538           Elts.push_back(UndefValue::get(Type::Int32Ty));
1539         else
1540           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1541                                           Shuffle->getMaskValue(i)));
1542       }
1543       I->setOperand(2, ConstantVector::get(Elts));
1544       MadeChange = true;
1545     }
1546     break;
1547   }
1548   case Instruction::BitCast: {
1549     // Vector->vector casts only.
1550     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1551     if (!VTy) break;
1552     unsigned InVWidth = VTy->getNumElements();
1553     uint64_t InputDemandedElts = 0;
1554     unsigned Ratio;
1555
1556     if (VWidth == InVWidth) {
1557       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1558       // elements as are demanded of us.
1559       Ratio = 1;
1560       InputDemandedElts = DemandedElts;
1561     } else if (VWidth > InVWidth) {
1562       // Untested so far.
1563       break;
1564       
1565       // If there are more elements in the result than there are in the source,
1566       // then an input element is live if any of the corresponding output
1567       // elements are live.
1568       Ratio = VWidth/InVWidth;
1569       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1570         if (DemandedElts & (1ULL << OutIdx))
1571           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1572       }
1573     } else {
1574       // Untested so far.
1575       break;
1576       
1577       // If there are more elements in the source than there are in the result,
1578       // then an input element is live if the corresponding output element is
1579       // live.
1580       Ratio = InVWidth/VWidth;
1581       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1582         if (DemandedElts & (1ULL << InIdx/Ratio))
1583           InputDemandedElts |= 1ULL << InIdx;
1584     }
1585     
1586     // div/rem demand all inputs, because they don't want divide by zero.
1587     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1588                                       UndefElts2, Depth+1);
1589     if (TmpV) {
1590       I->setOperand(0, TmpV);
1591       MadeChange = true;
1592     }
1593     
1594     UndefElts = UndefElts2;
1595     if (VWidth > InVWidth) {
1596       assert(0 && "Unimp");
1597       // If there are more elements in the result than there are in the source,
1598       // then an output element is undef if the corresponding input element is
1599       // undef.
1600       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1601         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1602           UndefElts |= 1ULL << OutIdx;
1603     } else if (VWidth < InVWidth) {
1604       assert(0 && "Unimp");
1605       // If there are more elements in the source than there are in the result,
1606       // then a result element is undef if all of the corresponding input
1607       // elements are undef.
1608       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1609       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1610         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1611           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1612     }
1613     break;
1614   }
1615   case Instruction::And:
1616   case Instruction::Or:
1617   case Instruction::Xor:
1618   case Instruction::Add:
1619   case Instruction::Sub:
1620   case Instruction::Mul:
1621     // div/rem demand all inputs, because they don't want divide by zero.
1622     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1623                                       UndefElts, Depth+1);
1624     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1626                                       UndefElts2, Depth+1);
1627     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1628       
1629     // Output elements are undefined if both are undefined.  Consider things
1630     // like undef&0.  The result is known zero, not undef.
1631     UndefElts &= UndefElts2;
1632     break;
1633     
1634   case Instruction::Call: {
1635     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1636     if (!II) break;
1637     switch (II->getIntrinsicID()) {
1638     default: break;
1639       
1640     // Binary vector operations that work column-wise.  A dest element is a
1641     // function of the corresponding input elements from the two inputs.
1642     case Intrinsic::x86_sse_sub_ss:
1643     case Intrinsic::x86_sse_mul_ss:
1644     case Intrinsic::x86_sse_min_ss:
1645     case Intrinsic::x86_sse_max_ss:
1646     case Intrinsic::x86_sse2_sub_sd:
1647     case Intrinsic::x86_sse2_mul_sd:
1648     case Intrinsic::x86_sse2_min_sd:
1649     case Intrinsic::x86_sse2_max_sd:
1650       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1651                                         UndefElts, Depth+1);
1652       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1653       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1654                                         UndefElts2, Depth+1);
1655       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1656
1657       // If only the low elt is demanded and this is a scalarizable intrinsic,
1658       // scalarize it now.
1659       if (DemandedElts == 1) {
1660         switch (II->getIntrinsicID()) {
1661         default: break;
1662         case Intrinsic::x86_sse_sub_ss:
1663         case Intrinsic::x86_sse_mul_ss:
1664         case Intrinsic::x86_sse2_sub_sd:
1665         case Intrinsic::x86_sse2_mul_sd:
1666           // TODO: Lower MIN/MAX/ABS/etc
1667           Value *LHS = II->getOperand(1);
1668           Value *RHS = II->getOperand(2);
1669           // Extract the element as scalars.
1670           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1671           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1672           
1673           switch (II->getIntrinsicID()) {
1674           default: assert(0 && "Case stmts out of sync!");
1675           case Intrinsic::x86_sse_sub_ss:
1676           case Intrinsic::x86_sse2_sub_sd:
1677             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1678                                                         II->getName()), *II);
1679             break;
1680           case Intrinsic::x86_sse_mul_ss:
1681           case Intrinsic::x86_sse2_mul_sd:
1682             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1683                                                          II->getName()), *II);
1684             break;
1685           }
1686           
1687           Instruction *New =
1688             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1689                                       II->getName());
1690           InsertNewInstBefore(New, *II);
1691           AddSoonDeadInstToWorklist(*II, 0);
1692           return New;
1693         }            
1694       }
1695         
1696       // Output elements are undefined if both are undefined.  Consider things
1697       // like undef&0.  The result is known zero, not undef.
1698       UndefElts &= UndefElts2;
1699       break;
1700     }
1701     break;
1702   }
1703   }
1704   return MadeChange ? I : 0;
1705 }
1706
1707
1708 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1709 /// function is designed to check a chain of associative operators for a
1710 /// potential to apply a certain optimization.  Since the optimization may be
1711 /// applicable if the expression was reassociated, this checks the chain, then
1712 /// reassociates the expression as necessary to expose the optimization
1713 /// opportunity.  This makes use of a special Functor, which must define
1714 /// 'shouldApply' and 'apply' methods.
1715 ///
1716 template<typename Functor>
1717 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1718   unsigned Opcode = Root.getOpcode();
1719   Value *LHS = Root.getOperand(0);
1720
1721   // Quick check, see if the immediate LHS matches...
1722   if (F.shouldApply(LHS))
1723     return F.apply(Root);
1724
1725   // Otherwise, if the LHS is not of the same opcode as the root, return.
1726   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1727   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1728     // Should we apply this transform to the RHS?
1729     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1730
1731     // If not to the RHS, check to see if we should apply to the LHS...
1732     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1733       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1734       ShouldApply = true;
1735     }
1736
1737     // If the functor wants to apply the optimization to the RHS of LHSI,
1738     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1739     if (ShouldApply) {
1740       // Now all of the instructions are in the current basic block, go ahead
1741       // and perform the reassociation.
1742       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1743
1744       // First move the selected RHS to the LHS of the root...
1745       Root.setOperand(0, LHSI->getOperand(1));
1746
1747       // Make what used to be the LHS of the root be the user of the root...
1748       Value *ExtraOperand = TmpLHSI->getOperand(1);
1749       if (&Root == TmpLHSI) {
1750         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1751         return 0;
1752       }
1753       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1754       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1755       BasicBlock::iterator ARI = &Root; ++ARI;
1756       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1757       ARI = Root;
1758
1759       // Now propagate the ExtraOperand down the chain of instructions until we
1760       // get to LHSI.
1761       while (TmpLHSI != LHSI) {
1762         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1763         // Move the instruction to immediately before the chain we are
1764         // constructing to avoid breaking dominance properties.
1765         NextLHSI->moveBefore(ARI);
1766         ARI = NextLHSI;
1767
1768         Value *NextOp = NextLHSI->getOperand(1);
1769         NextLHSI->setOperand(1, ExtraOperand);
1770         TmpLHSI = NextLHSI;
1771         ExtraOperand = NextOp;
1772       }
1773
1774       // Now that the instructions are reassociated, have the functor perform
1775       // the transformation...
1776       return F.apply(Root);
1777     }
1778
1779     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1780   }
1781   return 0;
1782 }
1783
1784 namespace {
1785
1786 // AddRHS - Implements: X + X --> X << 1
1787 struct AddRHS {
1788   Value *RHS;
1789   AddRHS(Value *rhs) : RHS(rhs) {}
1790   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1791   Instruction *apply(BinaryOperator &Add) const {
1792     return BinaryOperator::CreateShl(Add.getOperand(0),
1793                                      ConstantInt::get(Add.getType(), 1));
1794   }
1795 };
1796
1797 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1798 //                 iff C1&C2 == 0
1799 struct AddMaskingAnd {
1800   Constant *C2;
1801   AddMaskingAnd(Constant *c) : C2(c) {}
1802   bool shouldApply(Value *LHS) const {
1803     ConstantInt *C1;
1804     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1805            ConstantExpr::getAnd(C1, C2)->isNullValue();
1806   }
1807   Instruction *apply(BinaryOperator &Add) const {
1808     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1809   }
1810 };
1811
1812 }
1813
1814 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1815                                              InstCombiner *IC) {
1816   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1817     if (Constant *SOC = dyn_cast<Constant>(SO))
1818       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1819
1820     return IC->InsertNewInstBefore(CastInst::Create(
1821           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1822   }
1823
1824   // Figure out if the constant is the left or the right argument.
1825   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1826   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1827
1828   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1829     if (ConstIsRHS)
1830       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1831     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1832   }
1833
1834   Value *Op0 = SO, *Op1 = ConstOperand;
1835   if (!ConstIsRHS)
1836     std::swap(Op0, Op1);
1837   Instruction *New;
1838   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1839     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1840   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1841     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1842                           SO->getName()+".cmp");
1843   else {
1844     assert(0 && "Unknown binary instruction type!");
1845     abort();
1846   }
1847   return IC->InsertNewInstBefore(New, I);
1848 }
1849
1850 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1851 // constant as the other operand, try to fold the binary operator into the
1852 // select arguments.  This also works for Cast instructions, which obviously do
1853 // not have a second operand.
1854 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1855                                      InstCombiner *IC) {
1856   // Don't modify shared select instructions
1857   if (!SI->hasOneUse()) return 0;
1858   Value *TV = SI->getOperand(1);
1859   Value *FV = SI->getOperand(2);
1860
1861   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1862     // Bool selects with constant operands can be folded to logical ops.
1863     if (SI->getType() == Type::Int1Ty) return 0;
1864
1865     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1866     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1867
1868     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1869                               SelectFalseVal);
1870   }
1871   return 0;
1872 }
1873
1874
1875 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1876 /// node as operand #0, see if we can fold the instruction into the PHI (which
1877 /// is only possible if all operands to the PHI are constants).
1878 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1879   PHINode *PN = cast<PHINode>(I.getOperand(0));
1880   unsigned NumPHIValues = PN->getNumIncomingValues();
1881   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1882
1883   // Check to see if all of the operands of the PHI are constants.  If there is
1884   // one non-constant value, remember the BB it is.  If there is more than one
1885   // or if *it* is a PHI, bail out.
1886   BasicBlock *NonConstBB = 0;
1887   for (unsigned i = 0; i != NumPHIValues; ++i)
1888     if (!isa<Constant>(PN->getIncomingValue(i))) {
1889       if (NonConstBB) return 0;  // More than one non-const value.
1890       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1891       NonConstBB = PN->getIncomingBlock(i);
1892       
1893       // If the incoming non-constant value is in I's block, we have an infinite
1894       // loop.
1895       if (NonConstBB == I.getParent())
1896         return 0;
1897     }
1898   
1899   // If there is exactly one non-constant value, we can insert a copy of the
1900   // operation in that block.  However, if this is a critical edge, we would be
1901   // inserting the computation one some other paths (e.g. inside a loop).  Only
1902   // do this if the pred block is unconditionally branching into the phi block.
1903   if (NonConstBB) {
1904     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1905     if (!BI || !BI->isUnconditional()) return 0;
1906   }
1907
1908   // Okay, we can do the transformation: create the new PHI node.
1909   PHINode *NewPN = PHINode::Create(I.getType(), "");
1910   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1911   InsertNewInstBefore(NewPN, *PN);
1912   NewPN->takeName(PN);
1913
1914   // Next, add all of the operands to the PHI.
1915   if (I.getNumOperands() == 2) {
1916     Constant *C = cast<Constant>(I.getOperand(1));
1917     for (unsigned i = 0; i != NumPHIValues; ++i) {
1918       Value *InV = 0;
1919       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1920         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1921           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1922         else
1923           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1924       } else {
1925         assert(PN->getIncomingBlock(i) == NonConstBB);
1926         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1927           InV = BinaryOperator::Create(BO->getOpcode(),
1928                                        PN->getIncomingValue(i), C, "phitmp",
1929                                        NonConstBB->getTerminator());
1930         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1931           InV = CmpInst::Create(CI->getOpcode(), 
1932                                 CI->getPredicate(),
1933                                 PN->getIncomingValue(i), C, "phitmp",
1934                                 NonConstBB->getTerminator());
1935         else
1936           assert(0 && "Unknown binop!");
1937         
1938         AddToWorkList(cast<Instruction>(InV));
1939       }
1940       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1941     }
1942   } else { 
1943     CastInst *CI = cast<CastInst>(&I);
1944     const Type *RetTy = CI->getType();
1945     for (unsigned i = 0; i != NumPHIValues; ++i) {
1946       Value *InV;
1947       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1948         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1949       } else {
1950         assert(PN->getIncomingBlock(i) == NonConstBB);
1951         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1952                                I.getType(), "phitmp", 
1953                                NonConstBB->getTerminator());
1954         AddToWorkList(cast<Instruction>(InV));
1955       }
1956       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1957     }
1958   }
1959   return ReplaceInstUsesWith(I, NewPN);
1960 }
1961
1962
1963 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1964 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1965 /// This basically requires proving that the add in the original type would not
1966 /// overflow to change the sign bit or have a carry out.
1967 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1968   // There are different heuristics we can use for this.  Here are some simple
1969   // ones.
1970   
1971   // Add has the property that adding any two 2's complement numbers can only 
1972   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1973   // have at least two sign bits, we know that the addition of the two values will
1974   // sign extend fine.
1975   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1976     return true;
1977   
1978   
1979   // If one of the operands only has one non-zero bit, and if the other operand
1980   // has a known-zero bit in a more significant place than it (not including the
1981   // sign bit) the ripple may go up to and fill the zero, but won't change the
1982   // sign.  For example, (X & ~4) + 1.
1983   
1984   // TODO: Implement.
1985   
1986   return false;
1987 }
1988
1989
1990 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1991   bool Changed = SimplifyCommutative(I);
1992   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1993
1994   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1995     // X + undef -> undef
1996     if (isa<UndefValue>(RHS))
1997       return ReplaceInstUsesWith(I, RHS);
1998
1999     // X + 0 --> X
2000     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2001       if (RHSC->isNullValue())
2002         return ReplaceInstUsesWith(I, LHS);
2003     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2004       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2005                               (I.getType())->getValueAPF()))
2006         return ReplaceInstUsesWith(I, LHS);
2007     }
2008
2009     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2010       // X + (signbit) --> X ^ signbit
2011       const APInt& Val = CI->getValue();
2012       uint32_t BitWidth = Val.getBitWidth();
2013       if (Val == APInt::getSignBit(BitWidth))
2014         return BinaryOperator::CreateXor(LHS, RHS);
2015       
2016       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2017       // (X & 254)+1 -> (X&254)|1
2018       if (!isa<VectorType>(I.getType())) {
2019         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2020         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2021                                  KnownZero, KnownOne))
2022           return &I;
2023       }
2024
2025       // zext(i1) - 1  ->  select i1, 0, -1
2026       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2027         if (CI->isAllOnesValue() &&
2028             ZI->getOperand(0)->getType() == Type::Int1Ty)
2029           return SelectInst::Create(ZI->getOperand(0),
2030                                     Constant::getNullValue(I.getType()),
2031                                     ConstantInt::getAllOnesValue(I.getType()));
2032     }
2033
2034     if (isa<PHINode>(LHS))
2035       if (Instruction *NV = FoldOpIntoPhi(I))
2036         return NV;
2037     
2038     ConstantInt *XorRHS = 0;
2039     Value *XorLHS = 0;
2040     if (isa<ConstantInt>(RHSC) &&
2041         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2042       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2043       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2044       
2045       uint32_t Size = TySizeBits / 2;
2046       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2047       APInt CFF80Val(-C0080Val);
2048       do {
2049         if (TySizeBits > Size) {
2050           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2051           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2052           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2053               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2054             // This is a sign extend if the top bits are known zero.
2055             if (!MaskedValueIsZero(XorLHS, 
2056                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2057               Size = 0;  // Not a sign ext, but can't be any others either.
2058             break;
2059           }
2060         }
2061         Size >>= 1;
2062         C0080Val = APIntOps::lshr(C0080Val, Size);
2063         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2064       } while (Size >= 1);
2065       
2066       // FIXME: This shouldn't be necessary. When the backends can handle types
2067       // with funny bit widths then this switch statement should be removed. It
2068       // is just here to get the size of the "middle" type back up to something
2069       // that the back ends can handle.
2070       const Type *MiddleType = 0;
2071       switch (Size) {
2072         default: break;
2073         case 32: MiddleType = Type::Int32Ty; break;
2074         case 16: MiddleType = Type::Int16Ty; break;
2075         case  8: MiddleType = Type::Int8Ty; break;
2076       }
2077       if (MiddleType) {
2078         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2079         InsertNewInstBefore(NewTrunc, I);
2080         return new SExtInst(NewTrunc, I.getType(), I.getName());
2081       }
2082     }
2083   }
2084
2085   if (I.getType() == Type::Int1Ty)
2086     return BinaryOperator::CreateXor(LHS, RHS);
2087
2088   // X + X --> X << 1
2089   if (I.getType()->isInteger()) {
2090     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2091
2092     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2093       if (RHSI->getOpcode() == Instruction::Sub)
2094         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2095           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2096     }
2097     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2098       if (LHSI->getOpcode() == Instruction::Sub)
2099         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2100           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2101     }
2102   }
2103
2104   // -A + B  -->  B - A
2105   // -A + -B  -->  -(A + B)
2106   if (Value *LHSV = dyn_castNegVal(LHS)) {
2107     if (LHS->getType()->isIntOrIntVector()) {
2108       if (Value *RHSV = dyn_castNegVal(RHS)) {
2109         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2110         InsertNewInstBefore(NewAdd, I);
2111         return BinaryOperator::CreateNeg(NewAdd);
2112       }
2113     }
2114     
2115     return BinaryOperator::CreateSub(RHS, LHSV);
2116   }
2117
2118   // A + -B  -->  A - B
2119   if (!isa<Constant>(RHS))
2120     if (Value *V = dyn_castNegVal(RHS))
2121       return BinaryOperator::CreateSub(LHS, V);
2122
2123
2124   ConstantInt *C2;
2125   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2126     if (X == RHS)   // X*C + X --> X * (C+1)
2127       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2128
2129     // X*C1 + X*C2 --> X * (C1+C2)
2130     ConstantInt *C1;
2131     if (X == dyn_castFoldableMul(RHS, C1))
2132       return BinaryOperator::CreateMul(X, Add(C1, C2));
2133   }
2134
2135   // X + X*C --> X * (C+1)
2136   if (dyn_castFoldableMul(RHS, C2) == LHS)
2137     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2138
2139   // X + ~X --> -1   since   ~X = -X-1
2140   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2141     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2142   
2143
2144   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2145   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2146     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2147       return R;
2148   
2149   // A+B --> A|B iff A and B have no bits set in common.
2150   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2151     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2152     APInt LHSKnownOne(IT->getBitWidth(), 0);
2153     APInt LHSKnownZero(IT->getBitWidth(), 0);
2154     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2155     if (LHSKnownZero != 0) {
2156       APInt RHSKnownOne(IT->getBitWidth(), 0);
2157       APInt RHSKnownZero(IT->getBitWidth(), 0);
2158       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2159       
2160       // No bits in common -> bitwise or.
2161       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2162         return BinaryOperator::CreateOr(LHS, RHS);
2163     }
2164   }
2165
2166   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2167   if (I.getType()->isIntOrIntVector()) {
2168     Value *W, *X, *Y, *Z;
2169     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2170         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2171       if (W != Y) {
2172         if (W == Z) {
2173           std::swap(Y, Z);
2174         } else if (Y == X) {
2175           std::swap(W, X);
2176         } else if (X == Z) {
2177           std::swap(Y, Z);
2178           std::swap(W, X);
2179         }
2180       }
2181
2182       if (W == Y) {
2183         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2184                                                             LHS->getName()), I);
2185         return BinaryOperator::CreateMul(W, NewAdd);
2186       }
2187     }
2188   }
2189
2190   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2191     Value *X = 0;
2192     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2193       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2194
2195     // (X & FF00) + xx00  -> (X+xx00) & FF00
2196     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2197       Constant *Anded = And(CRHS, C2);
2198       if (Anded == CRHS) {
2199         // See if all bits from the first bit set in the Add RHS up are included
2200         // in the mask.  First, get the rightmost bit.
2201         const APInt& AddRHSV = CRHS->getValue();
2202
2203         // Form a mask of all bits from the lowest bit added through the top.
2204         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2205
2206         // See if the and mask includes all of these bits.
2207         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2208
2209         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2210           // Okay, the xform is safe.  Insert the new add pronto.
2211           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2212                                                             LHS->getName()), I);
2213           return BinaryOperator::CreateAnd(NewAdd, C2);
2214         }
2215       }
2216     }
2217
2218     // Try to fold constant add into select arguments.
2219     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2220       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2221         return R;
2222   }
2223
2224   // add (cast *A to intptrtype) B -> 
2225   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2226   {
2227     CastInst *CI = dyn_cast<CastInst>(LHS);
2228     Value *Other = RHS;
2229     if (!CI) {
2230       CI = dyn_cast<CastInst>(RHS);
2231       Other = LHS;
2232     }
2233     if (CI && CI->getType()->isSized() && 
2234         (CI->getType()->getPrimitiveSizeInBits() == 
2235          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2236         && isa<PointerType>(CI->getOperand(0)->getType())) {
2237       unsigned AS =
2238         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2239       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2240                                       PointerType::get(Type::Int8Ty, AS), I);
2241       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2242       return new PtrToIntInst(I2, CI->getType());
2243     }
2244   }
2245   
2246   // add (select X 0 (sub n A)) A  -->  select X A n
2247   {
2248     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2249     Value *A = RHS;
2250     if (!SI) {
2251       SI = dyn_cast<SelectInst>(RHS);
2252       A = LHS;
2253     }
2254     if (SI && SI->hasOneUse()) {
2255       Value *TV = SI->getTrueValue();
2256       Value *FV = SI->getFalseValue();
2257       Value *N;
2258
2259       // Can we fold the add into the argument of the select?
2260       // We check both true and false select arguments for a matching subtract.
2261       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2262         // Fold the add into the true select value.
2263         return SelectInst::Create(SI->getCondition(), N, A);
2264       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2265         // Fold the add into the false select value.
2266         return SelectInst::Create(SI->getCondition(), A, N);
2267     }
2268   }
2269   
2270   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2271   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2272     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2273       return ReplaceInstUsesWith(I, LHS);
2274
2275   // Check for (add (sext x), y), see if we can merge this into an
2276   // integer add followed by a sext.
2277   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2278     // (add (sext x), cst) --> (sext (add x, cst'))
2279     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2280       Constant *CI = 
2281         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2282       if (LHSConv->hasOneUse() &&
2283           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2284           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2285         // Insert the new, smaller add.
2286         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2287                                                         CI, "addconv");
2288         InsertNewInstBefore(NewAdd, I);
2289         return new SExtInst(NewAdd, I.getType());
2290       }
2291     }
2292     
2293     // (add (sext x), (sext y)) --> (sext (add int x, y))
2294     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2295       // Only do this if x/y have the same type, if at last one of them has a
2296       // single use (so we don't increase the number of sexts), and if the
2297       // integer add will not overflow.
2298       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2299           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2300           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2301                                    RHSConv->getOperand(0))) {
2302         // Insert the new integer add.
2303         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2304                                                         RHSConv->getOperand(0),
2305                                                         "addconv");
2306         InsertNewInstBefore(NewAdd, I);
2307         return new SExtInst(NewAdd, I.getType());
2308       }
2309     }
2310   }
2311   
2312   // Check for (add double (sitofp x), y), see if we can merge this into an
2313   // integer add followed by a promotion.
2314   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2315     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2316     // ... if the constant fits in the integer value.  This is useful for things
2317     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2318     // requires a constant pool load, and generally allows the add to be better
2319     // instcombined.
2320     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2321       Constant *CI = 
2322       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2323       if (LHSConv->hasOneUse() &&
2324           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2325           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2326         // Insert the new integer add.
2327         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2328                                                         CI, "addconv");
2329         InsertNewInstBefore(NewAdd, I);
2330         return new SIToFPInst(NewAdd, I.getType());
2331       }
2332     }
2333     
2334     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2335     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2336       // Only do this if x/y have the same type, if at last one of them has a
2337       // single use (so we don't increase the number of int->fp conversions),
2338       // and if the integer add will not overflow.
2339       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2340           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2341           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2342                                    RHSConv->getOperand(0))) {
2343         // Insert the new integer add.
2344         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2345                                                         RHSConv->getOperand(0),
2346                                                         "addconv");
2347         InsertNewInstBefore(NewAdd, I);
2348         return new SIToFPInst(NewAdd, I.getType());
2349       }
2350     }
2351   }
2352   
2353   return Changed ? &I : 0;
2354 }
2355
2356 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2357   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2358
2359   if (Op0 == Op1 &&                        // sub X, X  -> 0
2360       !I.getType()->isFPOrFPVector())
2361     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2362
2363   // If this is a 'B = x-(-A)', change to B = x+A...
2364   if (Value *V = dyn_castNegVal(Op1))
2365     return BinaryOperator::CreateAdd(Op0, V);
2366
2367   if (isa<UndefValue>(Op0))
2368     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2369   if (isa<UndefValue>(Op1))
2370     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2371
2372   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2373     // Replace (-1 - A) with (~A)...
2374     if (C->isAllOnesValue())
2375       return BinaryOperator::CreateNot(Op1);
2376
2377     // C - ~X == X + (1+C)
2378     Value *X = 0;
2379     if (match(Op1, m_Not(m_Value(X))))
2380       return BinaryOperator::CreateAdd(X, AddOne(C));
2381
2382     // -(X >>u 31) -> (X >>s 31)
2383     // -(X >>s 31) -> (X >>u 31)
2384     if (C->isZero()) {
2385       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2386         if (SI->getOpcode() == Instruction::LShr) {
2387           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2388             // Check to see if we are shifting out everything but the sign bit.
2389             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2390                 SI->getType()->getPrimitiveSizeInBits()-1) {
2391               // Ok, the transformation is safe.  Insert AShr.
2392               return BinaryOperator::Create(Instruction::AShr, 
2393                                           SI->getOperand(0), CU, SI->getName());
2394             }
2395           }
2396         }
2397         else if (SI->getOpcode() == Instruction::AShr) {
2398           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2399             // Check to see if we are shifting out everything but the sign bit.
2400             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2401                 SI->getType()->getPrimitiveSizeInBits()-1) {
2402               // Ok, the transformation is safe.  Insert LShr. 
2403               return BinaryOperator::CreateLShr(
2404                                           SI->getOperand(0), CU, SI->getName());
2405             }
2406           }
2407         }
2408       }
2409     }
2410
2411     // Try to fold constant sub into select arguments.
2412     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2413       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2414         return R;
2415
2416     if (isa<PHINode>(Op0))
2417       if (Instruction *NV = FoldOpIntoPhi(I))
2418         return NV;
2419   }
2420
2421   if (I.getType() == Type::Int1Ty)
2422     return BinaryOperator::CreateXor(Op0, Op1);
2423
2424   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2425     if (Op1I->getOpcode() == Instruction::Add &&
2426         !Op0->getType()->isFPOrFPVector()) {
2427       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2428         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2429       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2430         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2431       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2432         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2433           // C1-(X+C2) --> (C1-C2)-X
2434           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2435                                            Op1I->getOperand(0));
2436       }
2437     }
2438
2439     if (Op1I->hasOneUse()) {
2440       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2441       // is not used by anyone else...
2442       //
2443       if (Op1I->getOpcode() == Instruction::Sub &&
2444           !Op1I->getType()->isFPOrFPVector()) {
2445         // Swap the two operands of the subexpr...
2446         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2447         Op1I->setOperand(0, IIOp1);
2448         Op1I->setOperand(1, IIOp0);
2449
2450         // Create the new top level add instruction...
2451         return BinaryOperator::CreateAdd(Op0, Op1);
2452       }
2453
2454       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2455       //
2456       if (Op1I->getOpcode() == Instruction::And &&
2457           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2458         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2459
2460         Value *NewNot =
2461           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2462         return BinaryOperator::CreateAnd(Op0, NewNot);
2463       }
2464
2465       // 0 - (X sdiv C)  -> (X sdiv -C)
2466       if (Op1I->getOpcode() == Instruction::SDiv)
2467         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2468           if (CSI->isZero())
2469             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2470               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2471                                                ConstantExpr::getNeg(DivRHS));
2472
2473       // X - X*C --> X * (1-C)
2474       ConstantInt *C2 = 0;
2475       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2476         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2477         return BinaryOperator::CreateMul(Op0, CP1);
2478       }
2479
2480       // X - ((X / Y) * Y) --> X % Y
2481       if (Op1I->getOpcode() == Instruction::Mul)
2482         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2483           if (Op0 == I->getOperand(0) &&
2484               Op1I->getOperand(1) == I->getOperand(1)) {
2485             if (I->getOpcode() == Instruction::SDiv)
2486               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2487             if (I->getOpcode() == Instruction::UDiv)
2488               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2489           }
2490     }
2491   }
2492
2493   if (!Op0->getType()->isFPOrFPVector())
2494     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2495       if (Op0I->getOpcode() == Instruction::Add) {
2496         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2497           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2498         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2499           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2500       } else if (Op0I->getOpcode() == Instruction::Sub) {
2501         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2502           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2503       }
2504     }
2505
2506   ConstantInt *C1;
2507   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2508     if (X == Op1)  // X*C - X --> X * (C-1)
2509       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2510
2511     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2512     if (X == dyn_castFoldableMul(Op1, C2))
2513       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2514   }
2515   return 0;
2516 }
2517
2518 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2519 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2520 /// TrueIfSigned if the result of the comparison is true when the input value is
2521 /// signed.
2522 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2523                            bool &TrueIfSigned) {
2524   switch (pred) {
2525   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2526     TrueIfSigned = true;
2527     return RHS->isZero();
2528   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2529     TrueIfSigned = true;
2530     return RHS->isAllOnesValue();
2531   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2532     TrueIfSigned = false;
2533     return RHS->isAllOnesValue();
2534   case ICmpInst::ICMP_UGT:
2535     // True if LHS u> RHS and RHS == high-bit-mask - 1
2536     TrueIfSigned = true;
2537     return RHS->getValue() ==
2538       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2539   case ICmpInst::ICMP_UGE: 
2540     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2541     TrueIfSigned = true;
2542     return RHS->getValue().isSignBit();
2543   default:
2544     return false;
2545   }
2546 }
2547
2548 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2549   bool Changed = SimplifyCommutative(I);
2550   Value *Op0 = I.getOperand(0);
2551
2552   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2553     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2554
2555   // Simplify mul instructions with a constant RHS...
2556   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2557     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2558
2559       // ((X << C1)*C2) == (X * (C2 << C1))
2560       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2561         if (SI->getOpcode() == Instruction::Shl)
2562           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2563             return BinaryOperator::CreateMul(SI->getOperand(0),
2564                                              ConstantExpr::getShl(CI, ShOp));
2565
2566       if (CI->isZero())
2567         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2568       if (CI->equalsInt(1))                  // X * 1  == X
2569         return ReplaceInstUsesWith(I, Op0);
2570       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2571         return BinaryOperator::CreateNeg(Op0, I.getName());
2572
2573       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2574       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2575         return BinaryOperator::CreateShl(Op0,
2576                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2577       }
2578     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2579       if (Op1F->isNullValue())
2580         return ReplaceInstUsesWith(I, Op1);
2581
2582       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2583       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2584       if (Op1F->isExactlyValue(1.0))
2585         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2586     } else if (isa<VectorType>(Op1->getType())) {
2587       if (isa<ConstantAggregateZero>(Op1))
2588         return ReplaceInstUsesWith(I, Op1);
2589       
2590       // As above, vector X*splat(1.0) -> X in all defined cases.
2591       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2592         if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2593           if (F->isExactlyValue(1.0))
2594             return ReplaceInstUsesWith(I, Op0);
2595     }
2596     
2597     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2598       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2599           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2600         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2601         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2602                                                      Op1, "tmp");
2603         InsertNewInstBefore(Add, I);
2604         Value *C1C2 = ConstantExpr::getMul(Op1, 
2605                                            cast<Constant>(Op0I->getOperand(1)));
2606         return BinaryOperator::CreateAdd(Add, C1C2);
2607         
2608       }
2609
2610     // Try to fold constant mul into select arguments.
2611     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2612       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2613         return R;
2614
2615     if (isa<PHINode>(Op0))
2616       if (Instruction *NV = FoldOpIntoPhi(I))
2617         return NV;
2618   }
2619
2620   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2621     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2622       return BinaryOperator::CreateMul(Op0v, Op1v);
2623
2624   if (I.getType() == Type::Int1Ty)
2625     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2626
2627   // If one of the operands of the multiply is a cast from a boolean value, then
2628   // we know the bool is either zero or one, so this is a 'masking' multiply.
2629   // See if we can simplify things based on how the boolean was originally
2630   // formed.
2631   CastInst *BoolCast = 0;
2632   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2633     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2634       BoolCast = CI;
2635   if (!BoolCast)
2636     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2637       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2638         BoolCast = CI;
2639   if (BoolCast) {
2640     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2641       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2642       const Type *SCOpTy = SCIOp0->getType();
2643       bool TIS = false;
2644       
2645       // If the icmp is true iff the sign bit of X is set, then convert this
2646       // multiply into a shift/and combination.
2647       if (isa<ConstantInt>(SCIOp1) &&
2648           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2649           TIS) {
2650         // Shift the X value right to turn it into "all signbits".
2651         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2652                                           SCOpTy->getPrimitiveSizeInBits()-1);
2653         Value *V =
2654           InsertNewInstBefore(
2655             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2656                                             BoolCast->getOperand(0)->getName()+
2657                                             ".mask"), I);
2658
2659         // If the multiply type is not the same as the source type, sign extend
2660         // or truncate to the multiply type.
2661         if (I.getType() != V->getType()) {
2662           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2663           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2664           Instruction::CastOps opcode = 
2665             (SrcBits == DstBits ? Instruction::BitCast : 
2666              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2667           V = InsertCastBefore(opcode, V, I.getType(), I);
2668         }
2669
2670         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2671         return BinaryOperator::CreateAnd(V, OtherOp);
2672       }
2673     }
2674   }
2675
2676   return Changed ? &I : 0;
2677 }
2678
2679 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2680 /// instruction.
2681 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2682   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2683   
2684   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2685   int NonNullOperand = -1;
2686   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2687     if (ST->isNullValue())
2688       NonNullOperand = 2;
2689   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2690   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2691     if (ST->isNullValue())
2692       NonNullOperand = 1;
2693   
2694   if (NonNullOperand == -1)
2695     return false;
2696   
2697   Value *SelectCond = SI->getOperand(0);
2698   
2699   // Change the div/rem to use 'Y' instead of the select.
2700   I.setOperand(1, SI->getOperand(NonNullOperand));
2701   
2702   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2703   // problem.  However, the select, or the condition of the select may have
2704   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2705   // propagate the known value for the select into other uses of it, and
2706   // propagate a known value of the condition into its other users.
2707   
2708   // If the select and condition only have a single use, don't bother with this,
2709   // early exit.
2710   if (SI->use_empty() && SelectCond->hasOneUse())
2711     return true;
2712   
2713   // Scan the current block backward, looking for other uses of SI.
2714   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2715   
2716   while (BBI != BBFront) {
2717     --BBI;
2718     // If we found a call to a function, we can't assume it will return, so
2719     // information from below it cannot be propagated above it.
2720     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2721       break;
2722     
2723     // Replace uses of the select or its condition with the known values.
2724     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2725          I != E; ++I) {
2726       if (*I == SI) {
2727         *I = SI->getOperand(NonNullOperand);
2728         AddToWorkList(BBI);
2729       } else if (*I == SelectCond) {
2730         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2731                                    ConstantInt::getFalse();
2732         AddToWorkList(BBI);
2733       }
2734     }
2735     
2736     // If we past the instruction, quit looking for it.
2737     if (&*BBI == SI)
2738       SI = 0;
2739     if (&*BBI == SelectCond)
2740       SelectCond = 0;
2741     
2742     // If we ran out of things to eliminate, break out of the loop.
2743     if (SelectCond == 0 && SI == 0)
2744       break;
2745     
2746   }
2747   return true;
2748 }
2749
2750
2751 /// This function implements the transforms on div instructions that work
2752 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2753 /// used by the visitors to those instructions.
2754 /// @brief Transforms common to all three div instructions
2755 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2756   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2757
2758   // undef / X -> 0        for integer.
2759   // undef / X -> undef    for FP (the undef could be a snan).
2760   if (isa<UndefValue>(Op0)) {
2761     if (Op0->getType()->isFPOrFPVector())
2762       return ReplaceInstUsesWith(I, Op0);
2763     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2764   }
2765
2766   // X / undef -> undef
2767   if (isa<UndefValue>(Op1))
2768     return ReplaceInstUsesWith(I, Op1);
2769
2770   return 0;
2771 }
2772
2773 /// This function implements the transforms common to both integer division
2774 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2775 /// division instructions.
2776 /// @brief Common integer divide transforms
2777 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2778   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2779
2780   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2781   if (Op0 == Op1) {
2782     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2783       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2784       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2785       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2786     }
2787
2788     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2789     return ReplaceInstUsesWith(I, CI);
2790   }
2791   
2792   if (Instruction *Common = commonDivTransforms(I))
2793     return Common;
2794   
2795   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2796   // This does not apply for fdiv.
2797   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2798     return &I;
2799
2800   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2801     // div X, 1 == X
2802     if (RHS->equalsInt(1))
2803       return ReplaceInstUsesWith(I, Op0);
2804
2805     // (X / C1) / C2  -> X / (C1*C2)
2806     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2807       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2808         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2809           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2810             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2811           else 
2812             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2813                                           Multiply(RHS, LHSRHS));
2814         }
2815
2816     if (!RHS->isZero()) { // avoid X udiv 0
2817       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2818         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2819           return R;
2820       if (isa<PHINode>(Op0))
2821         if (Instruction *NV = FoldOpIntoPhi(I))
2822           return NV;
2823     }
2824   }
2825
2826   // 0 / X == 0, we don't need to preserve faults!
2827   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2828     if (LHS->equalsInt(0))
2829       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2830
2831   // It can't be division by zero, hence it must be division by one.
2832   if (I.getType() == Type::Int1Ty)
2833     return ReplaceInstUsesWith(I, Op0);
2834
2835   return 0;
2836 }
2837
2838 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2839   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2840
2841   // Handle the integer div common cases
2842   if (Instruction *Common = commonIDivTransforms(I))
2843     return Common;
2844
2845   // X udiv C^2 -> X >> C
2846   // Check to see if this is an unsigned division with an exact power of 2,
2847   // if so, convert to a right shift.
2848   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2849     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2850       return BinaryOperator::CreateLShr(Op0, 
2851                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2852   }
2853
2854   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2855   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2856     if (RHSI->getOpcode() == Instruction::Shl &&
2857         isa<ConstantInt>(RHSI->getOperand(0))) {
2858       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2859       if (C1.isPowerOf2()) {
2860         Value *N = RHSI->getOperand(1);
2861         const Type *NTy = N->getType();
2862         if (uint32_t C2 = C1.logBase2()) {
2863           Constant *C2V = ConstantInt::get(NTy, C2);
2864           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2865         }
2866         return BinaryOperator::CreateLShr(Op0, N);
2867       }
2868     }
2869   }
2870   
2871   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2872   // where C1&C2 are powers of two.
2873   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2874     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2875       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2876         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2877         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2878           // Compute the shift amounts
2879           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2880           // Construct the "on true" case of the select
2881           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2882           Instruction *TSI = BinaryOperator::CreateLShr(
2883                                                  Op0, TC, SI->getName()+".t");
2884           TSI = InsertNewInstBefore(TSI, I);
2885   
2886           // Construct the "on false" case of the select
2887           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2888           Instruction *FSI = BinaryOperator::CreateLShr(
2889                                                  Op0, FC, SI->getName()+".f");
2890           FSI = InsertNewInstBefore(FSI, I);
2891
2892           // construct the select instruction and return it.
2893           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2894         }
2895       }
2896   return 0;
2897 }
2898
2899 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2900   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2901
2902   // Handle the integer div common cases
2903   if (Instruction *Common = commonIDivTransforms(I))
2904     return Common;
2905
2906   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2907     // sdiv X, -1 == -X
2908     if (RHS->isAllOnesValue())
2909       return BinaryOperator::CreateNeg(Op0);
2910
2911     // -X/C -> X/-C
2912     if (Value *LHSNeg = dyn_castNegVal(Op0))
2913       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2914   }
2915
2916   // If the sign bits of both operands are zero (i.e. we can prove they are
2917   // unsigned inputs), turn this into a udiv.
2918   if (I.getType()->isInteger()) {
2919     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2920     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2921       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2922       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2923     }
2924   }      
2925   
2926   return 0;
2927 }
2928
2929 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2930   return commonDivTransforms(I);
2931 }
2932
2933 /// This function implements the transforms on rem instructions that work
2934 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2935 /// is used by the visitors to those instructions.
2936 /// @brief Transforms common to all three rem instructions
2937 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2939
2940   // 0 % X == 0 for integer, we don't need to preserve faults!
2941   if (Constant *LHS = dyn_cast<Constant>(Op0))
2942     if (LHS->isNullValue())
2943       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2944
2945   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2946     if (I.getType()->isFPOrFPVector())
2947       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2948     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2949   }
2950   if (isa<UndefValue>(Op1))
2951     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2952
2953   // Handle cases involving: rem X, (select Cond, Y, Z)
2954   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2955     return &I;
2956
2957   return 0;
2958 }
2959
2960 /// This function implements the transforms common to both integer remainder
2961 /// instructions (urem and srem). It is called by the visitors to those integer
2962 /// remainder instructions.
2963 /// @brief Common integer remainder transforms
2964 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2965   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2966
2967   if (Instruction *common = commonRemTransforms(I))
2968     return common;
2969
2970   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2971     // X % 0 == undef, we don't need to preserve faults!
2972     if (RHS->equalsInt(0))
2973       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2974     
2975     if (RHS->equalsInt(1))  // X % 1 == 0
2976       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2977
2978     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2979       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2980         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2981           return R;
2982       } else if (isa<PHINode>(Op0I)) {
2983         if (Instruction *NV = FoldOpIntoPhi(I))
2984           return NV;
2985       }
2986
2987       // See if we can fold away this rem instruction.
2988       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2989       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2990       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2991                                KnownZero, KnownOne))
2992         return &I;
2993     }
2994   }
2995
2996   return 0;
2997 }
2998
2999 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3000   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3001
3002   if (Instruction *common = commonIRemTransforms(I))
3003     return common;
3004   
3005   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3006     // X urem C^2 -> X and C
3007     // Check to see if this is an unsigned remainder with an exact power of 2,
3008     // if so, convert to a bitwise and.
3009     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3010       if (C->getValue().isPowerOf2())
3011         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3012   }
3013
3014   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3015     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3016     if (RHSI->getOpcode() == Instruction::Shl &&
3017         isa<ConstantInt>(RHSI->getOperand(0))) {
3018       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3019         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3020         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3021                                                                    "tmp"), I);
3022         return BinaryOperator::CreateAnd(Op0, Add);
3023       }
3024     }
3025   }
3026
3027   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3028   // where C1&C2 are powers of two.
3029   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3030     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3031       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3032         // STO == 0 and SFO == 0 handled above.
3033         if ((STO->getValue().isPowerOf2()) && 
3034             (SFO->getValue().isPowerOf2())) {
3035           Value *TrueAnd = InsertNewInstBefore(
3036             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3037           Value *FalseAnd = InsertNewInstBefore(
3038             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3039           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3040         }
3041       }
3042   }
3043   
3044   return 0;
3045 }
3046
3047 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3048   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3049
3050   // Handle the integer rem common cases
3051   if (Instruction *common = commonIRemTransforms(I))
3052     return common;
3053   
3054   if (Value *RHSNeg = dyn_castNegVal(Op1))
3055     if (!isa<Constant>(RHSNeg) ||
3056         (isa<ConstantInt>(RHSNeg) &&
3057          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3058       // X % -Y -> X % Y
3059       AddUsesToWorkList(I);
3060       I.setOperand(1, RHSNeg);
3061       return &I;
3062     }
3063
3064   // If the sign bits of both operands are zero (i.e. we can prove they are
3065   // unsigned inputs), turn this into a urem.
3066   if (I.getType()->isInteger()) {
3067     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3068     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3069       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3070       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3071     }
3072   }
3073
3074   return 0;
3075 }
3076
3077 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3078   return commonRemTransforms(I);
3079 }
3080
3081 // isOneBitSet - Return true if there is exactly one bit set in the specified
3082 // constant.
3083 static bool isOneBitSet(const ConstantInt *CI) {
3084   return CI->getValue().isPowerOf2();
3085 }
3086
3087 // isHighOnes - Return true if the constant is of the form 1+0+.
3088 // This is the same as lowones(~X).
3089 static bool isHighOnes(const ConstantInt *CI) {
3090   return (~CI->getValue() + 1).isPowerOf2();
3091 }
3092
3093 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3094 /// are carefully arranged to allow folding of expressions such as:
3095 ///
3096 ///      (A < B) | (A > B) --> (A != B)
3097 ///
3098 /// Note that this is only valid if the first and second predicates have the
3099 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3100 ///
3101 /// Three bits are used to represent the condition, as follows:
3102 ///   0  A > B
3103 ///   1  A == B
3104 ///   2  A < B
3105 ///
3106 /// <=>  Value  Definition
3107 /// 000     0   Always false
3108 /// 001     1   A >  B
3109 /// 010     2   A == B
3110 /// 011     3   A >= B
3111 /// 100     4   A <  B
3112 /// 101     5   A != B
3113 /// 110     6   A <= B
3114 /// 111     7   Always true
3115 ///  
3116 static unsigned getICmpCode(const ICmpInst *ICI) {
3117   switch (ICI->getPredicate()) {
3118     // False -> 0
3119   case ICmpInst::ICMP_UGT: return 1;  // 001
3120   case ICmpInst::ICMP_SGT: return 1;  // 001
3121   case ICmpInst::ICMP_EQ:  return 2;  // 010
3122   case ICmpInst::ICMP_UGE: return 3;  // 011
3123   case ICmpInst::ICMP_SGE: return 3;  // 011
3124   case ICmpInst::ICMP_ULT: return 4;  // 100
3125   case ICmpInst::ICMP_SLT: return 4;  // 100
3126   case ICmpInst::ICMP_NE:  return 5;  // 101
3127   case ICmpInst::ICMP_ULE: return 6;  // 110
3128   case ICmpInst::ICMP_SLE: return 6;  // 110
3129     // True -> 7
3130   default:
3131     assert(0 && "Invalid ICmp predicate!");
3132     return 0;
3133   }
3134 }
3135
3136 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3137 /// predicate into a three bit mask. It also returns whether it is an ordered
3138 /// predicate by reference.
3139 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3140   isOrdered = false;
3141   switch (CC) {
3142   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3143   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3144   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3145   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3146   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3147   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3148   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3149   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3150   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3151   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3152   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3153   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3154   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3155   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3156     // True -> 7
3157   default:
3158     // Not expecting FCMP_FALSE and FCMP_TRUE;
3159     assert(0 && "Unexpected FCmp predicate!");
3160     return 0;
3161   }
3162 }
3163
3164 /// getICmpValue - This is the complement of getICmpCode, which turns an
3165 /// opcode and two operands into either a constant true or false, or a brand 
3166 /// new ICmp instruction. The sign is passed in to determine which kind
3167 /// of predicate to use in the new icmp instruction.
3168 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3169   switch (code) {
3170   default: assert(0 && "Illegal ICmp code!");
3171   case  0: return ConstantInt::getFalse();
3172   case  1: 
3173     if (sign)
3174       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3175     else
3176       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3177   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3178   case  3: 
3179     if (sign)
3180       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3181     else
3182       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3183   case  4: 
3184     if (sign)
3185       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3186     else
3187       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3188   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3189   case  6: 
3190     if (sign)
3191       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3192     else
3193       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3194   case  7: return ConstantInt::getTrue();
3195   }
3196 }
3197
3198 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3199 /// opcode and two operands into either a FCmp instruction. isordered is passed
3200 /// in to determine which kind of predicate to use in the new fcmp instruction.
3201 static Value *getFCmpValue(bool isordered, unsigned code,
3202                            Value *LHS, Value *RHS) {
3203   switch (code) {
3204   default: assert(0 && "Illegal FCmp code!");
3205   case  0:
3206     if (isordered)
3207       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3208     else
3209       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3210   case  1: 
3211     if (isordered)
3212       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3213     else
3214       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3215   case  2: 
3216     if (isordered)
3217       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3218     else
3219       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3220   case  3: 
3221     if (isordered)
3222       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3223     else
3224       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3225   case  4: 
3226     if (isordered)
3227       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3228     else
3229       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3230   case  5: 
3231     if (isordered)
3232       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3233     else
3234       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3235   case  6: 
3236     if (isordered)
3237       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3238     else
3239       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3240   case  7: return ConstantInt::getTrue();
3241   }
3242 }
3243
3244 /// PredicatesFoldable - Return true if both predicates match sign or if at
3245 /// least one of them is an equality comparison (which is signless).
3246 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3247   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3248          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3249          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3250 }
3251
3252 namespace { 
3253 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3254 struct FoldICmpLogical {
3255   InstCombiner &IC;
3256   Value *LHS, *RHS;
3257   ICmpInst::Predicate pred;
3258   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3259     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3260       pred(ICI->getPredicate()) {}
3261   bool shouldApply(Value *V) const {
3262     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3263       if (PredicatesFoldable(pred, ICI->getPredicate()))
3264         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3265                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3266     return false;
3267   }
3268   Instruction *apply(Instruction &Log) const {
3269     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3270     if (ICI->getOperand(0) != LHS) {
3271       assert(ICI->getOperand(1) == LHS);
3272       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3273     }
3274
3275     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3276     unsigned LHSCode = getICmpCode(ICI);
3277     unsigned RHSCode = getICmpCode(RHSICI);
3278     unsigned Code;
3279     switch (Log.getOpcode()) {
3280     case Instruction::And: Code = LHSCode & RHSCode; break;
3281     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3282     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3283     default: assert(0 && "Illegal logical opcode!"); return 0;
3284     }
3285
3286     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3287                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3288       
3289     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3290     if (Instruction *I = dyn_cast<Instruction>(RV))
3291       return I;
3292     // Otherwise, it's a constant boolean value...
3293     return IC.ReplaceInstUsesWith(Log, RV);
3294   }
3295 };
3296 } // end anonymous namespace
3297
3298 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3299 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3300 // guaranteed to be a binary operator.
3301 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3302                                     ConstantInt *OpRHS,
3303                                     ConstantInt *AndRHS,
3304                                     BinaryOperator &TheAnd) {
3305   Value *X = Op->getOperand(0);
3306   Constant *Together = 0;
3307   if (!Op->isShift())
3308     Together = And(AndRHS, OpRHS);
3309
3310   switch (Op->getOpcode()) {
3311   case Instruction::Xor:
3312     if (Op->hasOneUse()) {
3313       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3314       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3315       InsertNewInstBefore(And, TheAnd);
3316       And->takeName(Op);
3317       return BinaryOperator::CreateXor(And, Together);
3318     }
3319     break;
3320   case Instruction::Or:
3321     if (Together == AndRHS) // (X | C) & C --> C
3322       return ReplaceInstUsesWith(TheAnd, AndRHS);
3323
3324     if (Op->hasOneUse() && Together != OpRHS) {
3325       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3326       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3327       InsertNewInstBefore(Or, TheAnd);
3328       Or->takeName(Op);
3329       return BinaryOperator::CreateAnd(Or, AndRHS);
3330     }
3331     break;
3332   case Instruction::Add:
3333     if (Op->hasOneUse()) {
3334       // Adding a one to a single bit bit-field should be turned into an XOR
3335       // of the bit.  First thing to check is to see if this AND is with a
3336       // single bit constant.
3337       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3338
3339       // If there is only one bit set...
3340       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3341         // Ok, at this point, we know that we are masking the result of the
3342         // ADD down to exactly one bit.  If the constant we are adding has
3343         // no bits set below this bit, then we can eliminate the ADD.
3344         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3345
3346         // Check to see if any bits below the one bit set in AndRHSV are set.
3347         if ((AddRHS & (AndRHSV-1)) == 0) {
3348           // If not, the only thing that can effect the output of the AND is
3349           // the bit specified by AndRHSV.  If that bit is set, the effect of
3350           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3351           // no effect.
3352           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3353             TheAnd.setOperand(0, X);
3354             return &TheAnd;
3355           } else {
3356             // Pull the XOR out of the AND.
3357             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3358             InsertNewInstBefore(NewAnd, TheAnd);
3359             NewAnd->takeName(Op);
3360             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3361           }
3362         }
3363       }
3364     }
3365     break;
3366
3367   case Instruction::Shl: {
3368     // We know that the AND will not produce any of the bits shifted in, so if
3369     // the anded constant includes them, clear them now!
3370     //
3371     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3372     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3373     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3374     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3375
3376     if (CI->getValue() == ShlMask) { 
3377     // Masking out bits that the shift already masks
3378       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3379     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3380       TheAnd.setOperand(1, CI);
3381       return &TheAnd;
3382     }
3383     break;
3384   }
3385   case Instruction::LShr:
3386   {
3387     // We know that the AND will not produce any of the bits shifted in, so if
3388     // the anded constant includes them, clear them now!  This only applies to
3389     // unsigned shifts, because a signed shr may bring in set bits!
3390     //
3391     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3392     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3393     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3394     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3395
3396     if (CI->getValue() == ShrMask) {   
3397     // Masking out bits that the shift already masks.
3398       return ReplaceInstUsesWith(TheAnd, Op);
3399     } else if (CI != AndRHS) {
3400       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3401       return &TheAnd;
3402     }
3403     break;
3404   }
3405   case Instruction::AShr:
3406     // Signed shr.
3407     // See if this is shifting in some sign extension, then masking it out
3408     // with an and.
3409     if (Op->hasOneUse()) {
3410       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3411       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3412       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3413       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3414       if (C == AndRHS) {          // Masking out bits shifted in.
3415         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3416         // Make the argument unsigned.
3417         Value *ShVal = Op->getOperand(0);
3418         ShVal = InsertNewInstBefore(
3419             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3420                                    Op->getName()), TheAnd);
3421         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3422       }
3423     }
3424     break;
3425   }
3426   return 0;
3427 }
3428
3429
3430 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3431 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3432 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3433 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3434 /// insert new instructions.
3435 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3436                                            bool isSigned, bool Inside, 
3437                                            Instruction &IB) {
3438   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3439             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3440          "Lo is not <= Hi in range emission code!");
3441     
3442   if (Inside) {
3443     if (Lo == Hi)  // Trivially false.
3444       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3445
3446     // V >= Min && V < Hi --> V < Hi
3447     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3448       ICmpInst::Predicate pred = (isSigned ? 
3449         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3450       return new ICmpInst(pred, V, Hi);
3451     }
3452
3453     // Emit V-Lo <u Hi-Lo
3454     Constant *NegLo = ConstantExpr::getNeg(Lo);
3455     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3456     InsertNewInstBefore(Add, IB);
3457     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3458     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3459   }
3460
3461   if (Lo == Hi)  // Trivially true.
3462     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3463
3464   // V < Min || V >= Hi -> V > Hi-1
3465   Hi = SubOne(cast<ConstantInt>(Hi));
3466   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3467     ICmpInst::Predicate pred = (isSigned ? 
3468         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3469     return new ICmpInst(pred, V, Hi);
3470   }
3471
3472   // Emit V-Lo >u Hi-1-Lo
3473   // Note that Hi has already had one subtracted from it, above.
3474   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3475   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3476   InsertNewInstBefore(Add, IB);
3477   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3478   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3479 }
3480
3481 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3482 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3483 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3484 // not, since all 1s are not contiguous.
3485 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3486   const APInt& V = Val->getValue();
3487   uint32_t BitWidth = Val->getType()->getBitWidth();
3488   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3489
3490   // look for the first zero bit after the run of ones
3491   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3492   // look for the first non-zero bit
3493   ME = V.getActiveBits(); 
3494   return true;
3495 }
3496
3497 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3498 /// where isSub determines whether the operator is a sub.  If we can fold one of
3499 /// the following xforms:
3500 /// 
3501 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3502 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3503 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3504 ///
3505 /// return (A +/- B).
3506 ///
3507 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3508                                         ConstantInt *Mask, bool isSub,
3509                                         Instruction &I) {
3510   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3511   if (!LHSI || LHSI->getNumOperands() != 2 ||
3512       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3513
3514   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3515
3516   switch (LHSI->getOpcode()) {
3517   default: return 0;
3518   case Instruction::And:
3519     if (And(N, Mask) == Mask) {
3520       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3521       if ((Mask->getValue().countLeadingZeros() + 
3522            Mask->getValue().countPopulation()) == 
3523           Mask->getValue().getBitWidth())
3524         break;
3525
3526       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3527       // part, we don't need any explicit masks to take them out of A.  If that
3528       // is all N is, ignore it.
3529       uint32_t MB = 0, ME = 0;
3530       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3531         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3532         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3533         if (MaskedValueIsZero(RHS, Mask))
3534           break;
3535       }
3536     }
3537     return 0;
3538   case Instruction::Or:
3539   case Instruction::Xor:
3540     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3541     if ((Mask->getValue().countLeadingZeros() + 
3542          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3543         && And(N, Mask)->isZero())
3544       break;
3545     return 0;
3546   }
3547   
3548   Instruction *New;
3549   if (isSub)
3550     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3551   else
3552     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3553   return InsertNewInstBefore(New, I);
3554 }
3555
3556 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3557 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3558                                           ICmpInst *LHS, ICmpInst *RHS) {
3559   Value *Val, *Val2;
3560   ConstantInt *LHSCst, *RHSCst;
3561   ICmpInst::Predicate LHSCC, RHSCC;
3562   
3563   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3564   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3565       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3566     return 0;
3567   
3568   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3569   // where C is a power of 2
3570   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3571       LHSCst->getValue().isPowerOf2()) {
3572     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3573     InsertNewInstBefore(NewOr, I);
3574     return new ICmpInst(LHSCC, NewOr, LHSCst);
3575   }
3576   
3577   // From here on, we only handle:
3578   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3579   if (Val != Val2) return 0;
3580   
3581   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3582   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3583       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3584       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3585       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3586     return 0;
3587   
3588   // We can't fold (ugt x, C) & (sgt x, C2).
3589   if (!PredicatesFoldable(LHSCC, RHSCC))
3590     return 0;
3591     
3592   // Ensure that the larger constant is on the RHS.
3593   ICmpInst::Predicate GT;
3594   if (ICmpInst::isSignedPredicate(LHSCC) ||
3595       (ICmpInst::isEquality(LHSCC) && 
3596        ICmpInst::isSignedPredicate(RHSCC)))
3597     GT = ICmpInst::ICMP_SGT;
3598   else
3599     GT = ICmpInst::ICMP_UGT;
3600   
3601   Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3602   if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3603     std::swap(LHS, RHS);
3604     std::swap(LHSCst, RHSCst);
3605     std::swap(LHSCC, RHSCC);
3606   }
3607
3608   // At this point, we know we have have two icmp instructions
3609   // comparing a value against two constants and and'ing the result
3610   // together.  Because of the above check, we know that we only have
3611   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3612   // (from the FoldICmpLogical check above), that the two constants 
3613   // are not equal and that the larger constant is on the RHS
3614   assert(LHSCst != RHSCst && "Compares not folded above?");
3615
3616   switch (LHSCC) {
3617   default: assert(0 && "Unknown integer condition code!");
3618   case ICmpInst::ICMP_EQ:
3619     switch (RHSCC) {
3620     default: assert(0 && "Unknown integer condition code!");
3621     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3622     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3623     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3624       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3625     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3626     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3627     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3628       return ReplaceInstUsesWith(I, LHS);
3629     }
3630   case ICmpInst::ICMP_NE:
3631     switch (RHSCC) {
3632     default: assert(0 && "Unknown integer condition code!");
3633     case ICmpInst::ICMP_ULT:
3634       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3635         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3636       break;                        // (X != 13 & X u< 15) -> no change
3637     case ICmpInst::ICMP_SLT:
3638       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3639         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3640       break;                        // (X != 13 & X s< 15) -> no change
3641     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3642     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3643     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3644       return ReplaceInstUsesWith(I, RHS);
3645     case ICmpInst::ICMP_NE:
3646       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3647         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3648         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3649                                                      Val->getName()+".off");
3650         InsertNewInstBefore(Add, I);
3651         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3652                             ConstantInt::get(Add->getType(), 1));
3653       }
3654       break;                        // (X != 13 & X != 15) -> no change
3655     }
3656     break;
3657   case ICmpInst::ICMP_ULT:
3658     switch (RHSCC) {
3659     default: assert(0 && "Unknown integer condition code!");
3660     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3661     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3662       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3663     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3664       break;
3665     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3666     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3667       return ReplaceInstUsesWith(I, LHS);
3668     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3669       break;
3670     }
3671     break;
3672   case ICmpInst::ICMP_SLT:
3673     switch (RHSCC) {
3674     default: assert(0 && "Unknown integer condition code!");
3675     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3676     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3677       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3678     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3679       break;
3680     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3681     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3682       return ReplaceInstUsesWith(I, LHS);
3683     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3684       break;
3685     }
3686     break;
3687   case ICmpInst::ICMP_UGT:
3688     switch (RHSCC) {
3689     default: assert(0 && "Unknown integer condition code!");
3690     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3691     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3692       return ReplaceInstUsesWith(I, RHS);
3693     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3694       break;
3695     case ICmpInst::ICMP_NE:
3696       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3697         return new ICmpInst(LHSCC, Val, RHSCst);
3698       break;                        // (X u> 13 & X != 15) -> no change
3699     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3700       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3701     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3702       break;
3703     }
3704     break;
3705   case ICmpInst::ICMP_SGT:
3706     switch (RHSCC) {
3707     default: assert(0 && "Unknown integer condition code!");
3708     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3709     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3710       return ReplaceInstUsesWith(I, RHS);
3711     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3712       break;
3713     case ICmpInst::ICMP_NE:
3714       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3715         return new ICmpInst(LHSCC, Val, RHSCst);
3716       break;                        // (X s> 13 & X != 15) -> no change
3717     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3718       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3719     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3720       break;
3721     }
3722     break;
3723   }
3724
3725   
3726  
3727   return 0;
3728 }
3729
3730
3731 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3732   bool Changed = SimplifyCommutative(I);
3733   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3734
3735   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3736     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3737
3738   // and X, X = X
3739   if (Op0 == Op1)
3740     return ReplaceInstUsesWith(I, Op1);
3741
3742   // See if we can simplify any instructions used by the instruction whose sole 
3743   // purpose is to compute bits we don't care about.
3744   if (!isa<VectorType>(I.getType())) {
3745     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3746     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3747     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3748                              KnownZero, KnownOne))
3749       return &I;
3750   } else {
3751     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3752       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3753         return ReplaceInstUsesWith(I, I.getOperand(0));
3754     } else if (isa<ConstantAggregateZero>(Op1)) {
3755       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3756     }
3757   }
3758   
3759   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3760     const APInt& AndRHSMask = AndRHS->getValue();
3761     APInt NotAndRHS(~AndRHSMask);
3762
3763     // Optimize a variety of ((val OP C1) & C2) combinations...
3764     if (isa<BinaryOperator>(Op0)) {
3765       Instruction *Op0I = cast<Instruction>(Op0);
3766       Value *Op0LHS = Op0I->getOperand(0);
3767       Value *Op0RHS = Op0I->getOperand(1);
3768       switch (Op0I->getOpcode()) {
3769       case Instruction::Xor:
3770       case Instruction::Or:
3771         // If the mask is only needed on one incoming arm, push it up.
3772         if (Op0I->hasOneUse()) {
3773           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3774             // Not masking anything out for the LHS, move to RHS.
3775             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3776                                                    Op0RHS->getName()+".masked");
3777             InsertNewInstBefore(NewRHS, I);
3778             return BinaryOperator::Create(
3779                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3780           }
3781           if (!isa<Constant>(Op0RHS) &&
3782               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3783             // Not masking anything out for the RHS, move to LHS.
3784             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3785                                                    Op0LHS->getName()+".masked");
3786             InsertNewInstBefore(NewLHS, I);
3787             return BinaryOperator::Create(
3788                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3789           }
3790         }
3791
3792         break;
3793       case Instruction::Add:
3794         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3795         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3796         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3797         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3798           return BinaryOperator::CreateAnd(V, AndRHS);
3799         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3800           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3801         break;
3802
3803       case Instruction::Sub:
3804         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3805         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3806         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3807         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3808           return BinaryOperator::CreateAnd(V, AndRHS);
3809
3810         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3811         // has 1's for all bits that the subtraction with A might affect.
3812         if (Op0I->hasOneUse()) {
3813           uint32_t BitWidth = AndRHSMask.getBitWidth();
3814           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3815           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3816
3817           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3818           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3819               MaskedValueIsZero(Op0LHS, Mask)) {
3820             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3821             InsertNewInstBefore(NewNeg, I);
3822             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3823           }
3824         }
3825         break;
3826
3827       case Instruction::Shl:
3828       case Instruction::LShr:
3829         // (1 << x) & 1 --> zext(x == 0)
3830         // (1 >> x) & 1 --> zext(x == 0)
3831         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3832           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3833                                            Constant::getNullValue(I.getType()));
3834           InsertNewInstBefore(NewICmp, I);
3835           return new ZExtInst(NewICmp, I.getType());
3836         }
3837         break;
3838       }
3839
3840       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3841         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3842           return Res;
3843     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3844       // If this is an integer truncation or change from signed-to-unsigned, and
3845       // if the source is an and/or with immediate, transform it.  This
3846       // frequently occurs for bitfield accesses.
3847       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3848         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3849             CastOp->getNumOperands() == 2)
3850           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3851             if (CastOp->getOpcode() == Instruction::And) {
3852               // Change: and (cast (and X, C1) to T), C2
3853               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3854               // This will fold the two constants together, which may allow 
3855               // other simplifications.
3856               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3857                 CastOp->getOperand(0), I.getType(), 
3858                 CastOp->getName()+".shrunk");
3859               NewCast = InsertNewInstBefore(NewCast, I);
3860               // trunc_or_bitcast(C1)&C2
3861               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3862               C3 = ConstantExpr::getAnd(C3, AndRHS);
3863               return BinaryOperator::CreateAnd(NewCast, C3);
3864             } else if (CastOp->getOpcode() == Instruction::Or) {
3865               // Change: and (cast (or X, C1) to T), C2
3866               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3867               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3868               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3869                 return ReplaceInstUsesWith(I, AndRHS);
3870             }
3871           }
3872       }
3873     }
3874
3875     // Try to fold constant and into select arguments.
3876     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3877       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3878         return R;
3879     if (isa<PHINode>(Op0))
3880       if (Instruction *NV = FoldOpIntoPhi(I))
3881         return NV;
3882   }
3883
3884   Value *Op0NotVal = dyn_castNotVal(Op0);
3885   Value *Op1NotVal = dyn_castNotVal(Op1);
3886
3887   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3888     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3889
3890   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3891   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3892     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3893                                                I.getName()+".demorgan");
3894     InsertNewInstBefore(Or, I);
3895     return BinaryOperator::CreateNot(Or);
3896   }
3897   
3898   {
3899     Value *A = 0, *B = 0, *C = 0, *D = 0;
3900     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3901       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3902         return ReplaceInstUsesWith(I, Op1);
3903     
3904       // (A|B) & ~(A&B) -> A^B
3905       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3906         if ((A == C && B == D) || (A == D && B == C))
3907           return BinaryOperator::CreateXor(A, B);
3908       }
3909     }
3910     
3911     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3912       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3913         return ReplaceInstUsesWith(I, Op0);
3914
3915       // ~(A&B) & (A|B) -> A^B
3916       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3917         if ((A == C && B == D) || (A == D && B == C))
3918           return BinaryOperator::CreateXor(A, B);
3919       }
3920     }
3921     
3922     if (Op0->hasOneUse() &&
3923         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3924       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3925         I.swapOperands();     // Simplify below
3926         std::swap(Op0, Op1);
3927       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3928         cast<BinaryOperator>(Op0)->swapOperands();
3929         I.swapOperands();     // Simplify below
3930         std::swap(Op0, Op1);
3931       }
3932     }
3933     if (Op1->hasOneUse() &&
3934         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3935       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3936         cast<BinaryOperator>(Op1)->swapOperands();
3937         std::swap(A, B);
3938       }
3939       if (A == Op0) {                                // A&(A^B) -> A & ~B
3940         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3941         InsertNewInstBefore(NotB, I);
3942         return BinaryOperator::CreateAnd(A, NotB);
3943       }
3944     }
3945   }
3946   
3947   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3948     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3949     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3950       return R;
3951
3952     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3953       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3954         return Res;
3955   }
3956
3957   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3958   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3959     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3960       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3961         const Type *SrcTy = Op0C->getOperand(0)->getType();
3962         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3963             // Only do this if the casts both really cause code to be generated.
3964             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3965                               I.getType(), TD) &&
3966             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3967                               I.getType(), TD)) {
3968           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3969                                                          Op1C->getOperand(0),
3970                                                          I.getName());
3971           InsertNewInstBefore(NewOp, I);
3972           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3973         }
3974       }
3975     
3976   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3977   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3978     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3979       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3980           SI0->getOperand(1) == SI1->getOperand(1) &&
3981           (SI0->hasOneUse() || SI1->hasOneUse())) {
3982         Instruction *NewOp =
3983           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3984                                                         SI1->getOperand(0),
3985                                                         SI0->getName()), I);
3986         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3987                                       SI1->getOperand(1));
3988       }
3989   }
3990
3991   // If and'ing two fcmp, try combine them into one.
3992   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3993     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3994       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3995           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3996         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3997         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3998           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3999             // If either of the constants are nans, then the whole thing returns
4000             // false.
4001             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4002               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4003             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4004                                 RHS->getOperand(0));
4005           }
4006       } else {
4007         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4008         FCmpInst::Predicate Op0CC, Op1CC;
4009         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4010             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4011           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4012             // Swap RHS operands to match LHS.
4013             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4014             std::swap(Op1LHS, Op1RHS);
4015           }
4016           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4017             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4018             if (Op0CC == Op1CC)
4019               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4020             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4021                      Op1CC == FCmpInst::FCMP_FALSE)
4022               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4023             else if (Op0CC == FCmpInst::FCMP_TRUE)
4024               return ReplaceInstUsesWith(I, Op1);
4025             else if (Op1CC == FCmpInst::FCMP_TRUE)
4026               return ReplaceInstUsesWith(I, Op0);
4027             bool Op0Ordered;
4028             bool Op1Ordered;
4029             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4030             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4031             if (Op1Pred == 0) {
4032               std::swap(Op0, Op1);
4033               std::swap(Op0Pred, Op1Pred);
4034               std::swap(Op0Ordered, Op1Ordered);
4035             }
4036             if (Op0Pred == 0) {
4037               // uno && ueq -> uno && (uno || eq) -> ueq
4038               // ord && olt -> ord && (ord && lt) -> olt
4039               if (Op0Ordered == Op1Ordered)
4040                 return ReplaceInstUsesWith(I, Op1);
4041               // uno && oeq -> uno && (ord && eq) -> false
4042               // uno && ord -> false
4043               if (!Op0Ordered)
4044                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4045               // ord && ueq -> ord && (uno || eq) -> oeq
4046               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4047                                                     Op0LHS, Op0RHS));
4048             }
4049           }
4050         }
4051       }
4052     }
4053   }
4054
4055   return Changed ? &I : 0;
4056 }
4057
4058 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4059 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4060 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4061 /// the expression came from the corresponding "byte swapped" byte in some other
4062 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4063 /// we know that the expression deposits the low byte of %X into the high byte
4064 /// of the bswap result and that all other bytes are zero.  This expression is
4065 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4066 /// match.
4067 ///
4068 /// This function returns true if the match was unsuccessful and false if so.
4069 /// On entry to the function the "OverallLeftShift" is a signed integer value
4070 /// indicating the number of bytes that the subexpression is later shifted.  For
4071 /// example, if the expression is later right shifted by 16 bits, the
4072 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4073 /// byte of ByteValues is actually being set.
4074 ///
4075 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4076 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4077 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4078 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4079 /// always in the local (OverallLeftShift) coordinate space.
4080 ///
4081 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4082                               SmallVector<Value*, 8> &ByteValues) {
4083   if (Instruction *I = dyn_cast<Instruction>(V)) {
4084     // If this is an or instruction, it may be an inner node of the bswap.
4085     if (I->getOpcode() == Instruction::Or) {
4086       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4087                                ByteValues) ||
4088              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4089                                ByteValues);
4090     }
4091   
4092     // If this is a logical shift by a constant multiple of 8, recurse with
4093     // OverallLeftShift and ByteMask adjusted.
4094     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4095       unsigned ShAmt = 
4096         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4097       // Ensure the shift amount is defined and of a byte value.
4098       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4099         return true;
4100
4101       unsigned ByteShift = ShAmt >> 3;
4102       if (I->getOpcode() == Instruction::Shl) {
4103         // X << 2 -> collect(X, +2)
4104         OverallLeftShift += ByteShift;
4105         ByteMask >>= ByteShift;
4106       } else {
4107         // X >>u 2 -> collect(X, -2)
4108         OverallLeftShift -= ByteShift;
4109         ByteMask <<= ByteShift;
4110         ByteMask &= (~0U >> (32-ByteValues.size()));
4111       }
4112
4113       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4114       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4115
4116       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4117                                ByteValues);
4118     }
4119
4120     // If this is a logical 'and' with a mask that clears bytes, clear the
4121     // corresponding bytes in ByteMask.
4122     if (I->getOpcode() == Instruction::And &&
4123         isa<ConstantInt>(I->getOperand(1))) {
4124       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4125       unsigned NumBytes = ByteValues.size();
4126       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4127       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4128       
4129       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4130         // If this byte is masked out by a later operation, we don't care what
4131         // the and mask is.
4132         if ((ByteMask & (1 << i)) == 0)
4133           continue;
4134         
4135         // If the AndMask is all zeros for this byte, clear the bit.
4136         APInt MaskB = AndMask & Byte;
4137         if (MaskB == 0) {
4138           ByteMask &= ~(1U << i);
4139           continue;
4140         }
4141         
4142         // If the AndMask is not all ones for this byte, it's not a bytezap.
4143         if (MaskB != Byte)
4144           return true;
4145
4146         // Otherwise, this byte is kept.
4147       }
4148
4149       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4150                                ByteValues);
4151     }
4152   }
4153   
4154   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4155   // the input value to the bswap.  Some observations: 1) if more than one byte
4156   // is demanded from this input, then it could not be successfully assembled
4157   // into a byteswap.  At least one of the two bytes would not be aligned with
4158   // their ultimate destination.
4159   if (!isPowerOf2_32(ByteMask)) return true;
4160   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4161   
4162   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4163   // is demanded, it needs to go into byte 0 of the result.  This means that the
4164   // byte needs to be shifted until it lands in the right byte bucket.  The
4165   // shift amount depends on the position: if the byte is coming from the high
4166   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4167   // low part, it must be shifted left.
4168   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4169   if (InputByteNo < ByteValues.size()/2) {
4170     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4171       return true;
4172   } else {
4173     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4174       return true;
4175   }
4176   
4177   // If the destination byte value is already defined, the values are or'd
4178   // together, which isn't a bswap (unless it's an or of the same bits).
4179   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4180     return true;
4181   ByteValues[DestByteNo] = V;
4182   return false;
4183 }
4184
4185 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4186 /// If so, insert the new bswap intrinsic and return it.
4187 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4188   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4189   if (!ITy || ITy->getBitWidth() % 16 || 
4190       // ByteMask only allows up to 32-byte values.
4191       ITy->getBitWidth() > 32*8) 
4192     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4193   
4194   /// ByteValues - For each byte of the result, we keep track of which value
4195   /// defines each byte.
4196   SmallVector<Value*, 8> ByteValues;
4197   ByteValues.resize(ITy->getBitWidth()/8);
4198     
4199   // Try to find all the pieces corresponding to the bswap.
4200   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4201   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4202     return 0;
4203   
4204   // Check to see if all of the bytes come from the same value.
4205   Value *V = ByteValues[0];
4206   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4207   
4208   // Check to make sure that all of the bytes come from the same value.
4209   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4210     if (ByteValues[i] != V)
4211       return 0;
4212   const Type *Tys[] = { ITy };
4213   Module *M = I.getParent()->getParent()->getParent();
4214   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4215   return CallInst::Create(F, V);
4216 }
4217
4218 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4219 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4220 /// we can simplify this expression to "cond ? C : D or B".
4221 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4222                                          Value *C, Value *D) {
4223   // If A is not a select of -1/0, this cannot match.
4224   Value *Cond = 0;
4225   if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4226     return 0;
4227
4228   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4229   if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4230     return SelectInst::Create(Cond, C, B);
4231   if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4232     return SelectInst::Create(Cond, C, B);
4233   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4234   if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4235     return SelectInst::Create(Cond, C, D);
4236   if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4237     return SelectInst::Create(Cond, C, D);
4238   return 0;
4239 }
4240
4241 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4242   bool Changed = SimplifyCommutative(I);
4243   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4244
4245   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4246     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4247
4248   // or X, X = X
4249   if (Op0 == Op1)
4250     return ReplaceInstUsesWith(I, Op0);
4251
4252   // See if we can simplify any instructions used by the instruction whose sole 
4253   // purpose is to compute bits we don't care about.
4254   if (!isa<VectorType>(I.getType())) {
4255     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4256     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4257     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4258                              KnownZero, KnownOne))
4259       return &I;
4260   } else if (isa<ConstantAggregateZero>(Op1)) {
4261     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4262   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4263     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4264       return ReplaceInstUsesWith(I, I.getOperand(1));
4265   }
4266     
4267
4268   
4269   // or X, -1 == -1
4270   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4271     ConstantInt *C1 = 0; Value *X = 0;
4272     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4273     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4274       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4275       InsertNewInstBefore(Or, I);
4276       Or->takeName(Op0);
4277       return BinaryOperator::CreateAnd(Or, 
4278                ConstantInt::get(RHS->getValue() | C1->getValue()));
4279     }
4280
4281     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4282     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4283       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4284       InsertNewInstBefore(Or, I);
4285       Or->takeName(Op0);
4286       return BinaryOperator::CreateXor(Or,
4287                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4288     }
4289
4290     // Try to fold constant and into select arguments.
4291     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4292       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4293         return R;
4294     if (isa<PHINode>(Op0))
4295       if (Instruction *NV = FoldOpIntoPhi(I))
4296         return NV;
4297   }
4298
4299   Value *A = 0, *B = 0;
4300   ConstantInt *C1 = 0, *C2 = 0;
4301
4302   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4303     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4304       return ReplaceInstUsesWith(I, Op1);
4305   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4306     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4307       return ReplaceInstUsesWith(I, Op0);
4308
4309   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4310   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4311   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4312       match(Op1, m_Or(m_Value(), m_Value())) ||
4313       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4314        match(Op1, m_Shift(m_Value(), m_Value())))) {
4315     if (Instruction *BSwap = MatchBSwap(I))
4316       return BSwap;
4317   }
4318   
4319   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4320   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4321       MaskedValueIsZero(Op1, C1->getValue())) {
4322     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4323     InsertNewInstBefore(NOr, I);
4324     NOr->takeName(Op0);
4325     return BinaryOperator::CreateXor(NOr, C1);
4326   }
4327
4328   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4329   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4330       MaskedValueIsZero(Op0, C1->getValue())) {
4331     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4332     InsertNewInstBefore(NOr, I);
4333     NOr->takeName(Op0);
4334     return BinaryOperator::CreateXor(NOr, C1);
4335   }
4336
4337   // (A & C)|(B & D)
4338   Value *C = 0, *D = 0;
4339   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4340       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4341     Value *V1 = 0, *V2 = 0, *V3 = 0;
4342     C1 = dyn_cast<ConstantInt>(C);
4343     C2 = dyn_cast<ConstantInt>(D);
4344     if (C1 && C2) {  // (A & C1)|(B & C2)
4345       // If we have: ((V + N) & C1) | (V & C2)
4346       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4347       // replace with V+N.
4348       if (C1->getValue() == ~C2->getValue()) {
4349         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4350             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4351           // Add commutes, try both ways.
4352           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4353             return ReplaceInstUsesWith(I, A);
4354           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4355             return ReplaceInstUsesWith(I, A);
4356         }
4357         // Or commutes, try both ways.
4358         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4359             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4360           // Add commutes, try both ways.
4361           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4362             return ReplaceInstUsesWith(I, B);
4363           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4364             return ReplaceInstUsesWith(I, B);
4365         }
4366       }
4367       V1 = 0; V2 = 0; V3 = 0;
4368     }
4369     
4370     // Check to see if we have any common things being and'ed.  If so, find the
4371     // terms for V1 & (V2|V3).
4372     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4373       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4374         V1 = A, V2 = C, V3 = D;
4375       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4376         V1 = A, V2 = B, V3 = C;
4377       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4378         V1 = C, V2 = A, V3 = D;
4379       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4380         V1 = C, V2 = A, V3 = B;
4381       
4382       if (V1) {
4383         Value *Or =
4384           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4385         return BinaryOperator::CreateAnd(V1, Or);
4386       }
4387     }
4388
4389     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4390     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4391       return Match;
4392     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4393       return Match;
4394     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4395       return Match;
4396     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4397       return Match;
4398   }
4399   
4400   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4401   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4402     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4403       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4404           SI0->getOperand(1) == SI1->getOperand(1) &&
4405           (SI0->hasOneUse() || SI1->hasOneUse())) {
4406         Instruction *NewOp =
4407         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4408                                                      SI1->getOperand(0),
4409                                                      SI0->getName()), I);
4410         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4411                                       SI1->getOperand(1));
4412       }
4413   }
4414
4415   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4416     if (A == Op1)   // ~A | A == -1
4417       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4418   } else {
4419     A = 0;
4420   }
4421   // Note, A is still live here!
4422   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4423     if (Op0 == B)
4424       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4425
4426     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4427     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4428       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4429                                               I.getName()+".demorgan"), I);
4430       return BinaryOperator::CreateNot(And);
4431     }
4432   }
4433
4434   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4435   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4436     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4437       return R;
4438
4439     Value *Val;
4440     ConstantInt *LHSCst, *RHSCst;
4441     ICmpInst::Predicate LHSCC, RHSCC;
4442     // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4443     if (match(Op0, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) &&
4444         match(RHS, m_ICmp(RHSCC, m_Specific(Val), m_ConstantInt(RHSCst))) &&
4445         
4446         // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4447         LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4448         RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4449         LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4450         RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4451         
4452         // We can't fold (ugt x, C) | (sgt x, C2).
4453         PredicatesFoldable(LHSCC, RHSCC)) {
4454       // Ensure that the larger constant is on the RHS.
4455       ICmpInst *LHS = cast<ICmpInst>(Op0);
4456       bool NeedsSwap;
4457       if (ICmpInst::isEquality(LHSCC) ? ICmpInst::isSignedPredicate(RHSCC)
4458                                       : ICmpInst::isSignedPredicate(LHSCC))
4459         NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4460       else
4461         NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4462         
4463       if (NeedsSwap) {
4464         std::swap(LHS, RHS);
4465         std::swap(LHSCst, RHSCst);
4466         std::swap(LHSCC, RHSCC);
4467       }
4468
4469       // At this point, we know we have have two icmp instructions
4470       // comparing a value against two constants and or'ing the result
4471       // together.  Because of the above check, we know that we only have
4472       // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4473       // FoldICmpLogical check above), that the two constants are not
4474       // equal.
4475       assert(LHSCst != RHSCst && "Compares not folded above?");
4476
4477       switch (LHSCC) {
4478       default: assert(0 && "Unknown integer condition code!");
4479       case ICmpInst::ICMP_EQ:
4480         switch (RHSCC) {
4481         default: assert(0 && "Unknown integer condition code!");
4482         case ICmpInst::ICMP_EQ:
4483           if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4484             Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4485             Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4486                                                          Val->getName()+".off");
4487             InsertNewInstBefore(Add, I);
4488             AddCST = Subtract(AddOne(RHSCst), LHSCst);
4489             return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4490           }
4491           break;                         // (X == 13 | X == 15) -> no change
4492         case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4493         case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4494           break;
4495         case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4496         case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4497         case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4498           return ReplaceInstUsesWith(I, RHS);
4499         }
4500         break;
4501       case ICmpInst::ICMP_NE:
4502         switch (RHSCC) {
4503         default: assert(0 && "Unknown integer condition code!");
4504         case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4505         case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4506         case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4507           return ReplaceInstUsesWith(I, LHS);
4508         case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4509         case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4510         case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4511           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4512         }
4513         break;
4514       case ICmpInst::ICMP_ULT:
4515         switch (RHSCC) {
4516         default: assert(0 && "Unknown integer condition code!");
4517         case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4518           break;
4519         case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4520           // If RHSCst is [us]MAXINT, it is always false.  Not handling
4521           // this can cause overflow.
4522           if (RHSCst->isMaxValue(false))
4523             return ReplaceInstUsesWith(I, LHS);
4524           return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4525         case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4526           break;
4527         case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4528         case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4529           return ReplaceInstUsesWith(I, RHS);
4530         case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4531           break;
4532         }
4533         break;
4534       case ICmpInst::ICMP_SLT:
4535         switch (RHSCC) {
4536         default: assert(0 && "Unknown integer condition code!");
4537         case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4538           break;
4539         case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4540           // If RHSCst is [us]MAXINT, it is always false.  Not handling
4541           // this can cause overflow.
4542           if (RHSCst->isMaxValue(true))
4543             return ReplaceInstUsesWith(I, LHS);
4544           return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4545         case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4546           break;
4547         case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4548         case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4549           return ReplaceInstUsesWith(I, RHS);
4550         case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4551           break;
4552         }
4553         break;
4554       case ICmpInst::ICMP_UGT:
4555         switch (RHSCC) {
4556         default: assert(0 && "Unknown integer condition code!");
4557         case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4558         case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4559           return ReplaceInstUsesWith(I, LHS);
4560         case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4561           break;
4562         case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4563         case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4564           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4565         case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4566           break;
4567         }
4568         break;
4569       case ICmpInst::ICMP_SGT:
4570         switch (RHSCC) {
4571         default: assert(0 && "Unknown integer condition code!");
4572         case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4573         case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4574           return ReplaceInstUsesWith(I, LHS);
4575         case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4576           break;
4577         case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4578         case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4579           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4580         case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4581           break;
4582         }
4583         break;
4584       }
4585     }
4586   }
4587     
4588   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4589   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4590     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4591       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4592         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4593             !isa<ICmpInst>(Op1C->getOperand(0))) {
4594           const Type *SrcTy = Op0C->getOperand(0)->getType();
4595           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4596               // Only do this if the casts both really cause code to be
4597               // generated.
4598               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4599                                 I.getType(), TD) &&
4600               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4601                                 I.getType(), TD)) {
4602             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4603                                                           Op1C->getOperand(0),
4604                                                           I.getName());
4605             InsertNewInstBefore(NewOp, I);
4606             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4607           }
4608         }
4609       }
4610   }
4611   
4612     
4613   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4614   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4615     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4616       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4617           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4618           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4619         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4620           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4621             // If either of the constants are nans, then the whole thing returns
4622             // true.
4623             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4624               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4625             
4626             // Otherwise, no need to compare the two constants, compare the
4627             // rest.
4628             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4629                                 RHS->getOperand(0));
4630           }
4631       } else {
4632         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4633         FCmpInst::Predicate Op0CC, Op1CC;
4634         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4635             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4636           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4637             // Swap RHS operands to match LHS.
4638             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4639             std::swap(Op1LHS, Op1RHS);
4640           }
4641           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4642             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4643             if (Op0CC == Op1CC)
4644               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4645             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4646                      Op1CC == FCmpInst::FCMP_TRUE)
4647               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4648             else if (Op0CC == FCmpInst::FCMP_FALSE)
4649               return ReplaceInstUsesWith(I, Op1);
4650             else if (Op1CC == FCmpInst::FCMP_FALSE)
4651               return ReplaceInstUsesWith(I, Op0);
4652             bool Op0Ordered;
4653             bool Op1Ordered;
4654             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4655             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4656             if (Op0Ordered == Op1Ordered) {
4657               // If both are ordered or unordered, return a new fcmp with
4658               // or'ed predicates.
4659               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4660                                        Op0LHS, Op0RHS);
4661               if (Instruction *I = dyn_cast<Instruction>(RV))
4662                 return I;
4663               // Otherwise, it's a constant boolean value...
4664               return ReplaceInstUsesWith(I, RV);
4665             }
4666           }
4667         }
4668       }
4669     }
4670   }
4671
4672   return Changed ? &I : 0;
4673 }
4674
4675 namespace {
4676
4677 // XorSelf - Implements: X ^ X --> 0
4678 struct XorSelf {
4679   Value *RHS;
4680   XorSelf(Value *rhs) : RHS(rhs) {}
4681   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4682   Instruction *apply(BinaryOperator &Xor) const {
4683     return &Xor;
4684   }
4685 };
4686
4687 }
4688
4689 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4690   bool Changed = SimplifyCommutative(I);
4691   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4692
4693   if (isa<UndefValue>(Op1)) {
4694     if (isa<UndefValue>(Op0))
4695       // Handle undef ^ undef -> 0 special case. This is a common
4696       // idiom (misuse).
4697       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4698     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4699   }
4700
4701   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4702   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4703     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4704     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4705   }
4706   
4707   // See if we can simplify any instructions used by the instruction whose sole 
4708   // purpose is to compute bits we don't care about.
4709   if (!isa<VectorType>(I.getType())) {
4710     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4711     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4712     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4713                              KnownZero, KnownOne))
4714       return &I;
4715   } else if (isa<ConstantAggregateZero>(Op1)) {
4716     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4717   }
4718
4719   // Is this a ~ operation?
4720   if (Value *NotOp = dyn_castNotVal(&I)) {
4721     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4722     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4723     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4724       if (Op0I->getOpcode() == Instruction::And || 
4725           Op0I->getOpcode() == Instruction::Or) {
4726         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4727         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4728           Instruction *NotY =
4729             BinaryOperator::CreateNot(Op0I->getOperand(1),
4730                                       Op0I->getOperand(1)->getName()+".not");
4731           InsertNewInstBefore(NotY, I);
4732           if (Op0I->getOpcode() == Instruction::And)
4733             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4734           else
4735             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4736         }
4737       }
4738     }
4739   }
4740   
4741   
4742   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4743     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4744     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4745       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4746         return new ICmpInst(ICI->getInversePredicate(),
4747                             ICI->getOperand(0), ICI->getOperand(1));
4748
4749       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4750         return new FCmpInst(FCI->getInversePredicate(),
4751                             FCI->getOperand(0), FCI->getOperand(1));
4752     }
4753
4754     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4755     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4756       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4757         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4758           Instruction::CastOps Opcode = Op0C->getOpcode();
4759           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4760             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4761                                              Op0C->getDestTy())) {
4762               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4763                                      CI->getOpcode(), CI->getInversePredicate(),
4764                                      CI->getOperand(0), CI->getOperand(1)), I);
4765               NewCI->takeName(CI);
4766               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4767             }
4768           }
4769         }
4770       }
4771     }
4772
4773     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4774       // ~(c-X) == X-c-1 == X+(-c-1)
4775       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4776         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4777           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4778           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4779                                               ConstantInt::get(I.getType(), 1));
4780           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4781         }
4782           
4783       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4784         if (Op0I->getOpcode() == Instruction::Add) {
4785           // ~(X-c) --> (-c-1)-X
4786           if (RHS->isAllOnesValue()) {
4787             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4788             return BinaryOperator::CreateSub(
4789                            ConstantExpr::getSub(NegOp0CI,
4790                                              ConstantInt::get(I.getType(), 1)),
4791                                           Op0I->getOperand(0));
4792           } else if (RHS->getValue().isSignBit()) {
4793             // (X + C) ^ signbit -> (X + C + signbit)
4794             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4795             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4796
4797           }
4798         } else if (Op0I->getOpcode() == Instruction::Or) {
4799           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4800           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4801             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4802             // Anything in both C1 and C2 is known to be zero, remove it from
4803             // NewRHS.
4804             Constant *CommonBits = And(Op0CI, RHS);
4805             NewRHS = ConstantExpr::getAnd(NewRHS, 
4806                                           ConstantExpr::getNot(CommonBits));
4807             AddToWorkList(Op0I);
4808             I.setOperand(0, Op0I->getOperand(0));
4809             I.setOperand(1, NewRHS);
4810             return &I;
4811           }
4812         }
4813       }
4814     }
4815
4816     // Try to fold constant and into select arguments.
4817     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4818       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4819         return R;
4820     if (isa<PHINode>(Op0))
4821       if (Instruction *NV = FoldOpIntoPhi(I))
4822         return NV;
4823   }
4824
4825   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4826     if (X == Op1)
4827       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4828
4829   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4830     if (X == Op0)
4831       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4832
4833   
4834   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4835   if (Op1I) {
4836     Value *A, *B;
4837     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4838       if (A == Op0) {              // B^(B|A) == (A|B)^B
4839         Op1I->swapOperands();
4840         I.swapOperands();
4841         std::swap(Op0, Op1);
4842       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4843         I.swapOperands();     // Simplified below.
4844         std::swap(Op0, Op1);
4845       }
4846     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4847       if (Op0 == A)                                          // A^(A^B) == B
4848         return ReplaceInstUsesWith(I, B);
4849       else if (Op0 == B)                                     // A^(B^A) == B
4850         return ReplaceInstUsesWith(I, A);
4851     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4852       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4853         Op1I->swapOperands();
4854         std::swap(A, B);
4855       }
4856       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4857         I.swapOperands();     // Simplified below.
4858         std::swap(Op0, Op1);
4859       }
4860     }
4861   }
4862   
4863   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4864   if (Op0I) {
4865     Value *A, *B;
4866     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4867       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4868         std::swap(A, B);
4869       if (B == Op1) {                                // (A|B)^B == A & ~B
4870         Instruction *NotB =
4871           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4872         return BinaryOperator::CreateAnd(A, NotB);
4873       }
4874     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4875       if (Op1 == A)                                          // (A^B)^A == B
4876         return ReplaceInstUsesWith(I, B);
4877       else if (Op1 == B)                                     // (B^A)^A == B
4878         return ReplaceInstUsesWith(I, A);
4879     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4880       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4881         std::swap(A, B);
4882       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4883           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4884         Instruction *N =
4885           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4886         return BinaryOperator::CreateAnd(N, Op1);
4887       }
4888     }
4889   }
4890   
4891   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4892   if (Op0I && Op1I && Op0I->isShift() && 
4893       Op0I->getOpcode() == Op1I->getOpcode() && 
4894       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4895       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4896     Instruction *NewOp =
4897       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4898                                                     Op1I->getOperand(0),
4899                                                     Op0I->getName()), I);
4900     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4901                                   Op1I->getOperand(1));
4902   }
4903     
4904   if (Op0I && Op1I) {
4905     Value *A, *B, *C, *D;
4906     // (A & B)^(A | B) -> A ^ B
4907     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4908         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4909       if ((A == C && B == D) || (A == D && B == C)) 
4910         return BinaryOperator::CreateXor(A, B);
4911     }
4912     // (A | B)^(A & B) -> A ^ B
4913     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4914         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4915       if ((A == C && B == D) || (A == D && B == C)) 
4916         return BinaryOperator::CreateXor(A, B);
4917     }
4918     
4919     // (A & B)^(C & D)
4920     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4921         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4922         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4923       // (X & Y)^(X & Y) -> (Y^Z) & X
4924       Value *X = 0, *Y = 0, *Z = 0;
4925       if (A == C)
4926         X = A, Y = B, Z = D;
4927       else if (A == D)
4928         X = A, Y = B, Z = C;
4929       else if (B == C)
4930         X = B, Y = A, Z = D;
4931       else if (B == D)
4932         X = B, Y = A, Z = C;
4933       
4934       if (X) {
4935         Instruction *NewOp =
4936         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4937         return BinaryOperator::CreateAnd(NewOp, X);
4938       }
4939     }
4940   }
4941     
4942   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4943   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4944     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4945       return R;
4946
4947   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4948   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4949     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4950       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4951         const Type *SrcTy = Op0C->getOperand(0)->getType();
4952         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4953             // Only do this if the casts both really cause code to be generated.
4954             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4955                               I.getType(), TD) &&
4956             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4957                               I.getType(), TD)) {
4958           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4959                                                          Op1C->getOperand(0),
4960                                                          I.getName());
4961           InsertNewInstBefore(NewOp, I);
4962           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4963         }
4964       }
4965   }
4966
4967   return Changed ? &I : 0;
4968 }
4969
4970 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4971 /// overflowed for this type.
4972 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4973                             ConstantInt *In2, bool IsSigned = false) {
4974   Result = cast<ConstantInt>(Add(In1, In2));
4975
4976   if (IsSigned)
4977     if (In2->getValue().isNegative())
4978       return Result->getValue().sgt(In1->getValue());
4979     else
4980       return Result->getValue().slt(In1->getValue());
4981   else
4982     return Result->getValue().ult(In1->getValue());
4983 }
4984
4985 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4986 /// overflowed for this type.
4987 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4988                             ConstantInt *In2, bool IsSigned = false) {
4989   Result = cast<ConstantInt>(Subtract(In1, In2));
4990
4991   if (IsSigned)
4992     if (In2->getValue().isNegative())
4993       return Result->getValue().slt(In1->getValue());
4994     else
4995       return Result->getValue().sgt(In1->getValue());
4996   else
4997     return Result->getValue().ugt(In1->getValue());
4998 }
4999
5000 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5001 /// code necessary to compute the offset from the base pointer (without adding
5002 /// in the base pointer).  Return the result as a signed integer of intptr size.
5003 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5004   TargetData &TD = IC.getTargetData();
5005   gep_type_iterator GTI = gep_type_begin(GEP);
5006   const Type *IntPtrTy = TD.getIntPtrType();
5007   Value *Result = Constant::getNullValue(IntPtrTy);
5008
5009   // Build a mask for high order bits.
5010   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5011   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5012
5013   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5014        ++i, ++GTI) {
5015     Value *Op = *i;
5016     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5017     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5018       if (OpC->isZero()) continue;
5019       
5020       // Handle a struct index, which adds its field offset to the pointer.
5021       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5022         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5023         
5024         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5025           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5026         else
5027           Result = IC.InsertNewInstBefore(
5028                    BinaryOperator::CreateAdd(Result,
5029                                              ConstantInt::get(IntPtrTy, Size),
5030                                              GEP->getName()+".offs"), I);
5031         continue;
5032       }
5033       
5034       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5035       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5036       Scale = ConstantExpr::getMul(OC, Scale);
5037       if (Constant *RC = dyn_cast<Constant>(Result))
5038         Result = ConstantExpr::getAdd(RC, Scale);
5039       else {
5040         // Emit an add instruction.
5041         Result = IC.InsertNewInstBefore(
5042            BinaryOperator::CreateAdd(Result, Scale,
5043                                      GEP->getName()+".offs"), I);
5044       }
5045       continue;
5046     }
5047     // Convert to correct type.
5048     if (Op->getType() != IntPtrTy) {
5049       if (Constant *OpC = dyn_cast<Constant>(Op))
5050         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5051       else
5052         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5053                                                  Op->getName()+".c"), I);
5054     }
5055     if (Size != 1) {
5056       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5057       if (Constant *OpC = dyn_cast<Constant>(Op))
5058         Op = ConstantExpr::getMul(OpC, Scale);
5059       else    // We'll let instcombine(mul) convert this to a shl if possible.
5060         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5061                                                   GEP->getName()+".idx"), I);
5062     }
5063
5064     // Emit an add instruction.
5065     if (isa<Constant>(Op) && isa<Constant>(Result))
5066       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5067                                     cast<Constant>(Result));
5068     else
5069       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5070                                                   GEP->getName()+".offs"), I);
5071   }
5072   return Result;
5073 }
5074
5075
5076 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5077 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5078 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5079 /// complex, and scales are involved.  The above expression would also be legal
5080 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5081 /// later form is less amenable to optimization though, and we are allowed to
5082 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5083 ///
5084 /// If we can't emit an optimized form for this expression, this returns null.
5085 /// 
5086 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5087                                           InstCombiner &IC) {
5088   TargetData &TD = IC.getTargetData();
5089   gep_type_iterator GTI = gep_type_begin(GEP);
5090
5091   // Check to see if this gep only has a single variable index.  If so, and if
5092   // any constant indices are a multiple of its scale, then we can compute this
5093   // in terms of the scale of the variable index.  For example, if the GEP
5094   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5095   // because the expression will cross zero at the same point.
5096   unsigned i, e = GEP->getNumOperands();
5097   int64_t Offset = 0;
5098   for (i = 1; i != e; ++i, ++GTI) {
5099     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5100       // Compute the aggregate offset of constant indices.
5101       if (CI->isZero()) continue;
5102
5103       // Handle a struct index, which adds its field offset to the pointer.
5104       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5105         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5106       } else {
5107         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5108         Offset += Size*CI->getSExtValue();
5109       }
5110     } else {
5111       // Found our variable index.
5112       break;
5113     }
5114   }
5115   
5116   // If there are no variable indices, we must have a constant offset, just
5117   // evaluate it the general way.
5118   if (i == e) return 0;
5119   
5120   Value *VariableIdx = GEP->getOperand(i);
5121   // Determine the scale factor of the variable element.  For example, this is
5122   // 4 if the variable index is into an array of i32.
5123   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5124   
5125   // Verify that there are no other variable indices.  If so, emit the hard way.
5126   for (++i, ++GTI; i != e; ++i, ++GTI) {
5127     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5128     if (!CI) return 0;
5129    
5130     // Compute the aggregate offset of constant indices.
5131     if (CI->isZero()) continue;
5132     
5133     // Handle a struct index, which adds its field offset to the pointer.
5134     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5135       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5136     } else {
5137       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5138       Offset += Size*CI->getSExtValue();
5139     }
5140   }
5141   
5142   // Okay, we know we have a single variable index, which must be a
5143   // pointer/array/vector index.  If there is no offset, life is simple, return
5144   // the index.
5145   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5146   if (Offset == 0) {
5147     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5148     // we don't need to bother extending: the extension won't affect where the
5149     // computation crosses zero.
5150     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5151       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5152                                   VariableIdx->getNameStart(), &I);
5153     return VariableIdx;
5154   }
5155   
5156   // Otherwise, there is an index.  The computation we will do will be modulo
5157   // the pointer size, so get it.
5158   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5159   
5160   Offset &= PtrSizeMask;
5161   VariableScale &= PtrSizeMask;
5162
5163   // To do this transformation, any constant index must be a multiple of the
5164   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5165   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5166   // multiple of the variable scale.
5167   int64_t NewOffs = Offset / (int64_t)VariableScale;
5168   if (Offset != NewOffs*(int64_t)VariableScale)
5169     return 0;
5170
5171   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5172   const Type *IntPtrTy = TD.getIntPtrType();
5173   if (VariableIdx->getType() != IntPtrTy)
5174     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5175                                               true /*SExt*/, 
5176                                               VariableIdx->getNameStart(), &I);
5177   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5178   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5179 }
5180
5181
5182 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5183 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5184 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5185                                        ICmpInst::Predicate Cond,
5186                                        Instruction &I) {
5187   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5188
5189   // Look through bitcasts.
5190   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5191     RHS = BCI->getOperand(0);
5192
5193   Value *PtrBase = GEPLHS->getOperand(0);
5194   if (PtrBase == RHS) {
5195     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5196     // This transformation (ignoring the base and scales) is valid because we
5197     // know pointers can't overflow.  See if we can output an optimized form.
5198     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5199     
5200     // If not, synthesize the offset the hard way.
5201     if (Offset == 0)
5202       Offset = EmitGEPOffset(GEPLHS, I, *this);
5203     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5204                         Constant::getNullValue(Offset->getType()));
5205   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5206     // If the base pointers are different, but the indices are the same, just
5207     // compare the base pointer.
5208     if (PtrBase != GEPRHS->getOperand(0)) {
5209       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5210       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5211                         GEPRHS->getOperand(0)->getType();
5212       if (IndicesTheSame)
5213         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5214           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5215             IndicesTheSame = false;
5216             break;
5217           }
5218
5219       // If all indices are the same, just compare the base pointers.
5220       if (IndicesTheSame)
5221         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5222                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5223
5224       // Otherwise, the base pointers are different and the indices are
5225       // different, bail out.
5226       return 0;
5227     }
5228
5229     // If one of the GEPs has all zero indices, recurse.
5230     bool AllZeros = true;
5231     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5232       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5233           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5234         AllZeros = false;
5235         break;
5236       }
5237     if (AllZeros)
5238       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5239                           ICmpInst::getSwappedPredicate(Cond), I);
5240
5241     // If the other GEP has all zero indices, recurse.
5242     AllZeros = true;
5243     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5244       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5245           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5246         AllZeros = false;
5247         break;
5248       }
5249     if (AllZeros)
5250       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5251
5252     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5253       // If the GEPs only differ by one index, compare it.
5254       unsigned NumDifferences = 0;  // Keep track of # differences.
5255       unsigned DiffOperand = 0;     // The operand that differs.
5256       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5257         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5258           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5259                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5260             // Irreconcilable differences.
5261             NumDifferences = 2;
5262             break;
5263           } else {
5264             if (NumDifferences++) break;
5265             DiffOperand = i;
5266           }
5267         }
5268
5269       if (NumDifferences == 0)   // SAME GEP?
5270         return ReplaceInstUsesWith(I, // No comparison is needed here.
5271                                    ConstantInt::get(Type::Int1Ty,
5272                                              ICmpInst::isTrueWhenEqual(Cond)));
5273
5274       else if (NumDifferences == 1) {
5275         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5276         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5277         // Make sure we do a signed comparison here.
5278         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5279       }
5280     }
5281
5282     // Only lower this if the icmp is the only user of the GEP or if we expect
5283     // the result to fold to a constant!
5284     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5285         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5286       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5287       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5288       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5289       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5290     }
5291   }
5292   return 0;
5293 }
5294
5295 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5296 ///
5297 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5298                                                 Instruction *LHSI,
5299                                                 Constant *RHSC) {
5300   if (!isa<ConstantFP>(RHSC)) return 0;
5301   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5302   
5303   // Get the width of the mantissa.  We don't want to hack on conversions that
5304   // might lose information from the integer, e.g. "i64 -> float"
5305   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5306   if (MantissaWidth == -1) return 0;  // Unknown.
5307   
5308   // Check to see that the input is converted from an integer type that is small
5309   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5310   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5311   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5312   
5313   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5314   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5315   if (LHSUnsigned)
5316     ++InputSize;
5317   
5318   // If the conversion would lose info, don't hack on this.
5319   if ((int)InputSize > MantissaWidth)
5320     return 0;
5321   
5322   // Otherwise, we can potentially simplify the comparison.  We know that it
5323   // will always come through as an integer value and we know the constant is
5324   // not a NAN (it would have been previously simplified).
5325   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5326   
5327   ICmpInst::Predicate Pred;
5328   switch (I.getPredicate()) {
5329   default: assert(0 && "Unexpected predicate!");
5330   case FCmpInst::FCMP_UEQ:
5331   case FCmpInst::FCMP_OEQ:
5332     Pred = ICmpInst::ICMP_EQ;
5333     break;
5334   case FCmpInst::FCMP_UGT:
5335   case FCmpInst::FCMP_OGT:
5336     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5337     break;
5338   case FCmpInst::FCMP_UGE:
5339   case FCmpInst::FCMP_OGE:
5340     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5341     break;
5342   case FCmpInst::FCMP_ULT:
5343   case FCmpInst::FCMP_OLT:
5344     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5345     break;
5346   case FCmpInst::FCMP_ULE:
5347   case FCmpInst::FCMP_OLE:
5348     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5349     break;
5350   case FCmpInst::FCMP_UNE:
5351   case FCmpInst::FCMP_ONE:
5352     Pred = ICmpInst::ICMP_NE;
5353     break;
5354   case FCmpInst::FCMP_ORD:
5355     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5356   case FCmpInst::FCMP_UNO:
5357     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5358   }
5359   
5360   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5361   
5362   // Now we know that the APFloat is a normal number, zero or inf.
5363   
5364   // See if the FP constant is too large for the integer.  For example,
5365   // comparing an i8 to 300.0.
5366   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5367   
5368   if (!LHSUnsigned) {
5369     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5370     // and large values.
5371     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5372     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5373                           APFloat::rmNearestTiesToEven);
5374     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5375       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5376           Pred == ICmpInst::ICMP_SLE)
5377         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5378       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5379     }
5380   } else {
5381     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5382     // +INF and large values.
5383     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5384     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5385                           APFloat::rmNearestTiesToEven);
5386     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5387       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5388           Pred == ICmpInst::ICMP_ULE)
5389         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5390       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5391     }
5392   }
5393   
5394   if (!LHSUnsigned) {
5395     // See if the RHS value is < SignedMin.
5396     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5397     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5398                           APFloat::rmNearestTiesToEven);
5399     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5400       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5401           Pred == ICmpInst::ICMP_SGE)
5402         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5403       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5404     }
5405   }
5406
5407   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5408   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5409   // casting the FP value to the integer value and back, checking for equality.
5410   // Don't do this for zero, because -0.0 is not fractional.
5411   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5412   if (!RHS.isZero() &&
5413       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5414     // If we had a comparison against a fractional value, we have to adjust the
5415     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5416     // at this point.
5417     switch (Pred) {
5418     default: assert(0 && "Unexpected integer comparison!");
5419     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5420       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5421     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5422       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5423     case ICmpInst::ICMP_ULE:
5424       // (float)int <= 4.4   --> int <= 4
5425       // (float)int <= -4.4  --> false
5426       if (RHS.isNegative())
5427         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5428       break;
5429     case ICmpInst::ICMP_SLE:
5430       // (float)int <= 4.4   --> int <= 4
5431       // (float)int <= -4.4  --> int < -4
5432       if (RHS.isNegative())
5433         Pred = ICmpInst::ICMP_SLT;
5434       break;
5435     case ICmpInst::ICMP_ULT:
5436       // (float)int < -4.4   --> false
5437       // (float)int < 4.4    --> int <= 4
5438       if (RHS.isNegative())
5439         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5440       Pred = ICmpInst::ICMP_ULE;
5441       break;
5442     case ICmpInst::ICMP_SLT:
5443       // (float)int < -4.4   --> int < -4
5444       // (float)int < 4.4    --> int <= 4
5445       if (!RHS.isNegative())
5446         Pred = ICmpInst::ICMP_SLE;
5447       break;
5448     case ICmpInst::ICMP_UGT:
5449       // (float)int > 4.4    --> int > 4
5450       // (float)int > -4.4   --> true
5451       if (RHS.isNegative())
5452         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5453       break;
5454     case ICmpInst::ICMP_SGT:
5455       // (float)int > 4.4    --> int > 4
5456       // (float)int > -4.4   --> int >= -4
5457       if (RHS.isNegative())
5458         Pred = ICmpInst::ICMP_SGE;
5459       break;
5460     case ICmpInst::ICMP_UGE:
5461       // (float)int >= -4.4   --> true
5462       // (float)int >= 4.4    --> int > 4
5463       if (!RHS.isNegative())
5464         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5465       Pred = ICmpInst::ICMP_UGT;
5466       break;
5467     case ICmpInst::ICMP_SGE:
5468       // (float)int >= -4.4   --> int >= -4
5469       // (float)int >= 4.4    --> int > 4
5470       if (!RHS.isNegative())
5471         Pred = ICmpInst::ICMP_SGT;
5472       break;
5473     }
5474   }
5475
5476   // Lower this FP comparison into an appropriate integer version of the
5477   // comparison.
5478   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5479 }
5480
5481 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5482   bool Changed = SimplifyCompare(I);
5483   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5484
5485   // Fold trivial predicates.
5486   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5487     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5488   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5489     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5490   
5491   // Simplify 'fcmp pred X, X'
5492   if (Op0 == Op1) {
5493     switch (I.getPredicate()) {
5494     default: assert(0 && "Unknown predicate!");
5495     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5496     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5497     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5498       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5499     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5500     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5501     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5502       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5503       
5504     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5505     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5506     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5507     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5508       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5509       I.setPredicate(FCmpInst::FCMP_UNO);
5510       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5511       return &I;
5512       
5513     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5514     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5515     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5516     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5517       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5518       I.setPredicate(FCmpInst::FCMP_ORD);
5519       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5520       return &I;
5521     }
5522   }
5523     
5524   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5525     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5526
5527   // Handle fcmp with constant RHS
5528   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5529     // If the constant is a nan, see if we can fold the comparison based on it.
5530     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5531       if (CFP->getValueAPF().isNaN()) {
5532         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5533           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5534         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5535                "Comparison must be either ordered or unordered!");
5536         // True if unordered.
5537         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5538       }
5539     }
5540     
5541     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5542       switch (LHSI->getOpcode()) {
5543       case Instruction::PHI:
5544         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5545         // block.  If in the same block, we're encouraging jump threading.  If
5546         // not, we are just pessimizing the code by making an i1 phi.
5547         if (LHSI->getParent() == I.getParent())
5548           if (Instruction *NV = FoldOpIntoPhi(I))
5549             return NV;
5550         break;
5551       case Instruction::SIToFP:
5552       case Instruction::UIToFP:
5553         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5554           return NV;
5555         break;
5556       case Instruction::Select:
5557         // If either operand of the select is a constant, we can fold the
5558         // comparison into the select arms, which will cause one to be
5559         // constant folded and the select turned into a bitwise or.
5560         Value *Op1 = 0, *Op2 = 0;
5561         if (LHSI->hasOneUse()) {
5562           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5563             // Fold the known value into the constant operand.
5564             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5565             // Insert a new FCmp of the other select operand.
5566             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5567                                                       LHSI->getOperand(2), RHSC,
5568                                                       I.getName()), I);
5569           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5570             // Fold the known value into the constant operand.
5571             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5572             // Insert a new FCmp of the other select operand.
5573             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5574                                                       LHSI->getOperand(1), RHSC,
5575                                                       I.getName()), I);
5576           }
5577         }
5578
5579         if (Op1)
5580           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5581         break;
5582       }
5583   }
5584
5585   return Changed ? &I : 0;
5586 }
5587
5588 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5589   bool Changed = SimplifyCompare(I);
5590   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5591   const Type *Ty = Op0->getType();
5592
5593   // icmp X, X
5594   if (Op0 == Op1)
5595     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5596                                                    I.isTrueWhenEqual()));
5597
5598   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5599     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5600   
5601   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5602   // addresses never equal each other!  We already know that Op0 != Op1.
5603   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5604        isa<ConstantPointerNull>(Op0)) &&
5605       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5606        isa<ConstantPointerNull>(Op1)))
5607     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5608                                                    !I.isTrueWhenEqual()));
5609
5610   // icmp's with boolean values can always be turned into bitwise operations
5611   if (Ty == Type::Int1Ty) {
5612     switch (I.getPredicate()) {
5613     default: assert(0 && "Invalid icmp instruction!");
5614     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5615       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5616       InsertNewInstBefore(Xor, I);
5617       return BinaryOperator::CreateNot(Xor);
5618     }
5619     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5620       return BinaryOperator::CreateXor(Op0, Op1);
5621
5622     case ICmpInst::ICMP_UGT:
5623       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5624       // FALL THROUGH
5625     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5626       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5627       InsertNewInstBefore(Not, I);
5628       return BinaryOperator::CreateAnd(Not, Op1);
5629     }
5630     case ICmpInst::ICMP_SGT:
5631       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5632       // FALL THROUGH
5633     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5634       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5635       InsertNewInstBefore(Not, I);
5636       return BinaryOperator::CreateAnd(Not, Op0);
5637     }
5638     case ICmpInst::ICMP_UGE:
5639       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5640       // FALL THROUGH
5641     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5642       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5643       InsertNewInstBefore(Not, I);
5644       return BinaryOperator::CreateOr(Not, Op1);
5645     }
5646     case ICmpInst::ICMP_SGE:
5647       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5648       // FALL THROUGH
5649     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5650       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5651       InsertNewInstBefore(Not, I);
5652       return BinaryOperator::CreateOr(Not, Op0);
5653     }
5654     }
5655   }
5656
5657   // See if we are doing a comparison with a constant.
5658   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5659     Value *A, *B;
5660     
5661     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5662     if (I.isEquality() && CI->isNullValue() &&
5663         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5664       // (icmp cond A B) if cond is equality
5665       return new ICmpInst(I.getPredicate(), A, B);
5666     }
5667     
5668     // If we have an icmp le or icmp ge instruction, turn it into the
5669     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5670     // them being folded in the code below.
5671     switch (I.getPredicate()) {
5672     default: break;
5673     case ICmpInst::ICMP_ULE:
5674       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5675         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5676       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5677     case ICmpInst::ICMP_SLE:
5678       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5679         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5680       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5681     case ICmpInst::ICMP_UGE:
5682       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5683         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5684       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5685     case ICmpInst::ICMP_SGE:
5686       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5687         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5688       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5689     }
5690     
5691     // See if we can fold the comparison based on range information we can get
5692     // by checking whether bits are known to be zero or one in the input.
5693     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5694     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5695     
5696     // If this comparison is a normal comparison, it demands all
5697     // bits, if it is a sign bit comparison, it only demands the sign bit.
5698     bool UnusedBit;
5699     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5700     
5701     if (SimplifyDemandedBits(Op0, 
5702                              isSignBit ? APInt::getSignBit(BitWidth)
5703                                        : APInt::getAllOnesValue(BitWidth),
5704                              KnownZero, KnownOne, 0))
5705       return &I;
5706         
5707     // Given the known and unknown bits, compute a range that the LHS could be
5708     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5709     // EQ and NE we use unsigned values.
5710     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5711     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5712       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5713     else
5714       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5715     
5716     // If Min and Max are known to be the same, then SimplifyDemandedBits
5717     // figured out that the LHS is a constant.  Just constant fold this now so
5718     // that code below can assume that Min != Max.
5719     if (Min == Max)
5720       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5721                                                           ConstantInt::get(Min),
5722                                                           CI));
5723     
5724     // Based on the range information we know about the LHS, see if we can
5725     // simplify this comparison.  For example, (x&4) < 8  is always true.
5726     const APInt &RHSVal = CI->getValue();
5727     switch (I.getPredicate()) {  // LE/GE have been folded already.
5728     default: assert(0 && "Unknown icmp opcode!");
5729     case ICmpInst::ICMP_EQ:
5730       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5731         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5732       break;
5733     case ICmpInst::ICMP_NE:
5734       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5735         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5736       break;
5737     case ICmpInst::ICMP_ULT:
5738       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5739         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5740       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5741         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5742       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5743         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5744       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5745         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5746         
5747       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5748       if (CI->isMinValue(true))
5749         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5750                             ConstantInt::getAllOnesValue(Op0->getType()));
5751       break;
5752     case ICmpInst::ICMP_UGT:
5753       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5754         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5755       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5756         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5757         
5758       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5759         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5760       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5761         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5762       
5763       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5764       if (CI->isMaxValue(true))
5765         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5766                             ConstantInt::getNullValue(Op0->getType()));
5767       break;
5768     case ICmpInst::ICMP_SLT:
5769       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5770         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5771       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5772         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5773       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5774         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5775       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5776         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5777       break;
5778     case ICmpInst::ICMP_SGT: 
5779       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5780         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5781       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5782         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5783         
5784       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5785         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5786       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5787         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5788       break;
5789     }
5790   }
5791
5792   // Test if the ICmpInst instruction is used exclusively by a select as
5793   // part of a minimum or maximum operation. If so, refrain from doing
5794   // any other folding. This helps out other analyses which understand
5795   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5796   // and CodeGen. And in this case, at least one of the comparison
5797   // operands has at least one user besides the compare (the select),
5798   // which would often largely negate the benefit of folding anyway.
5799   if (I.hasOneUse())
5800     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5801       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5802           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5803         return 0;
5804
5805   // See if we are doing a comparison between a constant and an instruction that
5806   // can be folded into the comparison.
5807   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5808     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5809     // instruction, see if that instruction also has constants so that the 
5810     // instruction can be folded into the icmp 
5811     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5812       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5813         return Res;
5814   }
5815
5816   // Handle icmp with constant (but not simple integer constant) RHS
5817   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5818     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5819       switch (LHSI->getOpcode()) {
5820       case Instruction::GetElementPtr:
5821         if (RHSC->isNullValue()) {
5822           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5823           bool isAllZeros = true;
5824           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5825             if (!isa<Constant>(LHSI->getOperand(i)) ||
5826                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5827               isAllZeros = false;
5828               break;
5829             }
5830           if (isAllZeros)
5831             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5832                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5833         }
5834         break;
5835
5836       case Instruction::PHI:
5837         // Only fold icmp into the PHI if the phi and fcmp are in the same
5838         // block.  If in the same block, we're encouraging jump threading.  If
5839         // not, we are just pessimizing the code by making an i1 phi.
5840         if (LHSI->getParent() == I.getParent())
5841           if (Instruction *NV = FoldOpIntoPhi(I))
5842             return NV;
5843         break;
5844       case Instruction::Select: {
5845         // If either operand of the select is a constant, we can fold the
5846         // comparison into the select arms, which will cause one to be
5847         // constant folded and the select turned into a bitwise or.
5848         Value *Op1 = 0, *Op2 = 0;
5849         if (LHSI->hasOneUse()) {
5850           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5851             // Fold the known value into the constant operand.
5852             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5853             // Insert a new ICmp of the other select operand.
5854             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5855                                                    LHSI->getOperand(2), RHSC,
5856                                                    I.getName()), I);
5857           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5858             // Fold the known value into the constant operand.
5859             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5860             // Insert a new ICmp of the other select operand.
5861             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5862                                                    LHSI->getOperand(1), RHSC,
5863                                                    I.getName()), I);
5864           }
5865         }
5866
5867         if (Op1)
5868           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5869         break;
5870       }
5871       case Instruction::Malloc:
5872         // If we have (malloc != null), and if the malloc has a single use, we
5873         // can assume it is successful and remove the malloc.
5874         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5875           AddToWorkList(LHSI);
5876           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5877                                                          !I.isTrueWhenEqual()));
5878         }
5879         break;
5880       }
5881   }
5882
5883   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5884   if (User *GEP = dyn_castGetElementPtr(Op0))
5885     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5886       return NI;
5887   if (User *GEP = dyn_castGetElementPtr(Op1))
5888     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5889                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5890       return NI;
5891
5892   // Test to see if the operands of the icmp are casted versions of other
5893   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5894   // now.
5895   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5896     if (isa<PointerType>(Op0->getType()) && 
5897         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5898       // We keep moving the cast from the left operand over to the right
5899       // operand, where it can often be eliminated completely.
5900       Op0 = CI->getOperand(0);
5901
5902       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5903       // so eliminate it as well.
5904       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5905         Op1 = CI2->getOperand(0);
5906
5907       // If Op1 is a constant, we can fold the cast into the constant.
5908       if (Op0->getType() != Op1->getType()) {
5909         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5910           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5911         } else {
5912           // Otherwise, cast the RHS right before the icmp
5913           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5914         }
5915       }
5916       return new ICmpInst(I.getPredicate(), Op0, Op1);
5917     }
5918   }
5919   
5920   if (isa<CastInst>(Op0)) {
5921     // Handle the special case of: icmp (cast bool to X), <cst>
5922     // This comes up when you have code like
5923     //   int X = A < B;
5924     //   if (X) ...
5925     // For generality, we handle any zero-extension of any operand comparison
5926     // with a constant or another cast from the same type.
5927     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5928       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5929         return R;
5930   }
5931   
5932   // See if it's the same type of instruction on the left and right.
5933   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5934     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5935       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5936           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5937           I.isEquality()) {
5938         switch (Op0I->getOpcode()) {
5939         default: break;
5940         case Instruction::Add:
5941         case Instruction::Sub:
5942         case Instruction::Xor:
5943           // a+x icmp eq/ne b+x --> a icmp b
5944           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5945                               Op1I->getOperand(0));
5946           break;
5947         case Instruction::Mul:
5948           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5949             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5950             // Mask = -1 >> count-trailing-zeros(Cst).
5951             if (!CI->isZero() && !CI->isOne()) {
5952               const APInt &AP = CI->getValue();
5953               ConstantInt *Mask = ConstantInt::get(
5954                                       APInt::getLowBitsSet(AP.getBitWidth(),
5955                                                            AP.getBitWidth() -
5956                                                       AP.countTrailingZeros()));
5957               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5958                                                             Mask);
5959               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5960                                                             Mask);
5961               InsertNewInstBefore(And1, I);
5962               InsertNewInstBefore(And2, I);
5963               return new ICmpInst(I.getPredicate(), And1, And2);
5964             }
5965           }
5966           break;
5967         }
5968       }
5969     }
5970   }
5971   
5972   // ~x < ~y --> y < x
5973   { Value *A, *B;
5974     if (match(Op0, m_Not(m_Value(A))) &&
5975         match(Op1, m_Not(m_Value(B))))
5976       return new ICmpInst(I.getPredicate(), B, A);
5977   }
5978   
5979   if (I.isEquality()) {
5980     Value *A, *B, *C, *D;
5981     
5982     // -x == -y --> x == y
5983     if (match(Op0, m_Neg(m_Value(A))) &&
5984         match(Op1, m_Neg(m_Value(B))))
5985       return new ICmpInst(I.getPredicate(), A, B);
5986     
5987     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5988       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5989         Value *OtherVal = A == Op1 ? B : A;
5990         return new ICmpInst(I.getPredicate(), OtherVal,
5991                             Constant::getNullValue(A->getType()));
5992       }
5993
5994       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5995         // A^c1 == C^c2 --> A == C^(c1^c2)
5996         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5997           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5998             if (Op1->hasOneUse()) {
5999               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6000               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6001               return new ICmpInst(I.getPredicate(), A,
6002                                   InsertNewInstBefore(Xor, I));
6003             }
6004         
6005         // A^B == A^D -> B == D
6006         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6007         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6008         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6009         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6010       }
6011     }
6012     
6013     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6014         (A == Op0 || B == Op0)) {
6015       // A == (A^B)  ->  B == 0
6016       Value *OtherVal = A == Op0 ? B : A;
6017       return new ICmpInst(I.getPredicate(), OtherVal,
6018                           Constant::getNullValue(A->getType()));
6019     }
6020     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6021       // (A-B) == A  ->  B == 0
6022       return new ICmpInst(I.getPredicate(), B,
6023                           Constant::getNullValue(B->getType()));
6024     }
6025     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6026       // A == (A-B)  ->  B == 0
6027       return new ICmpInst(I.getPredicate(), B,
6028                           Constant::getNullValue(B->getType()));
6029     }
6030     
6031     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6032     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6033         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6034         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6035       Value *X = 0, *Y = 0, *Z = 0;
6036       
6037       if (A == C) {
6038         X = B; Y = D; Z = A;
6039       } else if (A == D) {
6040         X = B; Y = C; Z = A;
6041       } else if (B == C) {
6042         X = A; Y = D; Z = B;
6043       } else if (B == D) {
6044         X = A; Y = C; Z = B;
6045       }
6046       
6047       if (X) {   // Build (X^Y) & Z
6048         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6049         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6050         I.setOperand(0, Op1);
6051         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6052         return &I;
6053       }
6054     }
6055   }
6056   return Changed ? &I : 0;
6057 }
6058
6059
6060 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6061 /// and CmpRHS are both known to be integer constants.
6062 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6063                                           ConstantInt *DivRHS) {
6064   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6065   const APInt &CmpRHSV = CmpRHS->getValue();
6066   
6067   // FIXME: If the operand types don't match the type of the divide 
6068   // then don't attempt this transform. The code below doesn't have the
6069   // logic to deal with a signed divide and an unsigned compare (and
6070   // vice versa). This is because (x /s C1) <s C2  produces different 
6071   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6072   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6073   // work. :(  The if statement below tests that condition and bails 
6074   // if it finds it. 
6075   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6076   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6077     return 0;
6078   if (DivRHS->isZero())
6079     return 0; // The ProdOV computation fails on divide by zero.
6080   if (DivIsSigned && DivRHS->isAllOnesValue())
6081     return 0; // The overflow computation also screws up here
6082   if (DivRHS->isOne())
6083     return 0; // Not worth bothering, and eliminates some funny cases
6084               // with INT_MIN.
6085
6086   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6087   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6088   // C2 (CI). By solving for X we can turn this into a range check 
6089   // instead of computing a divide. 
6090   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6091
6092   // Determine if the product overflows by seeing if the product is
6093   // not equal to the divide. Make sure we do the same kind of divide
6094   // as in the LHS instruction that we're folding. 
6095   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6096                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6097
6098   // Get the ICmp opcode
6099   ICmpInst::Predicate Pred = ICI.getPredicate();
6100
6101   // Figure out the interval that is being checked.  For example, a comparison
6102   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6103   // Compute this interval based on the constants involved and the signedness of
6104   // the compare/divide.  This computes a half-open interval, keeping track of
6105   // whether either value in the interval overflows.  After analysis each
6106   // overflow variable is set to 0 if it's corresponding bound variable is valid
6107   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6108   int LoOverflow = 0, HiOverflow = 0;
6109   ConstantInt *LoBound = 0, *HiBound = 0;
6110   
6111   if (!DivIsSigned) {  // udiv
6112     // e.g. X/5 op 3  --> [15, 20)
6113     LoBound = Prod;
6114     HiOverflow = LoOverflow = ProdOV;
6115     if (!HiOverflow)
6116       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6117   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6118     if (CmpRHSV == 0) {       // (X / pos) op 0
6119       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6120       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6121       HiBound = DivRHS;
6122     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6123       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6124       HiOverflow = LoOverflow = ProdOV;
6125       if (!HiOverflow)
6126         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6127     } else {                       // (X / pos) op neg
6128       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6129       HiBound = AddOne(Prod);
6130       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6131       if (!LoOverflow) {
6132         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6133         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6134                                      true) ? -1 : 0;
6135        }
6136     }
6137   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6138     if (CmpRHSV == 0) {       // (X / neg) op 0
6139       // e.g. X/-5 op 0  --> [-4, 5)
6140       LoBound = AddOne(DivRHS);
6141       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6142       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6143         HiOverflow = 1;            // [INTMIN+1, overflow)
6144         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6145       }
6146     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6147       // e.g. X/-5 op 3  --> [-19, -14)
6148       HiBound = AddOne(Prod);
6149       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6150       if (!LoOverflow)
6151         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6152     } else {                       // (X / neg) op neg
6153       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6154       LoOverflow = HiOverflow = ProdOV;
6155       if (!HiOverflow)
6156         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6157     }
6158     
6159     // Dividing by a negative swaps the condition.  LT <-> GT
6160     Pred = ICmpInst::getSwappedPredicate(Pred);
6161   }
6162
6163   Value *X = DivI->getOperand(0);
6164   switch (Pred) {
6165   default: assert(0 && "Unhandled icmp opcode!");
6166   case ICmpInst::ICMP_EQ:
6167     if (LoOverflow && HiOverflow)
6168       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6169     else if (HiOverflow)
6170       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6171                           ICmpInst::ICMP_UGE, X, LoBound);
6172     else if (LoOverflow)
6173       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6174                           ICmpInst::ICMP_ULT, X, HiBound);
6175     else
6176       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6177   case ICmpInst::ICMP_NE:
6178     if (LoOverflow && HiOverflow)
6179       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6180     else if (HiOverflow)
6181       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6182                           ICmpInst::ICMP_ULT, X, LoBound);
6183     else if (LoOverflow)
6184       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6185                           ICmpInst::ICMP_UGE, X, HiBound);
6186     else
6187       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6188   case ICmpInst::ICMP_ULT:
6189   case ICmpInst::ICMP_SLT:
6190     if (LoOverflow == +1)   // Low bound is greater than input range.
6191       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6192     if (LoOverflow == -1)   // Low bound is less than input range.
6193       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6194     return new ICmpInst(Pred, X, LoBound);
6195   case ICmpInst::ICMP_UGT:
6196   case ICmpInst::ICMP_SGT:
6197     if (HiOverflow == +1)       // High bound greater than input range.
6198       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6199     else if (HiOverflow == -1)  // High bound less than input range.
6200       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6201     if (Pred == ICmpInst::ICMP_UGT)
6202       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6203     else
6204       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6205   }
6206 }
6207
6208
6209 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6210 ///
6211 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6212                                                           Instruction *LHSI,
6213                                                           ConstantInt *RHS) {
6214   const APInt &RHSV = RHS->getValue();
6215   
6216   switch (LHSI->getOpcode()) {
6217   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6218     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6219       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6220       // fold the xor.
6221       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6222           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6223         Value *CompareVal = LHSI->getOperand(0);
6224         
6225         // If the sign bit of the XorCST is not set, there is no change to
6226         // the operation, just stop using the Xor.
6227         if (!XorCST->getValue().isNegative()) {
6228           ICI.setOperand(0, CompareVal);
6229           AddToWorkList(LHSI);
6230           return &ICI;
6231         }
6232         
6233         // Was the old condition true if the operand is positive?
6234         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6235         
6236         // If so, the new one isn't.
6237         isTrueIfPositive ^= true;
6238         
6239         if (isTrueIfPositive)
6240           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6241         else
6242           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6243       }
6244     }
6245     break;
6246   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6247     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6248         LHSI->getOperand(0)->hasOneUse()) {
6249       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6250       
6251       // If the LHS is an AND of a truncating cast, we can widen the
6252       // and/compare to be the input width without changing the value
6253       // produced, eliminating a cast.
6254       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6255         // We can do this transformation if either the AND constant does not
6256         // have its sign bit set or if it is an equality comparison. 
6257         // Extending a relational comparison when we're checking the sign
6258         // bit would not work.
6259         if (Cast->hasOneUse() &&
6260             (ICI.isEquality() ||
6261              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6262           uint32_t BitWidth = 
6263             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6264           APInt NewCST = AndCST->getValue();
6265           NewCST.zext(BitWidth);
6266           APInt NewCI = RHSV;
6267           NewCI.zext(BitWidth);
6268           Instruction *NewAnd = 
6269             BinaryOperator::CreateAnd(Cast->getOperand(0),
6270                                       ConstantInt::get(NewCST),LHSI->getName());
6271           InsertNewInstBefore(NewAnd, ICI);
6272           return new ICmpInst(ICI.getPredicate(), NewAnd,
6273                               ConstantInt::get(NewCI));
6274         }
6275       }
6276       
6277       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6278       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6279       // happens a LOT in code produced by the C front-end, for bitfield
6280       // access.
6281       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6282       if (Shift && !Shift->isShift())
6283         Shift = 0;
6284       
6285       ConstantInt *ShAmt;
6286       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6287       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6288       const Type *AndTy = AndCST->getType();          // Type of the and.
6289       
6290       // We can fold this as long as we can't shift unknown bits
6291       // into the mask.  This can only happen with signed shift
6292       // rights, as they sign-extend.
6293       if (ShAmt) {
6294         bool CanFold = Shift->isLogicalShift();
6295         if (!CanFold) {
6296           // To test for the bad case of the signed shr, see if any
6297           // of the bits shifted in could be tested after the mask.
6298           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6299           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6300           
6301           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6302           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6303                AndCST->getValue()) == 0)
6304             CanFold = true;
6305         }
6306         
6307         if (CanFold) {
6308           Constant *NewCst;
6309           if (Shift->getOpcode() == Instruction::Shl)
6310             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6311           else
6312             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6313           
6314           // Check to see if we are shifting out any of the bits being
6315           // compared.
6316           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6317             // If we shifted bits out, the fold is not going to work out.
6318             // As a special case, check to see if this means that the
6319             // result is always true or false now.
6320             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6321               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6322             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6323               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6324           } else {
6325             ICI.setOperand(1, NewCst);
6326             Constant *NewAndCST;
6327             if (Shift->getOpcode() == Instruction::Shl)
6328               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6329             else
6330               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6331             LHSI->setOperand(1, NewAndCST);
6332             LHSI->setOperand(0, Shift->getOperand(0));
6333             AddToWorkList(Shift); // Shift is dead.
6334             AddUsesToWorkList(ICI);
6335             return &ICI;
6336           }
6337         }
6338       }
6339       
6340       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6341       // preferable because it allows the C<<Y expression to be hoisted out
6342       // of a loop if Y is invariant and X is not.
6343       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6344           ICI.isEquality() && !Shift->isArithmeticShift() &&
6345           isa<Instruction>(Shift->getOperand(0))) {
6346         // Compute C << Y.
6347         Value *NS;
6348         if (Shift->getOpcode() == Instruction::LShr) {
6349           NS = BinaryOperator::CreateShl(AndCST, 
6350                                          Shift->getOperand(1), "tmp");
6351         } else {
6352           // Insert a logical shift.
6353           NS = BinaryOperator::CreateLShr(AndCST,
6354                                           Shift->getOperand(1), "tmp");
6355         }
6356         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6357         
6358         // Compute X & (C << Y).
6359         Instruction *NewAnd = 
6360           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6361         InsertNewInstBefore(NewAnd, ICI);
6362         
6363         ICI.setOperand(0, NewAnd);
6364         return &ICI;
6365       }
6366     }
6367     break;
6368     
6369   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6370     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6371     if (!ShAmt) break;
6372     
6373     uint32_t TypeBits = RHSV.getBitWidth();
6374     
6375     // Check that the shift amount is in range.  If not, don't perform
6376     // undefined shifts.  When the shift is visited it will be
6377     // simplified.
6378     if (ShAmt->uge(TypeBits))
6379       break;
6380     
6381     if (ICI.isEquality()) {
6382       // If we are comparing against bits always shifted out, the
6383       // comparison cannot succeed.
6384       Constant *Comp =
6385         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6386       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6387         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6388         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6389         return ReplaceInstUsesWith(ICI, Cst);
6390       }
6391       
6392       if (LHSI->hasOneUse()) {
6393         // Otherwise strength reduce the shift into an and.
6394         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6395         Constant *Mask =
6396           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6397         
6398         Instruction *AndI =
6399           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6400                                     Mask, LHSI->getName()+".mask");
6401         Value *And = InsertNewInstBefore(AndI, ICI);
6402         return new ICmpInst(ICI.getPredicate(), And,
6403                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6404       }
6405     }
6406     
6407     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6408     bool TrueIfSigned = false;
6409     if (LHSI->hasOneUse() &&
6410         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6411       // (X << 31) <s 0  --> (X&1) != 0
6412       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6413                                            (TypeBits-ShAmt->getZExtValue()-1));
6414       Instruction *AndI =
6415         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6416                                   Mask, LHSI->getName()+".mask");
6417       Value *And = InsertNewInstBefore(AndI, ICI);
6418       
6419       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6420                           And, Constant::getNullValue(And->getType()));
6421     }
6422     break;
6423   }
6424     
6425   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6426   case Instruction::AShr: {
6427     // Only handle equality comparisons of shift-by-constant.
6428     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6429     if (!ShAmt || !ICI.isEquality()) break;
6430
6431     // Check that the shift amount is in range.  If not, don't perform
6432     // undefined shifts.  When the shift is visited it will be
6433     // simplified.
6434     uint32_t TypeBits = RHSV.getBitWidth();
6435     if (ShAmt->uge(TypeBits))
6436       break;
6437     
6438     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6439       
6440     // If we are comparing against bits always shifted out, the
6441     // comparison cannot succeed.
6442     APInt Comp = RHSV << ShAmtVal;
6443     if (LHSI->getOpcode() == Instruction::LShr)
6444       Comp = Comp.lshr(ShAmtVal);
6445     else
6446       Comp = Comp.ashr(ShAmtVal);
6447     
6448     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6449       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6450       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6451       return ReplaceInstUsesWith(ICI, Cst);
6452     }
6453     
6454     // Otherwise, check to see if the bits shifted out are known to be zero.
6455     // If so, we can compare against the unshifted value:
6456     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6457     if (LHSI->hasOneUse() &&
6458         MaskedValueIsZero(LHSI->getOperand(0), 
6459                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6460       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6461                           ConstantExpr::getShl(RHS, ShAmt));
6462     }
6463       
6464     if (LHSI->hasOneUse()) {
6465       // Otherwise strength reduce the shift into an and.
6466       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6467       Constant *Mask = ConstantInt::get(Val);
6468       
6469       Instruction *AndI =
6470         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6471                                   Mask, LHSI->getName()+".mask");
6472       Value *And = InsertNewInstBefore(AndI, ICI);
6473       return new ICmpInst(ICI.getPredicate(), And,
6474                           ConstantExpr::getShl(RHS, ShAmt));
6475     }
6476     break;
6477   }
6478     
6479   case Instruction::SDiv:
6480   case Instruction::UDiv:
6481     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6482     // Fold this div into the comparison, producing a range check. 
6483     // Determine, based on the divide type, what the range is being 
6484     // checked.  If there is an overflow on the low or high side, remember 
6485     // it, otherwise compute the range [low, hi) bounding the new value.
6486     // See: InsertRangeTest above for the kinds of replacements possible.
6487     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6488       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6489                                           DivRHS))
6490         return R;
6491     break;
6492
6493   case Instruction::Add:
6494     // Fold: icmp pred (add, X, C1), C2
6495
6496     if (!ICI.isEquality()) {
6497       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6498       if (!LHSC) break;
6499       const APInt &LHSV = LHSC->getValue();
6500
6501       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6502                             .subtract(LHSV);
6503
6504       if (ICI.isSignedPredicate()) {
6505         if (CR.getLower().isSignBit()) {
6506           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6507                               ConstantInt::get(CR.getUpper()));
6508         } else if (CR.getUpper().isSignBit()) {
6509           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6510                               ConstantInt::get(CR.getLower()));
6511         }
6512       } else {
6513         if (CR.getLower().isMinValue()) {
6514           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6515                               ConstantInt::get(CR.getUpper()));
6516         } else if (CR.getUpper().isMinValue()) {
6517           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6518                               ConstantInt::get(CR.getLower()));
6519         }
6520       }
6521     }
6522     break;
6523   }
6524   
6525   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6526   if (ICI.isEquality()) {
6527     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6528     
6529     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6530     // the second operand is a constant, simplify a bit.
6531     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6532       switch (BO->getOpcode()) {
6533       case Instruction::SRem:
6534         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6535         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6536           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6537           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6538             Instruction *NewRem =
6539               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6540                                          BO->getName());
6541             InsertNewInstBefore(NewRem, ICI);
6542             return new ICmpInst(ICI.getPredicate(), NewRem, 
6543                                 Constant::getNullValue(BO->getType()));
6544           }
6545         }
6546         break;
6547       case Instruction::Add:
6548         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6549         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6550           if (BO->hasOneUse())
6551             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6552                                 Subtract(RHS, BOp1C));
6553         } else if (RHSV == 0) {
6554           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6555           // efficiently invertible, or if the add has just this one use.
6556           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6557           
6558           if (Value *NegVal = dyn_castNegVal(BOp1))
6559             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6560           else if (Value *NegVal = dyn_castNegVal(BOp0))
6561             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6562           else if (BO->hasOneUse()) {
6563             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6564             InsertNewInstBefore(Neg, ICI);
6565             Neg->takeName(BO);
6566             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6567           }
6568         }
6569         break;
6570       case Instruction::Xor:
6571         // For the xor case, we can xor two constants together, eliminating
6572         // the explicit xor.
6573         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6574           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6575                               ConstantExpr::getXor(RHS, BOC));
6576         
6577         // FALLTHROUGH
6578       case Instruction::Sub:
6579         // Replace (([sub|xor] A, B) != 0) with (A != B)
6580         if (RHSV == 0)
6581           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6582                               BO->getOperand(1));
6583         break;
6584         
6585       case Instruction::Or:
6586         // If bits are being or'd in that are not present in the constant we
6587         // are comparing against, then the comparison could never succeed!
6588         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6589           Constant *NotCI = ConstantExpr::getNot(RHS);
6590           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6591             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6592                                                              isICMP_NE));
6593         }
6594         break;
6595         
6596       case Instruction::And:
6597         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6598           // If bits are being compared against that are and'd out, then the
6599           // comparison can never succeed!
6600           if ((RHSV & ~BOC->getValue()) != 0)
6601             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6602                                                              isICMP_NE));
6603           
6604           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6605           if (RHS == BOC && RHSV.isPowerOf2())
6606             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6607                                 ICmpInst::ICMP_NE, LHSI,
6608                                 Constant::getNullValue(RHS->getType()));
6609           
6610           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6611           if (BOC->getValue().isSignBit()) {
6612             Value *X = BO->getOperand(0);
6613             Constant *Zero = Constant::getNullValue(X->getType());
6614             ICmpInst::Predicate pred = isICMP_NE ? 
6615               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6616             return new ICmpInst(pred, X, Zero);
6617           }
6618           
6619           // ((X & ~7) == 0) --> X < 8
6620           if (RHSV == 0 && isHighOnes(BOC)) {
6621             Value *X = BO->getOperand(0);
6622             Constant *NegX = ConstantExpr::getNeg(BOC);
6623             ICmpInst::Predicate pred = isICMP_NE ? 
6624               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6625             return new ICmpInst(pred, X, NegX);
6626           }
6627         }
6628       default: break;
6629       }
6630     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6631       // Handle icmp {eq|ne} <intrinsic>, intcst.
6632       if (II->getIntrinsicID() == Intrinsic::bswap) {
6633         AddToWorkList(II);
6634         ICI.setOperand(0, II->getOperand(1));
6635         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6636         return &ICI;
6637       }
6638     }
6639   } else {  // Not a ICMP_EQ/ICMP_NE
6640             // If the LHS is a cast from an integral value of the same size, 
6641             // then since we know the RHS is a constant, try to simlify.
6642     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6643       Value *CastOp = Cast->getOperand(0);
6644       const Type *SrcTy = CastOp->getType();
6645       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6646       if (SrcTy->isInteger() && 
6647           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6648         // If this is an unsigned comparison, try to make the comparison use
6649         // smaller constant values.
6650         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6651           // X u< 128 => X s> -1
6652           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6653                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6654         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6655                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6656           // X u> 127 => X s< 0
6657           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6658                               Constant::getNullValue(SrcTy));
6659         }
6660       }
6661     }
6662   }
6663   return 0;
6664 }
6665
6666 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6667 /// We only handle extending casts so far.
6668 ///
6669 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6670   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6671   Value *LHSCIOp        = LHSCI->getOperand(0);
6672   const Type *SrcTy     = LHSCIOp->getType();
6673   const Type *DestTy    = LHSCI->getType();
6674   Value *RHSCIOp;
6675
6676   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6677   // integer type is the same size as the pointer type.
6678   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6679       getTargetData().getPointerSizeInBits() == 
6680          cast<IntegerType>(DestTy)->getBitWidth()) {
6681     Value *RHSOp = 0;
6682     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6683       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6684     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6685       RHSOp = RHSC->getOperand(0);
6686       // If the pointer types don't match, insert a bitcast.
6687       if (LHSCIOp->getType() != RHSOp->getType())
6688         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6689     }
6690
6691     if (RHSOp)
6692       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6693   }
6694   
6695   // The code below only handles extension cast instructions, so far.
6696   // Enforce this.
6697   if (LHSCI->getOpcode() != Instruction::ZExt &&
6698       LHSCI->getOpcode() != Instruction::SExt)
6699     return 0;
6700
6701   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6702   bool isSignedCmp = ICI.isSignedPredicate();
6703
6704   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6705     // Not an extension from the same type?
6706     RHSCIOp = CI->getOperand(0);
6707     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6708       return 0;
6709     
6710     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6711     // and the other is a zext), then we can't handle this.
6712     if (CI->getOpcode() != LHSCI->getOpcode())
6713       return 0;
6714
6715     // Deal with equality cases early.
6716     if (ICI.isEquality())
6717       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6718
6719     // A signed comparison of sign extended values simplifies into a
6720     // signed comparison.
6721     if (isSignedCmp && isSignedExt)
6722       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6723
6724     // The other three cases all fold into an unsigned comparison.
6725     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6726   }
6727
6728   // If we aren't dealing with a constant on the RHS, exit early
6729   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6730   if (!CI)
6731     return 0;
6732
6733   // Compute the constant that would happen if we truncated to SrcTy then
6734   // reextended to DestTy.
6735   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6736   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6737
6738   // If the re-extended constant didn't change...
6739   if (Res2 == CI) {
6740     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6741     // For example, we might have:
6742     //    %A = sext short %X to uint
6743     //    %B = icmp ugt uint %A, 1330
6744     // It is incorrect to transform this into 
6745     //    %B = icmp ugt short %X, 1330 
6746     // because %A may have negative value. 
6747     //
6748     // However, we allow this when the compare is EQ/NE, because they are
6749     // signless.
6750     if (isSignedExt == isSignedCmp || ICI.isEquality())
6751       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6752     return 0;
6753   }
6754
6755   // The re-extended constant changed so the constant cannot be represented 
6756   // in the shorter type. Consequently, we cannot emit a simple comparison.
6757
6758   // First, handle some easy cases. We know the result cannot be equal at this
6759   // point so handle the ICI.isEquality() cases
6760   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6761     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6762   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6763     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6764
6765   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6766   // should have been folded away previously and not enter in here.
6767   Value *Result;
6768   if (isSignedCmp) {
6769     // We're performing a signed comparison.
6770     if (cast<ConstantInt>(CI)->getValue().isNegative())
6771       Result = ConstantInt::getFalse();          // X < (small) --> false
6772     else
6773       Result = ConstantInt::getTrue();           // X < (large) --> true
6774   } else {
6775     // We're performing an unsigned comparison.
6776     if (isSignedExt) {
6777       // We're performing an unsigned comp with a sign extended value.
6778       // This is true if the input is >= 0. [aka >s -1]
6779       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6780       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6781                                    NegOne, ICI.getName()), ICI);
6782     } else {
6783       // Unsigned extend & unsigned compare -> always true.
6784       Result = ConstantInt::getTrue();
6785     }
6786   }
6787
6788   // Finally, return the value computed.
6789   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6790       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6791     return ReplaceInstUsesWith(ICI, Result);
6792
6793   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6794           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6795          "ICmp should be folded!");
6796   if (Constant *CI = dyn_cast<Constant>(Result))
6797     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6798   return BinaryOperator::CreateNot(Result);
6799 }
6800
6801 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6802   return commonShiftTransforms(I);
6803 }
6804
6805 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6806   return commonShiftTransforms(I);
6807 }
6808
6809 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6810   if (Instruction *R = commonShiftTransforms(I))
6811     return R;
6812   
6813   Value *Op0 = I.getOperand(0);
6814   
6815   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6816   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6817     if (CSI->isAllOnesValue())
6818       return ReplaceInstUsesWith(I, CSI);
6819   
6820   // See if we can turn a signed shr into an unsigned shr.
6821   if (!isa<VectorType>(I.getType()) &&
6822       MaskedValueIsZero(Op0,
6823                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6824     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6825   
6826   return 0;
6827 }
6828
6829 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6830   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6831   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6832
6833   // shl X, 0 == X and shr X, 0 == X
6834   // shl 0, X == 0 and shr 0, X == 0
6835   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6836       Op0 == Constant::getNullValue(Op0->getType()))
6837     return ReplaceInstUsesWith(I, Op0);
6838   
6839   if (isa<UndefValue>(Op0)) {            
6840     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6841       return ReplaceInstUsesWith(I, Op0);
6842     else                                    // undef << X -> 0, undef >>u X -> 0
6843       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6844   }
6845   if (isa<UndefValue>(Op1)) {
6846     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6847       return ReplaceInstUsesWith(I, Op0);          
6848     else                                     // X << undef, X >>u undef -> 0
6849       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6850   }
6851
6852   // Try to fold constant and into select arguments.
6853   if (isa<Constant>(Op0))
6854     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6855       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6856         return R;
6857
6858   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6859     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6860       return Res;
6861   return 0;
6862 }
6863
6864 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6865                                                BinaryOperator &I) {
6866   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6867
6868   // See if we can simplify any instructions used by the instruction whose sole 
6869   // purpose is to compute bits we don't care about.
6870   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6871   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6872   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6873                            KnownZero, KnownOne))
6874     return &I;
6875   
6876   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6877   // of a signed value.
6878   //
6879   if (Op1->uge(TypeBits)) {
6880     if (I.getOpcode() != Instruction::AShr)
6881       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6882     else {
6883       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6884       return &I;
6885     }
6886   }
6887   
6888   // ((X*C1) << C2) == (X * (C1 << C2))
6889   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6890     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6891       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6892         return BinaryOperator::CreateMul(BO->getOperand(0),
6893                                          ConstantExpr::getShl(BOOp, Op1));
6894   
6895   // Try to fold constant and into select arguments.
6896   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6897     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6898       return R;
6899   if (isa<PHINode>(Op0))
6900     if (Instruction *NV = FoldOpIntoPhi(I))
6901       return NV;
6902   
6903   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6904   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6905     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6906     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6907     // place.  Don't try to do this transformation in this case.  Also, we
6908     // require that the input operand is a shift-by-constant so that we have
6909     // confidence that the shifts will get folded together.  We could do this
6910     // xform in more cases, but it is unlikely to be profitable.
6911     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6912         isa<ConstantInt>(TrOp->getOperand(1))) {
6913       // Okay, we'll do this xform.  Make the shift of shift.
6914       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6915       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6916                                                 I.getName());
6917       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6918
6919       // For logical shifts, the truncation has the effect of making the high
6920       // part of the register be zeros.  Emulate this by inserting an AND to
6921       // clear the top bits as needed.  This 'and' will usually be zapped by
6922       // other xforms later if dead.
6923       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6924       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6925       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6926       
6927       // The mask we constructed says what the trunc would do if occurring
6928       // between the shifts.  We want to know the effect *after* the second
6929       // shift.  We know that it is a logical shift by a constant, so adjust the
6930       // mask as appropriate.
6931       if (I.getOpcode() == Instruction::Shl)
6932         MaskV <<= Op1->getZExtValue();
6933       else {
6934         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6935         MaskV = MaskV.lshr(Op1->getZExtValue());
6936       }
6937
6938       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6939                                                    TI->getName());
6940       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6941
6942       // Return the value truncated to the interesting size.
6943       return new TruncInst(And, I.getType());
6944     }
6945   }
6946   
6947   if (Op0->hasOneUse()) {
6948     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6949       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6950       Value *V1, *V2;
6951       ConstantInt *CC;
6952       switch (Op0BO->getOpcode()) {
6953         default: break;
6954         case Instruction::Add:
6955         case Instruction::And:
6956         case Instruction::Or:
6957         case Instruction::Xor: {
6958           // These operators commute.
6959           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6960           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6961               match(Op0BO->getOperand(1),
6962                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6963             Instruction *YS = BinaryOperator::CreateShl(
6964                                             Op0BO->getOperand(0), Op1,
6965                                             Op0BO->getName());
6966             InsertNewInstBefore(YS, I); // (Y << C)
6967             Instruction *X = 
6968               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6969                                      Op0BO->getOperand(1)->getName());
6970             InsertNewInstBefore(X, I);  // (X + (Y << C))
6971             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6972             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6973                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6974           }
6975           
6976           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6977           Value *Op0BOOp1 = Op0BO->getOperand(1);
6978           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6979               match(Op0BOOp1, 
6980                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6981               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6982               V2 == Op1) {
6983             Instruction *YS = BinaryOperator::CreateShl(
6984                                                      Op0BO->getOperand(0), Op1,
6985                                                      Op0BO->getName());
6986             InsertNewInstBefore(YS, I); // (Y << C)
6987             Instruction *XM =
6988               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6989                                         V1->getName()+".mask");
6990             InsertNewInstBefore(XM, I); // X & (CC << C)
6991             
6992             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6993           }
6994         }
6995           
6996         // FALL THROUGH.
6997         case Instruction::Sub: {
6998           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6999           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7000               match(Op0BO->getOperand(0),
7001                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7002             Instruction *YS = BinaryOperator::CreateShl(
7003                                                      Op0BO->getOperand(1), Op1,
7004                                                      Op0BO->getName());
7005             InsertNewInstBefore(YS, I); // (Y << C)
7006             Instruction *X =
7007               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7008                                      Op0BO->getOperand(0)->getName());
7009             InsertNewInstBefore(X, I);  // (X + (Y << C))
7010             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7011             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7012                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7013           }
7014           
7015           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7016           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7017               match(Op0BO->getOperand(0),
7018                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7019                           m_ConstantInt(CC))) && V2 == Op1 &&
7020               cast<BinaryOperator>(Op0BO->getOperand(0))
7021                   ->getOperand(0)->hasOneUse()) {
7022             Instruction *YS = BinaryOperator::CreateShl(
7023                                                      Op0BO->getOperand(1), Op1,
7024                                                      Op0BO->getName());
7025             InsertNewInstBefore(YS, I); // (Y << C)
7026             Instruction *XM =
7027               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7028                                         V1->getName()+".mask");
7029             InsertNewInstBefore(XM, I); // X & (CC << C)
7030             
7031             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7032           }
7033           
7034           break;
7035         }
7036       }
7037       
7038       
7039       // If the operand is an bitwise operator with a constant RHS, and the
7040       // shift is the only use, we can pull it out of the shift.
7041       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7042         bool isValid = true;     // Valid only for And, Or, Xor
7043         bool highBitSet = false; // Transform if high bit of constant set?
7044         
7045         switch (Op0BO->getOpcode()) {
7046           default: isValid = false; break;   // Do not perform transform!
7047           case Instruction::Add:
7048             isValid = isLeftShift;
7049             break;
7050           case Instruction::Or:
7051           case Instruction::Xor:
7052             highBitSet = false;
7053             break;
7054           case Instruction::And:
7055             highBitSet = true;
7056             break;
7057         }
7058         
7059         // If this is a signed shift right, and the high bit is modified
7060         // by the logical operation, do not perform the transformation.
7061         // The highBitSet boolean indicates the value of the high bit of
7062         // the constant which would cause it to be modified for this
7063         // operation.
7064         //
7065         if (isValid && I.getOpcode() == Instruction::AShr)
7066           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7067         
7068         if (isValid) {
7069           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7070           
7071           Instruction *NewShift =
7072             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7073           InsertNewInstBefore(NewShift, I);
7074           NewShift->takeName(Op0BO);
7075           
7076           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7077                                         NewRHS);
7078         }
7079       }
7080     }
7081   }
7082   
7083   // Find out if this is a shift of a shift by a constant.
7084   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7085   if (ShiftOp && !ShiftOp->isShift())
7086     ShiftOp = 0;
7087   
7088   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7089     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7090     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7091     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7092     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7093     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7094     Value *X = ShiftOp->getOperand(0);
7095     
7096     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7097     if (AmtSum > TypeBits)
7098       AmtSum = TypeBits;
7099     
7100     const IntegerType *Ty = cast<IntegerType>(I.getType());
7101     
7102     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7103     if (I.getOpcode() == ShiftOp->getOpcode()) {
7104       return BinaryOperator::Create(I.getOpcode(), X,
7105                                     ConstantInt::get(Ty, AmtSum));
7106     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7107                I.getOpcode() == Instruction::AShr) {
7108       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7109       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7110     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7111                I.getOpcode() == Instruction::LShr) {
7112       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7113       Instruction *Shift =
7114         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7115       InsertNewInstBefore(Shift, I);
7116
7117       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7118       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7119     }
7120     
7121     // Okay, if we get here, one shift must be left, and the other shift must be
7122     // right.  See if the amounts are equal.
7123     if (ShiftAmt1 == ShiftAmt2) {
7124       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7125       if (I.getOpcode() == Instruction::Shl) {
7126         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7127         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7128       }
7129       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7130       if (I.getOpcode() == Instruction::LShr) {
7131         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7132         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7133       }
7134       // We can simplify ((X << C) >>s C) into a trunc + sext.
7135       // NOTE: we could do this for any C, but that would make 'unusual' integer
7136       // types.  For now, just stick to ones well-supported by the code
7137       // generators.
7138       const Type *SExtType = 0;
7139       switch (Ty->getBitWidth() - ShiftAmt1) {
7140       case 1  :
7141       case 8  :
7142       case 16 :
7143       case 32 :
7144       case 64 :
7145       case 128:
7146         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7147         break;
7148       default: break;
7149       }
7150       if (SExtType) {
7151         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7152         InsertNewInstBefore(NewTrunc, I);
7153         return new SExtInst(NewTrunc, Ty);
7154       }
7155       // Otherwise, we can't handle it yet.
7156     } else if (ShiftAmt1 < ShiftAmt2) {
7157       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7158       
7159       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7160       if (I.getOpcode() == Instruction::Shl) {
7161         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7162                ShiftOp->getOpcode() == Instruction::AShr);
7163         Instruction *Shift =
7164           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7165         InsertNewInstBefore(Shift, I);
7166         
7167         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7168         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7169       }
7170       
7171       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7172       if (I.getOpcode() == Instruction::LShr) {
7173         assert(ShiftOp->getOpcode() == Instruction::Shl);
7174         Instruction *Shift =
7175           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7176         InsertNewInstBefore(Shift, I);
7177         
7178         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7179         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7180       }
7181       
7182       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7183     } else {
7184       assert(ShiftAmt2 < ShiftAmt1);
7185       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7186
7187       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7188       if (I.getOpcode() == Instruction::Shl) {
7189         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7190                ShiftOp->getOpcode() == Instruction::AShr);
7191         Instruction *Shift =
7192           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7193                                  ConstantInt::get(Ty, ShiftDiff));
7194         InsertNewInstBefore(Shift, I);
7195         
7196         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7197         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7198       }
7199       
7200       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7201       if (I.getOpcode() == Instruction::LShr) {
7202         assert(ShiftOp->getOpcode() == Instruction::Shl);
7203         Instruction *Shift =
7204           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7205         InsertNewInstBefore(Shift, I);
7206         
7207         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7208         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7209       }
7210       
7211       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7212     }
7213   }
7214   return 0;
7215 }
7216
7217
7218 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7219 /// expression.  If so, decompose it, returning some value X, such that Val is
7220 /// X*Scale+Offset.
7221 ///
7222 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7223                                         int &Offset) {
7224   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7225   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7226     Offset = CI->getZExtValue();
7227     Scale  = 0;
7228     return ConstantInt::get(Type::Int32Ty, 0);
7229   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7230     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7231       if (I->getOpcode() == Instruction::Shl) {
7232         // This is a value scaled by '1 << the shift amt'.
7233         Scale = 1U << RHS->getZExtValue();
7234         Offset = 0;
7235         return I->getOperand(0);
7236       } else if (I->getOpcode() == Instruction::Mul) {
7237         // This value is scaled by 'RHS'.
7238         Scale = RHS->getZExtValue();
7239         Offset = 0;
7240         return I->getOperand(0);
7241       } else if (I->getOpcode() == Instruction::Add) {
7242         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7243         // where C1 is divisible by C2.
7244         unsigned SubScale;
7245         Value *SubVal = 
7246           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7247         Offset += RHS->getZExtValue();
7248         Scale = SubScale;
7249         return SubVal;
7250       }
7251     }
7252   }
7253
7254   // Otherwise, we can't look past this.
7255   Scale = 1;
7256   Offset = 0;
7257   return Val;
7258 }
7259
7260
7261 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7262 /// try to eliminate the cast by moving the type information into the alloc.
7263 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7264                                                    AllocationInst &AI) {
7265   const PointerType *PTy = cast<PointerType>(CI.getType());
7266   
7267   // Remove any uses of AI that are dead.
7268   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7269   
7270   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7271     Instruction *User = cast<Instruction>(*UI++);
7272     if (isInstructionTriviallyDead(User)) {
7273       while (UI != E && *UI == User)
7274         ++UI; // If this instruction uses AI more than once, don't break UI.
7275       
7276       ++NumDeadInst;
7277       DOUT << "IC: DCE: " << *User;
7278       EraseInstFromFunction(*User);
7279     }
7280   }
7281   
7282   // Get the type really allocated and the type casted to.
7283   const Type *AllocElTy = AI.getAllocatedType();
7284   const Type *CastElTy = PTy->getElementType();
7285   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7286
7287   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7288   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7289   if (CastElTyAlign < AllocElTyAlign) return 0;
7290
7291   // If the allocation has multiple uses, only promote it if we are strictly
7292   // increasing the alignment of the resultant allocation.  If we keep it the
7293   // same, we open the door to infinite loops of various kinds.
7294   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7295
7296   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7297   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7298   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7299
7300   // See if we can satisfy the modulus by pulling a scale out of the array
7301   // size argument.
7302   unsigned ArraySizeScale;
7303   int ArrayOffset;
7304   Value *NumElements = // See if the array size is a decomposable linear expr.
7305     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7306  
7307   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7308   // do the xform.
7309   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7310       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7311
7312   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7313   Value *Amt = 0;
7314   if (Scale == 1) {
7315     Amt = NumElements;
7316   } else {
7317     // If the allocation size is constant, form a constant mul expression
7318     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7319     if (isa<ConstantInt>(NumElements))
7320       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7321     // otherwise multiply the amount and the number of elements
7322     else if (Scale != 1) {
7323       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7324       Amt = InsertNewInstBefore(Tmp, AI);
7325     }
7326   }
7327   
7328   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7329     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7330     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7331     Amt = InsertNewInstBefore(Tmp, AI);
7332   }
7333   
7334   AllocationInst *New;
7335   if (isa<MallocInst>(AI))
7336     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7337   else
7338     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7339   InsertNewInstBefore(New, AI);
7340   New->takeName(&AI);
7341   
7342   // If the allocation has multiple uses, insert a cast and change all things
7343   // that used it to use the new cast.  This will also hack on CI, but it will
7344   // die soon.
7345   if (!AI.hasOneUse()) {
7346     AddUsesToWorkList(AI);
7347     // New is the allocation instruction, pointer typed. AI is the original
7348     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7349     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7350     InsertNewInstBefore(NewCast, AI);
7351     AI.replaceAllUsesWith(NewCast);
7352   }
7353   return ReplaceInstUsesWith(CI, New);
7354 }
7355
7356 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7357 /// and return it as type Ty without inserting any new casts and without
7358 /// changing the computed value.  This is used by code that tries to decide
7359 /// whether promoting or shrinking integer operations to wider or smaller types
7360 /// will allow us to eliminate a truncate or extend.
7361 ///
7362 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7363 /// extension operation if Ty is larger.
7364 ///
7365 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7366 /// should return true if trunc(V) can be computed by computing V in the smaller
7367 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7368 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7369 /// efficiently truncated.
7370 ///
7371 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7372 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7373 /// the final result.
7374 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7375                                               unsigned CastOpc,
7376                                               int &NumCastsRemoved) {
7377   // We can always evaluate constants in another type.
7378   if (isa<ConstantInt>(V))
7379     return true;
7380   
7381   Instruction *I = dyn_cast<Instruction>(V);
7382   if (!I) return false;
7383   
7384   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7385   
7386   // If this is an extension or truncate, we can often eliminate it.
7387   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7388     // If this is a cast from the destination type, we can trivially eliminate
7389     // it, and this will remove a cast overall.
7390     if (I->getOperand(0)->getType() == Ty) {
7391       // If the first operand is itself a cast, and is eliminable, do not count
7392       // this as an eliminable cast.  We would prefer to eliminate those two
7393       // casts first.
7394       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7395         ++NumCastsRemoved;
7396       return true;
7397     }
7398   }
7399
7400   // We can't extend or shrink something that has multiple uses: doing so would
7401   // require duplicating the instruction in general, which isn't profitable.
7402   if (!I->hasOneUse()) return false;
7403
7404   switch (I->getOpcode()) {
7405   case Instruction::Add:
7406   case Instruction::Sub:
7407   case Instruction::Mul:
7408   case Instruction::And:
7409   case Instruction::Or:
7410   case Instruction::Xor:
7411     // These operators can all arbitrarily be extended or truncated.
7412     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7413                                       NumCastsRemoved) &&
7414            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7415                                       NumCastsRemoved);
7416
7417   case Instruction::Shl:
7418     // If we are truncating the result of this SHL, and if it's a shift of a
7419     // constant amount, we can always perform a SHL in a smaller type.
7420     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7421       uint32_t BitWidth = Ty->getBitWidth();
7422       if (BitWidth < OrigTy->getBitWidth() && 
7423           CI->getLimitedValue(BitWidth) < BitWidth)
7424         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7425                                           NumCastsRemoved);
7426     }
7427     break;
7428   case Instruction::LShr:
7429     // If this is a truncate of a logical shr, we can truncate it to a smaller
7430     // lshr iff we know that the bits we would otherwise be shifting in are
7431     // already zeros.
7432     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7433       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7434       uint32_t BitWidth = Ty->getBitWidth();
7435       if (BitWidth < OrigBitWidth &&
7436           MaskedValueIsZero(I->getOperand(0),
7437             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7438           CI->getLimitedValue(BitWidth) < BitWidth) {
7439         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7440                                           NumCastsRemoved);
7441       }
7442     }
7443     break;
7444   case Instruction::ZExt:
7445   case Instruction::SExt:
7446   case Instruction::Trunc:
7447     // If this is the same kind of case as our original (e.g. zext+zext), we
7448     // can safely replace it.  Note that replacing it does not reduce the number
7449     // of casts in the input.
7450     if (I->getOpcode() == CastOpc)
7451       return true;
7452     break;
7453   case Instruction::Select: {
7454     SelectInst *SI = cast<SelectInst>(I);
7455     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7456                                       NumCastsRemoved) &&
7457            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7458                                       NumCastsRemoved);
7459   }
7460   case Instruction::PHI: {
7461     // We can change a phi if we can change all operands.
7462     PHINode *PN = cast<PHINode>(I);
7463     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7464       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7465                                       NumCastsRemoved))
7466         return false;
7467     return true;
7468   }
7469   default:
7470     // TODO: Can handle more cases here.
7471     break;
7472   }
7473   
7474   return false;
7475 }
7476
7477 /// EvaluateInDifferentType - Given an expression that 
7478 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7479 /// evaluate the expression.
7480 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7481                                              bool isSigned) {
7482   if (Constant *C = dyn_cast<Constant>(V))
7483     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7484
7485   // Otherwise, it must be an instruction.
7486   Instruction *I = cast<Instruction>(V);
7487   Instruction *Res = 0;
7488   switch (I->getOpcode()) {
7489   case Instruction::Add:
7490   case Instruction::Sub:
7491   case Instruction::Mul:
7492   case Instruction::And:
7493   case Instruction::Or:
7494   case Instruction::Xor:
7495   case Instruction::AShr:
7496   case Instruction::LShr:
7497   case Instruction::Shl: {
7498     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7499     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7500     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7501                                  LHS, RHS);
7502     break;
7503   }    
7504   case Instruction::Trunc:
7505   case Instruction::ZExt:
7506   case Instruction::SExt:
7507     // If the source type of the cast is the type we're trying for then we can
7508     // just return the source.  There's no need to insert it because it is not
7509     // new.
7510     if (I->getOperand(0)->getType() == Ty)
7511       return I->getOperand(0);
7512     
7513     // Otherwise, must be the same type of cast, so just reinsert a new one.
7514     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7515                            Ty);
7516     break;
7517   case Instruction::Select: {
7518     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7519     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7520     Res = SelectInst::Create(I->getOperand(0), True, False);
7521     break;
7522   }
7523   case Instruction::PHI: {
7524     PHINode *OPN = cast<PHINode>(I);
7525     PHINode *NPN = PHINode::Create(Ty);
7526     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7527       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7528       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7529     }
7530     Res = NPN;
7531     break;
7532   }
7533   default: 
7534     // TODO: Can handle more cases here.
7535     assert(0 && "Unreachable!");
7536     break;
7537   }
7538   
7539   Res->takeName(I);
7540   return InsertNewInstBefore(Res, *I);
7541 }
7542
7543 /// @brief Implement the transforms common to all CastInst visitors.
7544 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7545   Value *Src = CI.getOperand(0);
7546
7547   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7548   // eliminate it now.
7549   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7550     if (Instruction::CastOps opc = 
7551         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7552       // The first cast (CSrc) is eliminable so we need to fix up or replace
7553       // the second cast (CI). CSrc will then have a good chance of being dead.
7554       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7555     }
7556   }
7557
7558   // If we are casting a select then fold the cast into the select
7559   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7560     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7561       return NV;
7562
7563   // If we are casting a PHI then fold the cast into the PHI
7564   if (isa<PHINode>(Src))
7565     if (Instruction *NV = FoldOpIntoPhi(CI))
7566       return NV;
7567   
7568   return 0;
7569 }
7570
7571 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7572 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7573   Value *Src = CI.getOperand(0);
7574   
7575   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7576     // If casting the result of a getelementptr instruction with no offset, turn
7577     // this into a cast of the original pointer!
7578     if (GEP->hasAllZeroIndices()) {
7579       // Changing the cast operand is usually not a good idea but it is safe
7580       // here because the pointer operand is being replaced with another 
7581       // pointer operand so the opcode doesn't need to change.
7582       AddToWorkList(GEP);
7583       CI.setOperand(0, GEP->getOperand(0));
7584       return &CI;
7585     }
7586     
7587     // If the GEP has a single use, and the base pointer is a bitcast, and the
7588     // GEP computes a constant offset, see if we can convert these three
7589     // instructions into fewer.  This typically happens with unions and other
7590     // non-type-safe code.
7591     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7592       if (GEP->hasAllConstantIndices()) {
7593         // We are guaranteed to get a constant from EmitGEPOffset.
7594         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7595         int64_t Offset = OffsetV->getSExtValue();
7596         
7597         // Get the base pointer input of the bitcast, and the type it points to.
7598         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7599         const Type *GEPIdxTy =
7600           cast<PointerType>(OrigBase->getType())->getElementType();
7601         if (GEPIdxTy->isSized()) {
7602           SmallVector<Value*, 8> NewIndices;
7603           
7604           // Start with the index over the outer type.  Note that the type size
7605           // might be zero (even if the offset isn't zero) if the indexed type
7606           // is something like [0 x {int, int}]
7607           const Type *IntPtrTy = TD->getIntPtrType();
7608           int64_t FirstIdx = 0;
7609           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7610             FirstIdx = Offset/TySize;
7611             Offset %= TySize;
7612           
7613             // Handle silly modulus not returning values values [0..TySize).
7614             if (Offset < 0) {
7615               --FirstIdx;
7616               Offset += TySize;
7617               assert(Offset >= 0);
7618             }
7619             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7620           }
7621           
7622           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7623
7624           // Index into the types.  If we fail, set OrigBase to null.
7625           while (Offset) {
7626             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7627               const StructLayout *SL = TD->getStructLayout(STy);
7628               if (Offset < (int64_t)SL->getSizeInBytes()) {
7629                 unsigned Elt = SL->getElementContainingOffset(Offset);
7630                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7631               
7632                 Offset -= SL->getElementOffset(Elt);
7633                 GEPIdxTy = STy->getElementType(Elt);
7634               } else {
7635                 // Otherwise, we can't index into this, bail out.
7636                 Offset = 0;
7637                 OrigBase = 0;
7638               }
7639             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7640               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7641               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7642                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7643                 Offset %= EltSize;
7644               } else {
7645                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7646               }
7647               GEPIdxTy = STy->getElementType();
7648             } else {
7649               // Otherwise, we can't index into this, bail out.
7650               Offset = 0;
7651               OrigBase = 0;
7652             }
7653           }
7654           if (OrigBase) {
7655             // If we were able to index down into an element, create the GEP
7656             // and bitcast the result.  This eliminates one bitcast, potentially
7657             // two.
7658             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7659                                                           NewIndices.begin(),
7660                                                           NewIndices.end(), "");
7661             InsertNewInstBefore(NGEP, CI);
7662             NGEP->takeName(GEP);
7663             
7664             if (isa<BitCastInst>(CI))
7665               return new BitCastInst(NGEP, CI.getType());
7666             assert(isa<PtrToIntInst>(CI));
7667             return new PtrToIntInst(NGEP, CI.getType());
7668           }
7669         }
7670       }      
7671     }
7672   }
7673     
7674   return commonCastTransforms(CI);
7675 }
7676
7677
7678
7679 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7680 /// integer types. This function implements the common transforms for all those
7681 /// cases.
7682 /// @brief Implement the transforms common to CastInst with integer operands
7683 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7684   if (Instruction *Result = commonCastTransforms(CI))
7685     return Result;
7686
7687   Value *Src = CI.getOperand(0);
7688   const Type *SrcTy = Src->getType();
7689   const Type *DestTy = CI.getType();
7690   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7691   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7692
7693   // See if we can simplify any instructions used by the LHS whose sole 
7694   // purpose is to compute bits we don't care about.
7695   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7696   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7697                            KnownZero, KnownOne))
7698     return &CI;
7699
7700   // If the source isn't an instruction or has more than one use then we
7701   // can't do anything more. 
7702   Instruction *SrcI = dyn_cast<Instruction>(Src);
7703   if (!SrcI || !Src->hasOneUse())
7704     return 0;
7705
7706   // Attempt to propagate the cast into the instruction for int->int casts.
7707   int NumCastsRemoved = 0;
7708   if (!isa<BitCastInst>(CI) &&
7709       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7710                                  CI.getOpcode(), NumCastsRemoved)) {
7711     // If this cast is a truncate, evaluting in a different type always
7712     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7713     // we need to do an AND to maintain the clear top-part of the computation,
7714     // so we require that the input have eliminated at least one cast.  If this
7715     // is a sign extension, we insert two new casts (to do the extension) so we
7716     // require that two casts have been eliminated.
7717     bool DoXForm;
7718     switch (CI.getOpcode()) {
7719     default:
7720       // All the others use floating point so we shouldn't actually 
7721       // get here because of the check above.
7722       assert(0 && "Unknown cast type");
7723     case Instruction::Trunc:
7724       DoXForm = true;
7725       break;
7726     case Instruction::ZExt:
7727       DoXForm = NumCastsRemoved >= 1;
7728       break;
7729     case Instruction::SExt:
7730       DoXForm = NumCastsRemoved >= 2;
7731       break;
7732     }
7733     
7734     if (DoXForm) {
7735       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7736                                            CI.getOpcode() == Instruction::SExt);
7737       assert(Res->getType() == DestTy);
7738       switch (CI.getOpcode()) {
7739       default: assert(0 && "Unknown cast type!");
7740       case Instruction::Trunc:
7741       case Instruction::BitCast:
7742         // Just replace this cast with the result.
7743         return ReplaceInstUsesWith(CI, Res);
7744       case Instruction::ZExt: {
7745         // We need to emit an AND to clear the high bits.
7746         assert(SrcBitSize < DestBitSize && "Not a zext?");
7747         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7748                                                             SrcBitSize));
7749         return BinaryOperator::CreateAnd(Res, C);
7750       }
7751       case Instruction::SExt:
7752         // We need to emit a cast to truncate, then a cast to sext.
7753         return CastInst::Create(Instruction::SExt,
7754             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7755                              CI), DestTy);
7756       }
7757     }
7758   }
7759   
7760   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7761   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7762
7763   switch (SrcI->getOpcode()) {
7764   case Instruction::Add:
7765   case Instruction::Mul:
7766   case Instruction::And:
7767   case Instruction::Or:
7768   case Instruction::Xor:
7769     // If we are discarding information, rewrite.
7770     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7771       // Don't insert two casts if they cannot be eliminated.  We allow 
7772       // two casts to be inserted if the sizes are the same.  This could 
7773       // only be converting signedness, which is a noop.
7774       if (DestBitSize == SrcBitSize || 
7775           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7776           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7777         Instruction::CastOps opcode = CI.getOpcode();
7778         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7779         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7780         return BinaryOperator::Create(
7781             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7782       }
7783     }
7784
7785     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7786     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7787         SrcI->getOpcode() == Instruction::Xor &&
7788         Op1 == ConstantInt::getTrue() &&
7789         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7790       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7791       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7792     }
7793     break;
7794   case Instruction::SDiv:
7795   case Instruction::UDiv:
7796   case Instruction::SRem:
7797   case Instruction::URem:
7798     // If we are just changing the sign, rewrite.
7799     if (DestBitSize == SrcBitSize) {
7800       // Don't insert two casts if they cannot be eliminated.  We allow 
7801       // two casts to be inserted if the sizes are the same.  This could 
7802       // only be converting signedness, which is a noop.
7803       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7804           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7805         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7806                                               Op0, DestTy, SrcI);
7807         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7808                                               Op1, DestTy, SrcI);
7809         return BinaryOperator::Create(
7810           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7811       }
7812     }
7813     break;
7814
7815   case Instruction::Shl:
7816     // Allow changing the sign of the source operand.  Do not allow 
7817     // changing the size of the shift, UNLESS the shift amount is a 
7818     // constant.  We must not change variable sized shifts to a smaller 
7819     // size, because it is undefined to shift more bits out than exist 
7820     // in the value.
7821     if (DestBitSize == SrcBitSize ||
7822         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7823       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7824           Instruction::BitCast : Instruction::Trunc);
7825       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7826       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7827       return BinaryOperator::CreateShl(Op0c, Op1c);
7828     }
7829     break;
7830   case Instruction::AShr:
7831     // If this is a signed shr, and if all bits shifted in are about to be
7832     // truncated off, turn it into an unsigned shr to allow greater
7833     // simplifications.
7834     if (DestBitSize < SrcBitSize &&
7835         isa<ConstantInt>(Op1)) {
7836       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7837       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7838         // Insert the new logical shift right.
7839         return BinaryOperator::CreateLShr(Op0, Op1);
7840       }
7841     }
7842     break;
7843   }
7844   return 0;
7845 }
7846
7847 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7848   if (Instruction *Result = commonIntCastTransforms(CI))
7849     return Result;
7850   
7851   Value *Src = CI.getOperand(0);
7852   const Type *Ty = CI.getType();
7853   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7854   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7855   
7856   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7857     switch (SrcI->getOpcode()) {
7858     default: break;
7859     case Instruction::LShr:
7860       // We can shrink lshr to something smaller if we know the bits shifted in
7861       // are already zeros.
7862       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7863         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7864         
7865         // Get a mask for the bits shifting in.
7866         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7867         Value* SrcIOp0 = SrcI->getOperand(0);
7868         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7869           if (ShAmt >= DestBitWidth)        // All zeros.
7870             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7871
7872           // Okay, we can shrink this.  Truncate the input, then return a new
7873           // shift.
7874           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7875           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7876                                        Ty, CI);
7877           return BinaryOperator::CreateLShr(V1, V2);
7878         }
7879       } else {     // This is a variable shr.
7880         
7881         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7882         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7883         // loop-invariant and CSE'd.
7884         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7885           Value *One = ConstantInt::get(SrcI->getType(), 1);
7886
7887           Value *V = InsertNewInstBefore(
7888               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7889                                      "tmp"), CI);
7890           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7891                                                             SrcI->getOperand(0),
7892                                                             "tmp"), CI);
7893           Value *Zero = Constant::getNullValue(V->getType());
7894           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7895         }
7896       }
7897       break;
7898     }
7899   }
7900   
7901   return 0;
7902 }
7903
7904 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7905 /// in order to eliminate the icmp.
7906 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7907                                              bool DoXform) {
7908   // If we are just checking for a icmp eq of a single bit and zext'ing it
7909   // to an integer, then shift the bit to the appropriate place and then
7910   // cast to integer to avoid the comparison.
7911   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7912     const APInt &Op1CV = Op1C->getValue();
7913       
7914     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7915     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7916     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7917         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7918       if (!DoXform) return ICI;
7919
7920       Value *In = ICI->getOperand(0);
7921       Value *Sh = ConstantInt::get(In->getType(),
7922                                    In->getType()->getPrimitiveSizeInBits()-1);
7923       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7924                                                         In->getName()+".lobit"),
7925                                CI);
7926       if (In->getType() != CI.getType())
7927         In = CastInst::CreateIntegerCast(In, CI.getType(),
7928                                          false/*ZExt*/, "tmp", &CI);
7929
7930       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7931         Constant *One = ConstantInt::get(In->getType(), 1);
7932         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7933                                                          In->getName()+".not"),
7934                                  CI);
7935       }
7936
7937       return ReplaceInstUsesWith(CI, In);
7938     }
7939       
7940       
7941       
7942     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7943     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7944     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7945     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7946     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7947     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7948     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7949     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7950     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7951         // This only works for EQ and NE
7952         ICI->isEquality()) {
7953       // If Op1C some other power of two, convert:
7954       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7955       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7956       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7957       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7958         
7959       APInt KnownZeroMask(~KnownZero);
7960       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7961         if (!DoXform) return ICI;
7962
7963         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7964         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7965           // (X&4) == 2 --> false
7966           // (X&4) != 2 --> true
7967           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7968           Res = ConstantExpr::getZExt(Res, CI.getType());
7969           return ReplaceInstUsesWith(CI, Res);
7970         }
7971           
7972         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7973         Value *In = ICI->getOperand(0);
7974         if (ShiftAmt) {
7975           // Perform a logical shr by shiftamt.
7976           // Insert the shift to put the result in the low bit.
7977           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7978                                   ConstantInt::get(In->getType(), ShiftAmt),
7979                                                    In->getName()+".lobit"), CI);
7980         }
7981           
7982         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7983           Constant *One = ConstantInt::get(In->getType(), 1);
7984           In = BinaryOperator::CreateXor(In, One, "tmp");
7985           InsertNewInstBefore(cast<Instruction>(In), CI);
7986         }
7987           
7988         if (CI.getType() == In->getType())
7989           return ReplaceInstUsesWith(CI, In);
7990         else
7991           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7992       }
7993     }
7994   }
7995
7996   return 0;
7997 }
7998
7999 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8000   // If one of the common conversion will work ..
8001   if (Instruction *Result = commonIntCastTransforms(CI))
8002     return Result;
8003
8004   Value *Src = CI.getOperand(0);
8005
8006   // If this is a cast of a cast
8007   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8008     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8009     // types and if the sizes are just right we can convert this into a logical
8010     // 'and' which will be much cheaper than the pair of casts.
8011     if (isa<TruncInst>(CSrc)) {
8012       // Get the sizes of the types involved
8013       Value *A = CSrc->getOperand(0);
8014       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8015       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8016       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8017       // If we're actually extending zero bits and the trunc is a no-op
8018       if (MidSize < DstSize && SrcSize == DstSize) {
8019         // Replace both of the casts with an And of the type mask.
8020         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8021         Constant *AndConst = ConstantInt::get(AndValue);
8022         Instruction *And = 
8023           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8024         // Unfortunately, if the type changed, we need to cast it back.
8025         if (And->getType() != CI.getType()) {
8026           And->setName(CSrc->getName()+".mask");
8027           InsertNewInstBefore(And, CI);
8028           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8029         }
8030         return And;
8031       }
8032     }
8033   }
8034
8035   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8036     return transformZExtICmp(ICI, CI);
8037
8038   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8039   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8040     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8041     // of the (zext icmp) will be transformed.
8042     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8043     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8044     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8045         (transformZExtICmp(LHS, CI, false) ||
8046          transformZExtICmp(RHS, CI, false))) {
8047       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8048       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8049       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8050     }
8051   }
8052
8053   return 0;
8054 }
8055
8056 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8057   if (Instruction *I = commonIntCastTransforms(CI))
8058     return I;
8059   
8060   Value *Src = CI.getOperand(0);
8061   
8062   // Canonicalize sign-extend from i1 to a select.
8063   if (Src->getType() == Type::Int1Ty)
8064     return SelectInst::Create(Src,
8065                               ConstantInt::getAllOnesValue(CI.getType()),
8066                               Constant::getNullValue(CI.getType()));
8067
8068   // See if the value being truncated is already sign extended.  If so, just
8069   // eliminate the trunc/sext pair.
8070   if (getOpcode(Src) == Instruction::Trunc) {
8071     Value *Op = cast<User>(Src)->getOperand(0);
8072     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8073     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8074     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8075     unsigned NumSignBits = ComputeNumSignBits(Op);
8076
8077     if (OpBits == DestBits) {
8078       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8079       // bits, it is already ready.
8080       if (NumSignBits > DestBits-MidBits)
8081         return ReplaceInstUsesWith(CI, Op);
8082     } else if (OpBits < DestBits) {
8083       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8084       // bits, just sext from i32.
8085       if (NumSignBits > OpBits-MidBits)
8086         return new SExtInst(Op, CI.getType(), "tmp");
8087     } else {
8088       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8089       // bits, just truncate to i32.
8090       if (NumSignBits > OpBits-MidBits)
8091         return new TruncInst(Op, CI.getType(), "tmp");
8092     }
8093   }
8094
8095   // If the input is a shl/ashr pair of a same constant, then this is a sign
8096   // extension from a smaller value.  If we could trust arbitrary bitwidth
8097   // integers, we could turn this into a truncate to the smaller bit and then
8098   // use a sext for the whole extension.  Since we don't, look deeper and check
8099   // for a truncate.  If the source and dest are the same type, eliminate the
8100   // trunc and extend and just do shifts.  For example, turn:
8101   //   %a = trunc i32 %i to i8
8102   //   %b = shl i8 %a, 6
8103   //   %c = ashr i8 %b, 6
8104   //   %d = sext i8 %c to i32
8105   // into:
8106   //   %a = shl i32 %i, 30
8107   //   %d = ashr i32 %a, 30
8108   Value *A = 0;
8109   ConstantInt *BA = 0, *CA = 0;
8110   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8111                         m_ConstantInt(CA))) &&
8112       BA == CA && isa<TruncInst>(A)) {
8113     Value *I = cast<TruncInst>(A)->getOperand(0);
8114     if (I->getType() == CI.getType()) {
8115       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8116       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8117       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8118       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8119       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8120                                                         CI.getName()), CI);
8121       return BinaryOperator::CreateAShr(I, ShAmtV);
8122     }
8123   }
8124   
8125   return 0;
8126 }
8127
8128 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8129 /// in the specified FP type without changing its value.
8130 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8131   bool losesInfo;
8132   APFloat F = CFP->getValueAPF();
8133   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8134   if (!losesInfo)
8135     return ConstantFP::get(F);
8136   return 0;
8137 }
8138
8139 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8140 /// through it until we get the source value.
8141 static Value *LookThroughFPExtensions(Value *V) {
8142   if (Instruction *I = dyn_cast<Instruction>(V))
8143     if (I->getOpcode() == Instruction::FPExt)
8144       return LookThroughFPExtensions(I->getOperand(0));
8145   
8146   // If this value is a constant, return the constant in the smallest FP type
8147   // that can accurately represent it.  This allows us to turn
8148   // (float)((double)X+2.0) into x+2.0f.
8149   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8150     if (CFP->getType() == Type::PPC_FP128Ty)
8151       return V;  // No constant folding of this.
8152     // See if the value can be truncated to float and then reextended.
8153     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8154       return V;
8155     if (CFP->getType() == Type::DoubleTy)
8156       return V;  // Won't shrink.
8157     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8158       return V;
8159     // Don't try to shrink to various long double types.
8160   }
8161   
8162   return V;
8163 }
8164
8165 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8166   if (Instruction *I = commonCastTransforms(CI))
8167     return I;
8168   
8169   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8170   // smaller than the destination type, we can eliminate the truncate by doing
8171   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8172   // many builtins (sqrt, etc).
8173   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8174   if (OpI && OpI->hasOneUse()) {
8175     switch (OpI->getOpcode()) {
8176     default: break;
8177     case Instruction::Add:
8178     case Instruction::Sub:
8179     case Instruction::Mul:
8180     case Instruction::FDiv:
8181     case Instruction::FRem:
8182       const Type *SrcTy = OpI->getType();
8183       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8184       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8185       if (LHSTrunc->getType() != SrcTy && 
8186           RHSTrunc->getType() != SrcTy) {
8187         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8188         // If the source types were both smaller than the destination type of
8189         // the cast, do this xform.
8190         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8191             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8192           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8193                                       CI.getType(), CI);
8194           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8195                                       CI.getType(), CI);
8196           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8197         }
8198       }
8199       break;  
8200     }
8201   }
8202   return 0;
8203 }
8204
8205 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8206   return commonCastTransforms(CI);
8207 }
8208
8209 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8210   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8211   if (OpI == 0)
8212     return commonCastTransforms(FI);
8213
8214   // fptoui(uitofp(X)) --> X
8215   // fptoui(sitofp(X)) --> X
8216   // This is safe if the intermediate type has enough bits in its mantissa to
8217   // accurately represent all values of X.  For example, do not do this with
8218   // i64->float->i64.  This is also safe for sitofp case, because any negative
8219   // 'X' value would cause an undefined result for the fptoui. 
8220   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8221       OpI->getOperand(0)->getType() == FI.getType() &&
8222       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8223                     OpI->getType()->getFPMantissaWidth())
8224     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8225
8226   return commonCastTransforms(FI);
8227 }
8228
8229 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8230   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8231   if (OpI == 0)
8232     return commonCastTransforms(FI);
8233   
8234   // fptosi(sitofp(X)) --> X
8235   // fptosi(uitofp(X)) --> X
8236   // This is safe if the intermediate type has enough bits in its mantissa to
8237   // accurately represent all values of X.  For example, do not do this with
8238   // i64->float->i64.  This is also safe for sitofp case, because any negative
8239   // 'X' value would cause an undefined result for the fptoui. 
8240   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8241       OpI->getOperand(0)->getType() == FI.getType() &&
8242       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8243                     OpI->getType()->getFPMantissaWidth())
8244     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8245   
8246   return commonCastTransforms(FI);
8247 }
8248
8249 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8250   return commonCastTransforms(CI);
8251 }
8252
8253 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8254   return commonCastTransforms(CI);
8255 }
8256
8257 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8258   return commonPointerCastTransforms(CI);
8259 }
8260
8261 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8262   if (Instruction *I = commonCastTransforms(CI))
8263     return I;
8264   
8265   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8266   if (!DestPointee->isSized()) return 0;
8267
8268   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8269   ConstantInt *Cst;
8270   Value *X;
8271   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8272                                     m_ConstantInt(Cst)))) {
8273     // If the source and destination operands have the same type, see if this
8274     // is a single-index GEP.
8275     if (X->getType() == CI.getType()) {
8276       // Get the size of the pointee type.
8277       uint64_t Size = TD->getABITypeSize(DestPointee);
8278
8279       // Convert the constant to intptr type.
8280       APInt Offset = Cst->getValue();
8281       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8282
8283       // If Offset is evenly divisible by Size, we can do this xform.
8284       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8285         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8286         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8287       }
8288     }
8289     // TODO: Could handle other cases, e.g. where add is indexing into field of
8290     // struct etc.
8291   } else if (CI.getOperand(0)->hasOneUse() &&
8292              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8293     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8294     // "inttoptr+GEP" instead of "add+intptr".
8295     
8296     // Get the size of the pointee type.
8297     uint64_t Size = TD->getABITypeSize(DestPointee);
8298     
8299     // Convert the constant to intptr type.
8300     APInt Offset = Cst->getValue();
8301     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8302     
8303     // If Offset is evenly divisible by Size, we can do this xform.
8304     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8305       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8306       
8307       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8308                                                             "tmp"), CI);
8309       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8310     }
8311   }
8312   return 0;
8313 }
8314
8315 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8316   // If the operands are integer typed then apply the integer transforms,
8317   // otherwise just apply the common ones.
8318   Value *Src = CI.getOperand(0);
8319   const Type *SrcTy = Src->getType();
8320   const Type *DestTy = CI.getType();
8321
8322   if (SrcTy->isInteger() && DestTy->isInteger()) {
8323     if (Instruction *Result = commonIntCastTransforms(CI))
8324       return Result;
8325   } else if (isa<PointerType>(SrcTy)) {
8326     if (Instruction *I = commonPointerCastTransforms(CI))
8327       return I;
8328   } else {
8329     if (Instruction *Result = commonCastTransforms(CI))
8330       return Result;
8331   }
8332
8333
8334   // Get rid of casts from one type to the same type. These are useless and can
8335   // be replaced by the operand.
8336   if (DestTy == Src->getType())
8337     return ReplaceInstUsesWith(CI, Src);
8338
8339   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8340     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8341     const Type *DstElTy = DstPTy->getElementType();
8342     const Type *SrcElTy = SrcPTy->getElementType();
8343     
8344     // If the address spaces don't match, don't eliminate the bitcast, which is
8345     // required for changing types.
8346     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8347       return 0;
8348     
8349     // If we are casting a malloc or alloca to a pointer to a type of the same
8350     // size, rewrite the allocation instruction to allocate the "right" type.
8351     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8352       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8353         return V;
8354     
8355     // If the source and destination are pointers, and this cast is equivalent
8356     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8357     // This can enhance SROA and other transforms that want type-safe pointers.
8358     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8359     unsigned NumZeros = 0;
8360     while (SrcElTy != DstElTy && 
8361            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8362            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8363       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8364       ++NumZeros;
8365     }
8366
8367     // If we found a path from the src to dest, create the getelementptr now.
8368     if (SrcElTy == DstElTy) {
8369       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8370       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8371                                        ((Instruction*) NULL));
8372     }
8373   }
8374
8375   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8376     if (SVI->hasOneUse()) {
8377       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8378       // a bitconvert to a vector with the same # elts.
8379       if (isa<VectorType>(DestTy) && 
8380           cast<VectorType>(DestTy)->getNumElements() ==
8381                 SVI->getType()->getNumElements() &&
8382           SVI->getType()->getNumElements() ==
8383             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8384         CastInst *Tmp;
8385         // If either of the operands is a cast from CI.getType(), then
8386         // evaluating the shuffle in the casted destination's type will allow
8387         // us to eliminate at least one cast.
8388         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8389              Tmp->getOperand(0)->getType() == DestTy) ||
8390             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8391              Tmp->getOperand(0)->getType() == DestTy)) {
8392           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8393                                                SVI->getOperand(0), DestTy, &CI);
8394           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8395                                                SVI->getOperand(1), DestTy, &CI);
8396           // Return a new shuffle vector.  Use the same element ID's, as we
8397           // know the vector types match #elts.
8398           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8399         }
8400       }
8401     }
8402   }
8403   return 0;
8404 }
8405
8406 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8407 ///   %C = or %A, %B
8408 ///   %D = select %cond, %C, %A
8409 /// into:
8410 ///   %C = select %cond, %B, 0
8411 ///   %D = or %A, %C
8412 ///
8413 /// Assuming that the specified instruction is an operand to the select, return
8414 /// a bitmask indicating which operands of this instruction are foldable if they
8415 /// equal the other incoming value of the select.
8416 ///
8417 static unsigned GetSelectFoldableOperands(Instruction *I) {
8418   switch (I->getOpcode()) {
8419   case Instruction::Add:
8420   case Instruction::Mul:
8421   case Instruction::And:
8422   case Instruction::Or:
8423   case Instruction::Xor:
8424     return 3;              // Can fold through either operand.
8425   case Instruction::Sub:   // Can only fold on the amount subtracted.
8426   case Instruction::Shl:   // Can only fold on the shift amount.
8427   case Instruction::LShr:
8428   case Instruction::AShr:
8429     return 1;
8430   default:
8431     return 0;              // Cannot fold
8432   }
8433 }
8434
8435 /// GetSelectFoldableConstant - For the same transformation as the previous
8436 /// function, return the identity constant that goes into the select.
8437 static Constant *GetSelectFoldableConstant(Instruction *I) {
8438   switch (I->getOpcode()) {
8439   default: assert(0 && "This cannot happen!"); abort();
8440   case Instruction::Add:
8441   case Instruction::Sub:
8442   case Instruction::Or:
8443   case Instruction::Xor:
8444   case Instruction::Shl:
8445   case Instruction::LShr:
8446   case Instruction::AShr:
8447     return Constant::getNullValue(I->getType());
8448   case Instruction::And:
8449     return Constant::getAllOnesValue(I->getType());
8450   case Instruction::Mul:
8451     return ConstantInt::get(I->getType(), 1);
8452   }
8453 }
8454
8455 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8456 /// have the same opcode and only one use each.  Try to simplify this.
8457 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8458                                           Instruction *FI) {
8459   if (TI->getNumOperands() == 1) {
8460     // If this is a non-volatile load or a cast from the same type,
8461     // merge.
8462     if (TI->isCast()) {
8463       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8464         return 0;
8465     } else {
8466       return 0;  // unknown unary op.
8467     }
8468
8469     // Fold this by inserting a select from the input values.
8470     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8471                                            FI->getOperand(0), SI.getName()+".v");
8472     InsertNewInstBefore(NewSI, SI);
8473     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8474                             TI->getType());
8475   }
8476
8477   // Only handle binary operators here.
8478   if (!isa<BinaryOperator>(TI))
8479     return 0;
8480
8481   // Figure out if the operations have any operands in common.
8482   Value *MatchOp, *OtherOpT, *OtherOpF;
8483   bool MatchIsOpZero;
8484   if (TI->getOperand(0) == FI->getOperand(0)) {
8485     MatchOp  = TI->getOperand(0);
8486     OtherOpT = TI->getOperand(1);
8487     OtherOpF = FI->getOperand(1);
8488     MatchIsOpZero = true;
8489   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8490     MatchOp  = TI->getOperand(1);
8491     OtherOpT = TI->getOperand(0);
8492     OtherOpF = FI->getOperand(0);
8493     MatchIsOpZero = false;
8494   } else if (!TI->isCommutative()) {
8495     return 0;
8496   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8497     MatchOp  = TI->getOperand(0);
8498     OtherOpT = TI->getOperand(1);
8499     OtherOpF = FI->getOperand(0);
8500     MatchIsOpZero = true;
8501   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8502     MatchOp  = TI->getOperand(1);
8503     OtherOpT = TI->getOperand(0);
8504     OtherOpF = FI->getOperand(1);
8505     MatchIsOpZero = true;
8506   } else {
8507     return 0;
8508   }
8509
8510   // If we reach here, they do have operations in common.
8511   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8512                                          OtherOpF, SI.getName()+".v");
8513   InsertNewInstBefore(NewSI, SI);
8514
8515   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8516     if (MatchIsOpZero)
8517       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8518     else
8519       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8520   }
8521   assert(0 && "Shouldn't get here");
8522   return 0;
8523 }
8524
8525 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8526 /// ICmpInst as its first operand.
8527 ///
8528 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8529                                                    ICmpInst *ICI) {
8530   bool Changed = false;
8531   ICmpInst::Predicate Pred = ICI->getPredicate();
8532   Value *CmpLHS = ICI->getOperand(0);
8533   Value *CmpRHS = ICI->getOperand(1);
8534   Value *TrueVal = SI.getTrueValue();
8535   Value *FalseVal = SI.getFalseValue();
8536
8537   // Check cases where the comparison is with a constant that
8538   // can be adjusted to fit the min/max idiom. We may edit ICI in
8539   // place here, so make sure the select is the only user.
8540   if (ICI->hasOneUse())
8541     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8542       switch (Pred) {
8543       default: break;
8544       case ICmpInst::ICMP_ULT:
8545       case ICmpInst::ICMP_SLT: {
8546         // X < MIN ? T : F  -->  F
8547         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8548           return ReplaceInstUsesWith(SI, FalseVal);
8549         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8550         Constant *AdjustedRHS = SubOne(CI);
8551         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8552             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8553           Pred = ICmpInst::getSwappedPredicate(Pred);
8554           CmpRHS = AdjustedRHS;
8555           std::swap(FalseVal, TrueVal);
8556           ICI->setPredicate(Pred);
8557           ICI->setOperand(1, CmpRHS);
8558           SI.setOperand(1, TrueVal);
8559           SI.setOperand(2, FalseVal);
8560           Changed = true;
8561         }
8562         break;
8563       }
8564       case ICmpInst::ICMP_UGT:
8565       case ICmpInst::ICMP_SGT: {
8566         // X > MAX ? T : F  -->  F
8567         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8568           return ReplaceInstUsesWith(SI, FalseVal);
8569         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8570         Constant *AdjustedRHS = AddOne(CI);
8571         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8572             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8573           Pred = ICmpInst::getSwappedPredicate(Pred);
8574           CmpRHS = AdjustedRHS;
8575           std::swap(FalseVal, TrueVal);
8576           ICI->setPredicate(Pred);
8577           ICI->setOperand(1, CmpRHS);
8578           SI.setOperand(1, TrueVal);
8579           SI.setOperand(2, FalseVal);
8580           Changed = true;
8581         }
8582         break;
8583       }
8584       }
8585
8586       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8587       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8588       CmpInst::Predicate Pred = ICI->getPredicate();
8589       if (match(TrueVal, m_ConstantInt(0)) &&
8590           match(FalseVal, m_ConstantInt(-1)))
8591         Pred = CmpInst::getInversePredicate(Pred);
8592       else if (!match(TrueVal, m_ConstantInt(-1)) ||
8593                !match(FalseVal, m_ConstantInt(0)))
8594         Pred = CmpInst::BAD_ICMP_PREDICATE;
8595       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8596         // If we are just checking for a icmp eq of a single bit and zext'ing it
8597         // to an integer, then shift the bit to the appropriate place and then
8598         // cast to integer to avoid the comparison.
8599         const APInt &Op1CV = CI->getValue();
8600     
8601         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8602         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8603         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8604             (Pred == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8605           Value *In = ICI->getOperand(0);
8606           Value *Sh = ConstantInt::get(In->getType(),
8607                                        In->getType()->getPrimitiveSizeInBits()-1);
8608           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8609                                                           In->getName()+".lobit"),
8610                                    *ICI);
8611           if (In->getType() != SI.getType())
8612             In = CastInst::CreateIntegerCast(In, SI.getType(),
8613                                              true/*SExt*/, "tmp", ICI);
8614     
8615           if (Pred == ICmpInst::ICMP_SGT)
8616             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8617                                        In->getName()+".not"), *ICI);
8618     
8619           return ReplaceInstUsesWith(SI, In);
8620         }
8621       }
8622     }
8623
8624   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8625     // Transform (X == Y) ? X : Y  -> Y
8626     if (Pred == ICmpInst::ICMP_EQ)
8627       return ReplaceInstUsesWith(SI, FalseVal);
8628     // Transform (X != Y) ? X : Y  -> X
8629     if (Pred == ICmpInst::ICMP_NE)
8630       return ReplaceInstUsesWith(SI, TrueVal);
8631     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8632
8633   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8634     // Transform (X == Y) ? Y : X  -> X
8635     if (Pred == ICmpInst::ICMP_EQ)
8636       return ReplaceInstUsesWith(SI, FalseVal);
8637     // Transform (X != Y) ? Y : X  -> Y
8638     if (Pred == ICmpInst::ICMP_NE)
8639       return ReplaceInstUsesWith(SI, TrueVal);
8640     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8641   }
8642
8643   /// NOTE: if we wanted to, this is where to detect integer ABS
8644
8645   return Changed ? &SI : 0;
8646 }
8647
8648 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8649   Value *CondVal = SI.getCondition();
8650   Value *TrueVal = SI.getTrueValue();
8651   Value *FalseVal = SI.getFalseValue();
8652
8653   // select true, X, Y  -> X
8654   // select false, X, Y -> Y
8655   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8656     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8657
8658   // select C, X, X -> X
8659   if (TrueVal == FalseVal)
8660     return ReplaceInstUsesWith(SI, TrueVal);
8661
8662   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8663     return ReplaceInstUsesWith(SI, FalseVal);
8664   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8665     return ReplaceInstUsesWith(SI, TrueVal);
8666   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8667     if (isa<Constant>(TrueVal))
8668       return ReplaceInstUsesWith(SI, TrueVal);
8669     else
8670       return ReplaceInstUsesWith(SI, FalseVal);
8671   }
8672
8673   if (SI.getType() == Type::Int1Ty) {
8674     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8675       if (C->getZExtValue()) {
8676         // Change: A = select B, true, C --> A = or B, C
8677         return BinaryOperator::CreateOr(CondVal, FalseVal);
8678       } else {
8679         // Change: A = select B, false, C --> A = and !B, C
8680         Value *NotCond =
8681           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8682                                              "not."+CondVal->getName()), SI);
8683         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8684       }
8685     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8686       if (C->getZExtValue() == false) {
8687         // Change: A = select B, C, false --> A = and B, C
8688         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8689       } else {
8690         // Change: A = select B, C, true --> A = or !B, C
8691         Value *NotCond =
8692           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8693                                              "not."+CondVal->getName()), SI);
8694         return BinaryOperator::CreateOr(NotCond, TrueVal);
8695       }
8696     }
8697     
8698     // select a, b, a  -> a&b
8699     // select a, a, b  -> a|b
8700     if (CondVal == TrueVal)
8701       return BinaryOperator::CreateOr(CondVal, FalseVal);
8702     else if (CondVal == FalseVal)
8703       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8704   }
8705
8706   // Selecting between two integer constants?
8707   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8708     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8709       // select C, 1, 0 -> zext C to int
8710       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8711         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8712       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8713         // select C, 0, 1 -> zext !C to int
8714         Value *NotCond =
8715           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8716                                                "not."+CondVal->getName()), SI);
8717         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8718       }
8719       
8720       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8721
8722       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8723
8724         // (x <s 0) ? -1 : 0 -> ashr x, 31
8725         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8726           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8727             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8728               // The comparison constant and the result are not neccessarily the
8729               // same width. Make an all-ones value by inserting a AShr.
8730               Value *X = IC->getOperand(0);
8731               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8732               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8733               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8734                                                         ShAmt, "ones");
8735               InsertNewInstBefore(SRA, SI);
8736               
8737               // Finally, convert to the type of the select RHS.  We figure out
8738               // if this requires a SExt, Trunc or BitCast based on the sizes.
8739               Instruction::CastOps opc = Instruction::BitCast;
8740               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8741               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8742               if (SRASize < SISize)
8743                 opc = Instruction::SExt;
8744               else if (SRASize > SISize)
8745                 opc = Instruction::Trunc;
8746               return CastInst::Create(opc, SRA, SI.getType());
8747             }
8748           }
8749
8750
8751         // If one of the constants is zero (we know they can't both be) and we
8752         // have an icmp instruction with zero, and we have an 'and' with the
8753         // non-constant value, eliminate this whole mess.  This corresponds to
8754         // cases like this: ((X & 27) ? 27 : 0)
8755         if (TrueValC->isZero() || FalseValC->isZero())
8756           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8757               cast<Constant>(IC->getOperand(1))->isNullValue())
8758             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8759               if (ICA->getOpcode() == Instruction::And &&
8760                   isa<ConstantInt>(ICA->getOperand(1)) &&
8761                   (ICA->getOperand(1) == TrueValC ||
8762                    ICA->getOperand(1) == FalseValC) &&
8763                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8764                 // Okay, now we know that everything is set up, we just don't
8765                 // know whether we have a icmp_ne or icmp_eq and whether the 
8766                 // true or false val is the zero.
8767                 bool ShouldNotVal = !TrueValC->isZero();
8768                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8769                 Value *V = ICA;
8770                 if (ShouldNotVal)
8771                   V = InsertNewInstBefore(BinaryOperator::Create(
8772                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8773                 return ReplaceInstUsesWith(SI, V);
8774               }
8775       }
8776     }
8777
8778   // See if we are selecting two values based on a comparison of the two values.
8779   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8780     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8781       // Transform (X == Y) ? X : Y  -> Y
8782       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8783         // This is not safe in general for floating point:  
8784         // consider X== -0, Y== +0.
8785         // It becomes safe if either operand is a nonzero constant.
8786         ConstantFP *CFPt, *CFPf;
8787         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8788               !CFPt->getValueAPF().isZero()) ||
8789             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8790              !CFPf->getValueAPF().isZero()))
8791         return ReplaceInstUsesWith(SI, FalseVal);
8792       }
8793       // Transform (X != Y) ? X : Y  -> X
8794       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8795         return ReplaceInstUsesWith(SI, TrueVal);
8796       // NOTE: if we wanted to, this is where to detect MIN/MAX
8797
8798     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8799       // Transform (X == Y) ? Y : X  -> X
8800       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8801         // This is not safe in general for floating point:  
8802         // consider X== -0, Y== +0.
8803         // It becomes safe if either operand is a nonzero constant.
8804         ConstantFP *CFPt, *CFPf;
8805         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8806               !CFPt->getValueAPF().isZero()) ||
8807             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8808              !CFPf->getValueAPF().isZero()))
8809           return ReplaceInstUsesWith(SI, FalseVal);
8810       }
8811       // Transform (X != Y) ? Y : X  -> Y
8812       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8813         return ReplaceInstUsesWith(SI, TrueVal);
8814       // NOTE: if we wanted to, this is where to detect MIN/MAX
8815     }
8816     // NOTE: if we wanted to, this is where to detect ABS
8817   }
8818
8819   // See if we are selecting two values based on a comparison of the two values.
8820   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8821     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8822       return Result;
8823
8824   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8825     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8826       if (TI->hasOneUse() && FI->hasOneUse()) {
8827         Instruction *AddOp = 0, *SubOp = 0;
8828
8829         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8830         if (TI->getOpcode() == FI->getOpcode())
8831           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8832             return IV;
8833
8834         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8835         // even legal for FP.
8836         if (TI->getOpcode() == Instruction::Sub &&
8837             FI->getOpcode() == Instruction::Add) {
8838           AddOp = FI; SubOp = TI;
8839         } else if (FI->getOpcode() == Instruction::Sub &&
8840                    TI->getOpcode() == Instruction::Add) {
8841           AddOp = TI; SubOp = FI;
8842         }
8843
8844         if (AddOp) {
8845           Value *OtherAddOp = 0;
8846           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8847             OtherAddOp = AddOp->getOperand(1);
8848           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8849             OtherAddOp = AddOp->getOperand(0);
8850           }
8851
8852           if (OtherAddOp) {
8853             // So at this point we know we have (Y -> OtherAddOp):
8854             //        select C, (add X, Y), (sub X, Z)
8855             Value *NegVal;  // Compute -Z
8856             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8857               NegVal = ConstantExpr::getNeg(C);
8858             } else {
8859               NegVal = InsertNewInstBefore(
8860                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8861             }
8862
8863             Value *NewTrueOp = OtherAddOp;
8864             Value *NewFalseOp = NegVal;
8865             if (AddOp != TI)
8866               std::swap(NewTrueOp, NewFalseOp);
8867             Instruction *NewSel =
8868               SelectInst::Create(CondVal, NewTrueOp,
8869                                  NewFalseOp, SI.getName() + ".p");
8870
8871             NewSel = InsertNewInstBefore(NewSel, SI);
8872             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8873           }
8874         }
8875       }
8876
8877   // See if we can fold the select into one of our operands.
8878   if (SI.getType()->isInteger()) {
8879     // See the comment above GetSelectFoldableOperands for a description of the
8880     // transformation we are doing here.
8881     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8882       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8883           !isa<Constant>(FalseVal))
8884         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8885           unsigned OpToFold = 0;
8886           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8887             OpToFold = 1;
8888           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8889             OpToFold = 2;
8890           }
8891
8892           if (OpToFold) {
8893             Constant *C = GetSelectFoldableConstant(TVI);
8894             Instruction *NewSel =
8895               SelectInst::Create(SI.getCondition(),
8896                                  TVI->getOperand(2-OpToFold), C);
8897             InsertNewInstBefore(NewSel, SI);
8898             NewSel->takeName(TVI);
8899             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8900               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8901             else {
8902               assert(0 && "Unknown instruction!!");
8903             }
8904           }
8905         }
8906
8907     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8908       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8909           !isa<Constant>(TrueVal))
8910         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8911           unsigned OpToFold = 0;
8912           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8913             OpToFold = 1;
8914           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8915             OpToFold = 2;
8916           }
8917
8918           if (OpToFold) {
8919             Constant *C = GetSelectFoldableConstant(FVI);
8920             Instruction *NewSel =
8921               SelectInst::Create(SI.getCondition(), C,
8922                                  FVI->getOperand(2-OpToFold));
8923             InsertNewInstBefore(NewSel, SI);
8924             NewSel->takeName(FVI);
8925             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8926               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8927             else
8928               assert(0 && "Unknown instruction!!");
8929           }
8930         }
8931   }
8932
8933   if (BinaryOperator::isNot(CondVal)) {
8934     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8935     SI.setOperand(1, FalseVal);
8936     SI.setOperand(2, TrueVal);
8937     return &SI;
8938   }
8939
8940   return 0;
8941 }
8942
8943 /// EnforceKnownAlignment - If the specified pointer points to an object that
8944 /// we control, modify the object's alignment to PrefAlign. This isn't
8945 /// often possible though. If alignment is important, a more reliable approach
8946 /// is to simply align all global variables and allocation instructions to
8947 /// their preferred alignment from the beginning.
8948 ///
8949 static unsigned EnforceKnownAlignment(Value *V,
8950                                       unsigned Align, unsigned PrefAlign) {
8951
8952   User *U = dyn_cast<User>(V);
8953   if (!U) return Align;
8954
8955   switch (getOpcode(U)) {
8956   default: break;
8957   case Instruction::BitCast:
8958     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8959   case Instruction::GetElementPtr: {
8960     // If all indexes are zero, it is just the alignment of the base pointer.
8961     bool AllZeroOperands = true;
8962     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8963       if (!isa<Constant>(*i) ||
8964           !cast<Constant>(*i)->isNullValue()) {
8965         AllZeroOperands = false;
8966         break;
8967       }
8968
8969     if (AllZeroOperands) {
8970       // Treat this like a bitcast.
8971       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8972     }
8973     break;
8974   }
8975   }
8976
8977   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8978     // If there is a large requested alignment and we can, bump up the alignment
8979     // of the global.
8980     if (!GV->isDeclaration()) {
8981       GV->setAlignment(PrefAlign);
8982       Align = PrefAlign;
8983     }
8984   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8985     // If there is a requested alignment and if this is an alloca, round up.  We
8986     // don't do this for malloc, because some systems can't respect the request.
8987     if (isa<AllocaInst>(AI)) {
8988       AI->setAlignment(PrefAlign);
8989       Align = PrefAlign;
8990     }
8991   }
8992
8993   return Align;
8994 }
8995
8996 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8997 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8998 /// and it is more than the alignment of the ultimate object, see if we can
8999 /// increase the alignment of the ultimate object, making this check succeed.
9000 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9001                                                   unsigned PrefAlign) {
9002   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9003                       sizeof(PrefAlign) * CHAR_BIT;
9004   APInt Mask = APInt::getAllOnesValue(BitWidth);
9005   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9006   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9007   unsigned TrailZ = KnownZero.countTrailingOnes();
9008   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9009
9010   if (PrefAlign > Align)
9011     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9012   
9013     // We don't need to make any adjustment.
9014   return Align;
9015 }
9016
9017 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9018   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9019   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9020   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9021   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9022
9023   if (CopyAlign < MinAlign) {
9024     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9025     return MI;
9026   }
9027   
9028   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9029   // load/store.
9030   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9031   if (MemOpLength == 0) return 0;
9032   
9033   // Source and destination pointer types are always "i8*" for intrinsic.  See
9034   // if the size is something we can handle with a single primitive load/store.
9035   // A single load+store correctly handles overlapping memory in the memmove
9036   // case.
9037   unsigned Size = MemOpLength->getZExtValue();
9038   if (Size == 0) return MI;  // Delete this mem transfer.
9039   
9040   if (Size > 8 || (Size&(Size-1)))
9041     return 0;  // If not 1/2/4/8 bytes, exit.
9042   
9043   // Use an integer load+store unless we can find something better.
9044   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9045   
9046   // Memcpy forces the use of i8* for the source and destination.  That means
9047   // that if you're using memcpy to move one double around, you'll get a cast
9048   // from double* to i8*.  We'd much rather use a double load+store rather than
9049   // an i64 load+store, here because this improves the odds that the source or
9050   // dest address will be promotable.  See if we can find a better type than the
9051   // integer datatype.
9052   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9053     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9054     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9055       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9056       // down through these levels if so.
9057       while (!SrcETy->isSingleValueType()) {
9058         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9059           if (STy->getNumElements() == 1)
9060             SrcETy = STy->getElementType(0);
9061           else
9062             break;
9063         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9064           if (ATy->getNumElements() == 1)
9065             SrcETy = ATy->getElementType();
9066           else
9067             break;
9068         } else
9069           break;
9070       }
9071       
9072       if (SrcETy->isSingleValueType())
9073         NewPtrTy = PointerType::getUnqual(SrcETy);
9074     }
9075   }
9076   
9077   
9078   // If the memcpy/memmove provides better alignment info than we can
9079   // infer, use it.
9080   SrcAlign = std::max(SrcAlign, CopyAlign);
9081   DstAlign = std::max(DstAlign, CopyAlign);
9082   
9083   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9084   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9085   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9086   InsertNewInstBefore(L, *MI);
9087   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9088
9089   // Set the size of the copy to 0, it will be deleted on the next iteration.
9090   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9091   return MI;
9092 }
9093
9094 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9095   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9096   if (MI->getAlignment()->getZExtValue() < Alignment) {
9097     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9098     return MI;
9099   }
9100   
9101   // Extract the length and alignment and fill if they are constant.
9102   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9103   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9104   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9105     return 0;
9106   uint64_t Len = LenC->getZExtValue();
9107   Alignment = MI->getAlignment()->getZExtValue();
9108   
9109   // If the length is zero, this is a no-op
9110   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9111   
9112   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9113   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9114     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9115     
9116     Value *Dest = MI->getDest();
9117     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9118
9119     // Alignment 0 is identity for alignment 1 for memset, but not store.
9120     if (Alignment == 0) Alignment = 1;
9121     
9122     // Extract the fill value and store.
9123     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9124     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9125                                       Alignment), *MI);
9126     
9127     // Set the size of the copy to 0, it will be deleted on the next iteration.
9128     MI->setLength(Constant::getNullValue(LenC->getType()));
9129     return MI;
9130   }
9131
9132   return 0;
9133 }
9134
9135
9136 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9137 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9138 /// the heavy lifting.
9139 ///
9140 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9141   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9142   if (!II) return visitCallSite(&CI);
9143   
9144   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9145   // visitCallSite.
9146   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9147     bool Changed = false;
9148
9149     // memmove/cpy/set of zero bytes is a noop.
9150     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9151       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9152
9153       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9154         if (CI->getZExtValue() == 1) {
9155           // Replace the instruction with just byte operations.  We would
9156           // transform other cases to loads/stores, but we don't know if
9157           // alignment is sufficient.
9158         }
9159     }
9160
9161     // If we have a memmove and the source operation is a constant global,
9162     // then the source and dest pointers can't alias, so we can change this
9163     // into a call to memcpy.
9164     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9165       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9166         if (GVSrc->isConstant()) {
9167           Module *M = CI.getParent()->getParent()->getParent();
9168           Intrinsic::ID MemCpyID;
9169           if (CI.getOperand(3)->getType() == Type::Int32Ty)
9170             MemCpyID = Intrinsic::memcpy_i32;
9171           else
9172             MemCpyID = Intrinsic::memcpy_i64;
9173           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9174           Changed = true;
9175         }
9176
9177       // memmove(x,x,size) -> noop.
9178       if (MMI->getSource() == MMI->getDest())
9179         return EraseInstFromFunction(CI);
9180     }
9181
9182     // If we can determine a pointer alignment that is bigger than currently
9183     // set, update the alignment.
9184     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9185       if (Instruction *I = SimplifyMemTransfer(MI))
9186         return I;
9187     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9188       if (Instruction *I = SimplifyMemSet(MSI))
9189         return I;
9190     }
9191           
9192     if (Changed) return II;
9193   }
9194   
9195   switch (II->getIntrinsicID()) {
9196   default: break;
9197   case Intrinsic::bswap:
9198     // bswap(bswap(x)) -> x
9199     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9200       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9201         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9202     break;
9203   case Intrinsic::ppc_altivec_lvx:
9204   case Intrinsic::ppc_altivec_lvxl:
9205   case Intrinsic::x86_sse_loadu_ps:
9206   case Intrinsic::x86_sse2_loadu_pd:
9207   case Intrinsic::x86_sse2_loadu_dq:
9208     // Turn PPC lvx     -> load if the pointer is known aligned.
9209     // Turn X86 loadups -> load if the pointer is known aligned.
9210     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9211       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9212                                        PointerType::getUnqual(II->getType()),
9213                                        CI);
9214       return new LoadInst(Ptr);
9215     }
9216     break;
9217   case Intrinsic::ppc_altivec_stvx:
9218   case Intrinsic::ppc_altivec_stvxl:
9219     // Turn stvx -> store if the pointer is known aligned.
9220     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9221       const Type *OpPtrTy = 
9222         PointerType::getUnqual(II->getOperand(1)->getType());
9223       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9224       return new StoreInst(II->getOperand(1), Ptr);
9225     }
9226     break;
9227   case Intrinsic::x86_sse_storeu_ps:
9228   case Intrinsic::x86_sse2_storeu_pd:
9229   case Intrinsic::x86_sse2_storeu_dq:
9230     // Turn X86 storeu -> store if the pointer is known aligned.
9231     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9232       const Type *OpPtrTy = 
9233         PointerType::getUnqual(II->getOperand(2)->getType());
9234       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9235       return new StoreInst(II->getOperand(2), Ptr);
9236     }
9237     break;
9238     
9239   case Intrinsic::x86_sse_cvttss2si: {
9240     // These intrinsics only demands the 0th element of its input vector.  If
9241     // we can simplify the input based on that, do so now.
9242     uint64_t UndefElts;
9243     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9244                                               UndefElts)) {
9245       II->setOperand(1, V);
9246       return II;
9247     }
9248     break;
9249   }
9250     
9251   case Intrinsic::ppc_altivec_vperm:
9252     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9253     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9254       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9255       
9256       // Check that all of the elements are integer constants or undefs.
9257       bool AllEltsOk = true;
9258       for (unsigned i = 0; i != 16; ++i) {
9259         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9260             !isa<UndefValue>(Mask->getOperand(i))) {
9261           AllEltsOk = false;
9262           break;
9263         }
9264       }
9265       
9266       if (AllEltsOk) {
9267         // Cast the input vectors to byte vectors.
9268         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9269         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9270         Value *Result = UndefValue::get(Op0->getType());
9271         
9272         // Only extract each element once.
9273         Value *ExtractedElts[32];
9274         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9275         
9276         for (unsigned i = 0; i != 16; ++i) {
9277           if (isa<UndefValue>(Mask->getOperand(i)))
9278             continue;
9279           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9280           Idx &= 31;  // Match the hardware behavior.
9281           
9282           if (ExtractedElts[Idx] == 0) {
9283             Instruction *Elt = 
9284               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9285             InsertNewInstBefore(Elt, CI);
9286             ExtractedElts[Idx] = Elt;
9287           }
9288         
9289           // Insert this value into the result vector.
9290           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9291                                              i, "tmp");
9292           InsertNewInstBefore(cast<Instruction>(Result), CI);
9293         }
9294         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9295       }
9296     }
9297     break;
9298
9299   case Intrinsic::stackrestore: {
9300     // If the save is right next to the restore, remove the restore.  This can
9301     // happen when variable allocas are DCE'd.
9302     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9303       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9304         BasicBlock::iterator BI = SS;
9305         if (&*++BI == II)
9306           return EraseInstFromFunction(CI);
9307       }
9308     }
9309     
9310     // Scan down this block to see if there is another stack restore in the
9311     // same block without an intervening call/alloca.
9312     BasicBlock::iterator BI = II;
9313     TerminatorInst *TI = II->getParent()->getTerminator();
9314     bool CannotRemove = false;
9315     for (++BI; &*BI != TI; ++BI) {
9316       if (isa<AllocaInst>(BI)) {
9317         CannotRemove = true;
9318         break;
9319       }
9320       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9321         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9322           // If there is a stackrestore below this one, remove this one.
9323           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9324             return EraseInstFromFunction(CI);
9325           // Otherwise, ignore the intrinsic.
9326         } else {
9327           // If we found a non-intrinsic call, we can't remove the stack
9328           // restore.
9329           CannotRemove = true;
9330           break;
9331         }
9332       }
9333     }
9334     
9335     // If the stack restore is in a return/unwind block and if there are no
9336     // allocas or calls between the restore and the return, nuke the restore.
9337     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9338       return EraseInstFromFunction(CI);
9339     break;
9340   }
9341   }
9342
9343   return visitCallSite(II);
9344 }
9345
9346 // InvokeInst simplification
9347 //
9348 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9349   return visitCallSite(&II);
9350 }
9351
9352 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9353 /// passed through the varargs area, we can eliminate the use of the cast.
9354 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9355                                          const CastInst * const CI,
9356                                          const TargetData * const TD,
9357                                          const int ix) {
9358   if (!CI->isLosslessCast())
9359     return false;
9360
9361   // The size of ByVal arguments is derived from the type, so we
9362   // can't change to a type with a different size.  If the size were
9363   // passed explicitly we could avoid this check.
9364   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9365     return true;
9366
9367   const Type* SrcTy = 
9368             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9369   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9370   if (!SrcTy->isSized() || !DstTy->isSized())
9371     return false;
9372   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9373     return false;
9374   return true;
9375 }
9376
9377 // visitCallSite - Improvements for call and invoke instructions.
9378 //
9379 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9380   bool Changed = false;
9381
9382   // If the callee is a constexpr cast of a function, attempt to move the cast
9383   // to the arguments of the call/invoke.
9384   if (transformConstExprCastCall(CS)) return 0;
9385
9386   Value *Callee = CS.getCalledValue();
9387
9388   if (Function *CalleeF = dyn_cast<Function>(Callee))
9389     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9390       Instruction *OldCall = CS.getInstruction();
9391       // If the call and callee calling conventions don't match, this call must
9392       // be unreachable, as the call is undefined.
9393       new StoreInst(ConstantInt::getTrue(),
9394                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9395                                     OldCall);
9396       if (!OldCall->use_empty())
9397         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9398       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9399         return EraseInstFromFunction(*OldCall);
9400       return 0;
9401     }
9402
9403   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9404     // This instruction is not reachable, just remove it.  We insert a store to
9405     // undef so that we know that this code is not reachable, despite the fact
9406     // that we can't modify the CFG here.
9407     new StoreInst(ConstantInt::getTrue(),
9408                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9409                   CS.getInstruction());
9410
9411     if (!CS.getInstruction()->use_empty())
9412       CS.getInstruction()->
9413         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9414
9415     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9416       // Don't break the CFG, insert a dummy cond branch.
9417       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9418                          ConstantInt::getTrue(), II);
9419     }
9420     return EraseInstFromFunction(*CS.getInstruction());
9421   }
9422
9423   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9424     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9425       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9426         return transformCallThroughTrampoline(CS);
9427
9428   const PointerType *PTy = cast<PointerType>(Callee->getType());
9429   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9430   if (FTy->isVarArg()) {
9431     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9432     // See if we can optimize any arguments passed through the varargs area of
9433     // the call.
9434     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9435            E = CS.arg_end(); I != E; ++I, ++ix) {
9436       CastInst *CI = dyn_cast<CastInst>(*I);
9437       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9438         *I = CI->getOperand(0);
9439         Changed = true;
9440       }
9441     }
9442   }
9443
9444   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9445     // Inline asm calls cannot throw - mark them 'nounwind'.
9446     CS.setDoesNotThrow();
9447     Changed = true;
9448   }
9449
9450   return Changed ? CS.getInstruction() : 0;
9451 }
9452
9453 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9454 // attempt to move the cast to the arguments of the call/invoke.
9455 //
9456 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9457   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9458   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9459   if (CE->getOpcode() != Instruction::BitCast || 
9460       !isa<Function>(CE->getOperand(0)))
9461     return false;
9462   Function *Callee = cast<Function>(CE->getOperand(0));
9463   Instruction *Caller = CS.getInstruction();
9464   const AttrListPtr &CallerPAL = CS.getAttributes();
9465
9466   // Okay, this is a cast from a function to a different type.  Unless doing so
9467   // would cause a type conversion of one of our arguments, change this call to
9468   // be a direct call with arguments casted to the appropriate types.
9469   //
9470   const FunctionType *FT = Callee->getFunctionType();
9471   const Type *OldRetTy = Caller->getType();
9472   const Type *NewRetTy = FT->getReturnType();
9473
9474   if (isa<StructType>(NewRetTy))
9475     return false; // TODO: Handle multiple return values.
9476
9477   // Check to see if we are changing the return type...
9478   if (OldRetTy != NewRetTy) {
9479     if (Callee->isDeclaration() &&
9480         // Conversion is ok if changing from one pointer type to another or from
9481         // a pointer to an integer of the same size.
9482         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9483           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9484       return false;   // Cannot transform this return value.
9485
9486     if (!Caller->use_empty() &&
9487         // void -> non-void is handled specially
9488         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9489       return false;   // Cannot transform this return value.
9490
9491     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9492       Attributes RAttrs = CallerPAL.getRetAttributes();
9493       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9494         return false;   // Attribute not compatible with transformed value.
9495     }
9496
9497     // If the callsite is an invoke instruction, and the return value is used by
9498     // a PHI node in a successor, we cannot change the return type of the call
9499     // because there is no place to put the cast instruction (without breaking
9500     // the critical edge).  Bail out in this case.
9501     if (!Caller->use_empty())
9502       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9503         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9504              UI != E; ++UI)
9505           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9506             if (PN->getParent() == II->getNormalDest() ||
9507                 PN->getParent() == II->getUnwindDest())
9508               return false;
9509   }
9510
9511   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9512   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9513
9514   CallSite::arg_iterator AI = CS.arg_begin();
9515   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9516     const Type *ParamTy = FT->getParamType(i);
9517     const Type *ActTy = (*AI)->getType();
9518
9519     if (!CastInst::isCastable(ActTy, ParamTy))
9520       return false;   // Cannot transform this parameter value.
9521
9522     if (CallerPAL.getParamAttributes(i + 1) 
9523         & Attribute::typeIncompatible(ParamTy))
9524       return false;   // Attribute not compatible with transformed value.
9525
9526     // Converting from one pointer type to another or between a pointer and an
9527     // integer of the same size is safe even if we do not have a body.
9528     bool isConvertible = ActTy == ParamTy ||
9529       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9530        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9531     if (Callee->isDeclaration() && !isConvertible) return false;
9532   }
9533
9534   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9535       Callee->isDeclaration())
9536     return false;   // Do not delete arguments unless we have a function body.
9537
9538   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9539       !CallerPAL.isEmpty())
9540     // In this case we have more arguments than the new function type, but we
9541     // won't be dropping them.  Check that these extra arguments have attributes
9542     // that are compatible with being a vararg call argument.
9543     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9544       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9545         break;
9546       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9547       if (PAttrs & Attribute::VarArgsIncompatible)
9548         return false;
9549     }
9550
9551   // Okay, we decided that this is a safe thing to do: go ahead and start
9552   // inserting cast instructions as necessary...
9553   std::vector<Value*> Args;
9554   Args.reserve(NumActualArgs);
9555   SmallVector<AttributeWithIndex, 8> attrVec;
9556   attrVec.reserve(NumCommonArgs);
9557
9558   // Get any return attributes.
9559   Attributes RAttrs = CallerPAL.getRetAttributes();
9560
9561   // If the return value is not being used, the type may not be compatible
9562   // with the existing attributes.  Wipe out any problematic attributes.
9563   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9564
9565   // Add the new return attributes.
9566   if (RAttrs)
9567     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9568
9569   AI = CS.arg_begin();
9570   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9571     const Type *ParamTy = FT->getParamType(i);
9572     if ((*AI)->getType() == ParamTy) {
9573       Args.push_back(*AI);
9574     } else {
9575       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9576           false, ParamTy, false);
9577       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9578       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9579     }
9580
9581     // Add any parameter attributes.
9582     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9583       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9584   }
9585
9586   // If the function takes more arguments than the call was taking, add them
9587   // now...
9588   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9589     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9590
9591   // If we are removing arguments to the function, emit an obnoxious warning...
9592   if (FT->getNumParams() < NumActualArgs) {
9593     if (!FT->isVarArg()) {
9594       cerr << "WARNING: While resolving call to function '"
9595            << Callee->getName() << "' arguments were dropped!\n";
9596     } else {
9597       // Add all of the arguments in their promoted form to the arg list...
9598       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9599         const Type *PTy = getPromotedType((*AI)->getType());
9600         if (PTy != (*AI)->getType()) {
9601           // Must promote to pass through va_arg area!
9602           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9603                                                                 PTy, false);
9604           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9605           InsertNewInstBefore(Cast, *Caller);
9606           Args.push_back(Cast);
9607         } else {
9608           Args.push_back(*AI);
9609         }
9610
9611         // Add any parameter attributes.
9612         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9613           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9614       }
9615     }
9616   }
9617
9618   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9619     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9620
9621   if (NewRetTy == Type::VoidTy)
9622     Caller->setName("");   // Void type should not have a name.
9623
9624   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9625
9626   Instruction *NC;
9627   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9628     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9629                             Args.begin(), Args.end(),
9630                             Caller->getName(), Caller);
9631     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9632     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9633   } else {
9634     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9635                           Caller->getName(), Caller);
9636     CallInst *CI = cast<CallInst>(Caller);
9637     if (CI->isTailCall())
9638       cast<CallInst>(NC)->setTailCall();
9639     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9640     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9641   }
9642
9643   // Insert a cast of the return type as necessary.
9644   Value *NV = NC;
9645   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9646     if (NV->getType() != Type::VoidTy) {
9647       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9648                                                             OldRetTy, false);
9649       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9650
9651       // If this is an invoke instruction, we should insert it after the first
9652       // non-phi, instruction in the normal successor block.
9653       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9654         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9655         InsertNewInstBefore(NC, *I);
9656       } else {
9657         // Otherwise, it's a call, just insert cast right after the call instr
9658         InsertNewInstBefore(NC, *Caller);
9659       }
9660       AddUsersToWorkList(*Caller);
9661     } else {
9662       NV = UndefValue::get(Caller->getType());
9663     }
9664   }
9665
9666   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9667     Caller->replaceAllUsesWith(NV);
9668   Caller->eraseFromParent();
9669   RemoveFromWorkList(Caller);
9670   return true;
9671 }
9672
9673 // transformCallThroughTrampoline - Turn a call to a function created by the
9674 // init_trampoline intrinsic into a direct call to the underlying function.
9675 //
9676 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9677   Value *Callee = CS.getCalledValue();
9678   const PointerType *PTy = cast<PointerType>(Callee->getType());
9679   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9680   const AttrListPtr &Attrs = CS.getAttributes();
9681
9682   // If the call already has the 'nest' attribute somewhere then give up -
9683   // otherwise 'nest' would occur twice after splicing in the chain.
9684   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9685     return 0;
9686
9687   IntrinsicInst *Tramp =
9688     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9689
9690   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9691   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9692   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9693
9694   const AttrListPtr &NestAttrs = NestF->getAttributes();
9695   if (!NestAttrs.isEmpty()) {
9696     unsigned NestIdx = 1;
9697     const Type *NestTy = 0;
9698     Attributes NestAttr = Attribute::None;
9699
9700     // Look for a parameter marked with the 'nest' attribute.
9701     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9702          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9703       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9704         // Record the parameter type and any other attributes.
9705         NestTy = *I;
9706         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9707         break;
9708       }
9709
9710     if (NestTy) {
9711       Instruction *Caller = CS.getInstruction();
9712       std::vector<Value*> NewArgs;
9713       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9714
9715       SmallVector<AttributeWithIndex, 8> NewAttrs;
9716       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9717
9718       // Insert the nest argument into the call argument list, which may
9719       // mean appending it.  Likewise for attributes.
9720
9721       // Add any result attributes.
9722       if (Attributes Attr = Attrs.getRetAttributes())
9723         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9724
9725       {
9726         unsigned Idx = 1;
9727         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9728         do {
9729           if (Idx == NestIdx) {
9730             // Add the chain argument and attributes.
9731             Value *NestVal = Tramp->getOperand(3);
9732             if (NestVal->getType() != NestTy)
9733               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9734             NewArgs.push_back(NestVal);
9735             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9736           }
9737
9738           if (I == E)
9739             break;
9740
9741           // Add the original argument and attributes.
9742           NewArgs.push_back(*I);
9743           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9744             NewAttrs.push_back
9745               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9746
9747           ++Idx, ++I;
9748         } while (1);
9749       }
9750
9751       // Add any function attributes.
9752       if (Attributes Attr = Attrs.getFnAttributes())
9753         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9754
9755       // The trampoline may have been bitcast to a bogus type (FTy).
9756       // Handle this by synthesizing a new function type, equal to FTy
9757       // with the chain parameter inserted.
9758
9759       std::vector<const Type*> NewTypes;
9760       NewTypes.reserve(FTy->getNumParams()+1);
9761
9762       // Insert the chain's type into the list of parameter types, which may
9763       // mean appending it.
9764       {
9765         unsigned Idx = 1;
9766         FunctionType::param_iterator I = FTy->param_begin(),
9767           E = FTy->param_end();
9768
9769         do {
9770           if (Idx == NestIdx)
9771             // Add the chain's type.
9772             NewTypes.push_back(NestTy);
9773
9774           if (I == E)
9775             break;
9776
9777           // Add the original type.
9778           NewTypes.push_back(*I);
9779
9780           ++Idx, ++I;
9781         } while (1);
9782       }
9783
9784       // Replace the trampoline call with a direct call.  Let the generic
9785       // code sort out any function type mismatches.
9786       FunctionType *NewFTy =
9787         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9788       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9789         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9790       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9791
9792       Instruction *NewCaller;
9793       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9794         NewCaller = InvokeInst::Create(NewCallee,
9795                                        II->getNormalDest(), II->getUnwindDest(),
9796                                        NewArgs.begin(), NewArgs.end(),
9797                                        Caller->getName(), Caller);
9798         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9799         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9800       } else {
9801         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9802                                      Caller->getName(), Caller);
9803         if (cast<CallInst>(Caller)->isTailCall())
9804           cast<CallInst>(NewCaller)->setTailCall();
9805         cast<CallInst>(NewCaller)->
9806           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9807         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9808       }
9809       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9810         Caller->replaceAllUsesWith(NewCaller);
9811       Caller->eraseFromParent();
9812       RemoveFromWorkList(Caller);
9813       return 0;
9814     }
9815   }
9816
9817   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9818   // parameter, there is no need to adjust the argument list.  Let the generic
9819   // code sort out any function type mismatches.
9820   Constant *NewCallee =
9821     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9822   CS.setCalledFunction(NewCallee);
9823   return CS.getInstruction();
9824 }
9825
9826 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9827 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9828 /// and a single binop.
9829 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9830   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9831   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9832          isa<CmpInst>(FirstInst));
9833   unsigned Opc = FirstInst->getOpcode();
9834   Value *LHSVal = FirstInst->getOperand(0);
9835   Value *RHSVal = FirstInst->getOperand(1);
9836     
9837   const Type *LHSType = LHSVal->getType();
9838   const Type *RHSType = RHSVal->getType();
9839   
9840   // Scan to see if all operands are the same opcode, all have one use, and all
9841   // kill their operands (i.e. the operands have one use).
9842   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9843     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9844     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9845         // Verify type of the LHS matches so we don't fold cmp's of different
9846         // types or GEP's with different index types.
9847         I->getOperand(0)->getType() != LHSType ||
9848         I->getOperand(1)->getType() != RHSType)
9849       return 0;
9850
9851     // If they are CmpInst instructions, check their predicates
9852     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9853       if (cast<CmpInst>(I)->getPredicate() !=
9854           cast<CmpInst>(FirstInst)->getPredicate())
9855         return 0;
9856     
9857     // Keep track of which operand needs a phi node.
9858     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9859     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9860   }
9861   
9862   // Otherwise, this is safe to transform, determine if it is profitable.
9863
9864   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9865   // Indexes are often folded into load/store instructions, so we don't want to
9866   // hide them behind a phi.
9867   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9868     return 0;
9869   
9870   Value *InLHS = FirstInst->getOperand(0);
9871   Value *InRHS = FirstInst->getOperand(1);
9872   PHINode *NewLHS = 0, *NewRHS = 0;
9873   if (LHSVal == 0) {
9874     NewLHS = PHINode::Create(LHSType,
9875                              FirstInst->getOperand(0)->getName() + ".pn");
9876     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9877     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9878     InsertNewInstBefore(NewLHS, PN);
9879     LHSVal = NewLHS;
9880   }
9881   
9882   if (RHSVal == 0) {
9883     NewRHS = PHINode::Create(RHSType,
9884                              FirstInst->getOperand(1)->getName() + ".pn");
9885     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9886     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9887     InsertNewInstBefore(NewRHS, PN);
9888     RHSVal = NewRHS;
9889   }
9890   
9891   // Add all operands to the new PHIs.
9892   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9893     if (NewLHS) {
9894       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9895       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9896     }
9897     if (NewRHS) {
9898       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9899       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9900     }
9901   }
9902     
9903   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9904     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9905   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9906     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9907                            RHSVal);
9908   else {
9909     assert(isa<GetElementPtrInst>(FirstInst));
9910     return GetElementPtrInst::Create(LHSVal, RHSVal);
9911   }
9912 }
9913
9914 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9915 /// of the block that defines it.  This means that it must be obvious the value
9916 /// of the load is not changed from the point of the load to the end of the
9917 /// block it is in.
9918 ///
9919 /// Finally, it is safe, but not profitable, to sink a load targetting a
9920 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9921 /// to a register.
9922 static bool isSafeToSinkLoad(LoadInst *L) {
9923   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9924   
9925   for (++BBI; BBI != E; ++BBI)
9926     if (BBI->mayWriteToMemory())
9927       return false;
9928   
9929   // Check for non-address taken alloca.  If not address-taken already, it isn't
9930   // profitable to do this xform.
9931   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9932     bool isAddressTaken = false;
9933     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9934          UI != E; ++UI) {
9935       if (isa<LoadInst>(UI)) continue;
9936       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9937         // If storing TO the alloca, then the address isn't taken.
9938         if (SI->getOperand(1) == AI) continue;
9939       }
9940       isAddressTaken = true;
9941       break;
9942     }
9943     
9944     if (!isAddressTaken)
9945       return false;
9946   }
9947   
9948   return true;
9949 }
9950
9951
9952 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9953 // operator and they all are only used by the PHI, PHI together their
9954 // inputs, and do the operation once, to the result of the PHI.
9955 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9956   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9957
9958   // Scan the instruction, looking for input operations that can be folded away.
9959   // If all input operands to the phi are the same instruction (e.g. a cast from
9960   // the same type or "+42") we can pull the operation through the PHI, reducing
9961   // code size and simplifying code.
9962   Constant *ConstantOp = 0;
9963   const Type *CastSrcTy = 0;
9964   bool isVolatile = false;
9965   if (isa<CastInst>(FirstInst)) {
9966     CastSrcTy = FirstInst->getOperand(0)->getType();
9967   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9968     // Can fold binop, compare or shift here if the RHS is a constant, 
9969     // otherwise call FoldPHIArgBinOpIntoPHI.
9970     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9971     if (ConstantOp == 0)
9972       return FoldPHIArgBinOpIntoPHI(PN);
9973   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9974     isVolatile = LI->isVolatile();
9975     // We can't sink the load if the loaded value could be modified between the
9976     // load and the PHI.
9977     if (LI->getParent() != PN.getIncomingBlock(0) ||
9978         !isSafeToSinkLoad(LI))
9979       return 0;
9980     
9981     // If the PHI is of volatile loads and the load block has multiple
9982     // successors, sinking it would remove a load of the volatile value from
9983     // the path through the other successor.
9984     if (isVolatile &&
9985         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9986       return 0;
9987     
9988   } else if (isa<GetElementPtrInst>(FirstInst)) {
9989     if (FirstInst->getNumOperands() == 2)
9990       return FoldPHIArgBinOpIntoPHI(PN);
9991     // Can't handle general GEPs yet.
9992     return 0;
9993   } else {
9994     return 0;  // Cannot fold this operation.
9995   }
9996
9997   // Check to see if all arguments are the same operation.
9998   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9999     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10000     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10001     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10002       return 0;
10003     if (CastSrcTy) {
10004       if (I->getOperand(0)->getType() != CastSrcTy)
10005         return 0;  // Cast operation must match.
10006     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10007       // We can't sink the load if the loaded value could be modified between 
10008       // the load and the PHI.
10009       if (LI->isVolatile() != isVolatile ||
10010           LI->getParent() != PN.getIncomingBlock(i) ||
10011           !isSafeToSinkLoad(LI))
10012         return 0;
10013       
10014       // If the PHI is of volatile loads and the load block has multiple
10015       // successors, sinking it would remove a load of the volatile value from
10016       // the path through the other successor.
10017       if (isVolatile &&
10018           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10019         return 0;
10020
10021       
10022     } else if (I->getOperand(1) != ConstantOp) {
10023       return 0;
10024     }
10025   }
10026
10027   // Okay, they are all the same operation.  Create a new PHI node of the
10028   // correct type, and PHI together all of the LHS's of the instructions.
10029   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10030                                    PN.getName()+".in");
10031   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10032
10033   Value *InVal = FirstInst->getOperand(0);
10034   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10035
10036   // Add all operands to the new PHI.
10037   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10038     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10039     if (NewInVal != InVal)
10040       InVal = 0;
10041     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10042   }
10043
10044   Value *PhiVal;
10045   if (InVal) {
10046     // The new PHI unions all of the same values together.  This is really
10047     // common, so we handle it intelligently here for compile-time speed.
10048     PhiVal = InVal;
10049     delete NewPN;
10050   } else {
10051     InsertNewInstBefore(NewPN, PN);
10052     PhiVal = NewPN;
10053   }
10054
10055   // Insert and return the new operation.
10056   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10057     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10058   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10059     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10060   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10061     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10062                            PhiVal, ConstantOp);
10063   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10064   
10065   // If this was a volatile load that we are merging, make sure to loop through
10066   // and mark all the input loads as non-volatile.  If we don't do this, we will
10067   // insert a new volatile load and the old ones will not be deletable.
10068   if (isVolatile)
10069     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10070       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10071   
10072   return new LoadInst(PhiVal, "", isVolatile);
10073 }
10074
10075 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10076 /// that is dead.
10077 static bool DeadPHICycle(PHINode *PN,
10078                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10079   if (PN->use_empty()) return true;
10080   if (!PN->hasOneUse()) return false;
10081
10082   // Remember this node, and if we find the cycle, return.
10083   if (!PotentiallyDeadPHIs.insert(PN))
10084     return true;
10085   
10086   // Don't scan crazily complex things.
10087   if (PotentiallyDeadPHIs.size() == 16)
10088     return false;
10089
10090   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10091     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10092
10093   return false;
10094 }
10095
10096 /// PHIsEqualValue - Return true if this phi node is always equal to
10097 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10098 ///   z = some value; x = phi (y, z); y = phi (x, z)
10099 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10100                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10101   // See if we already saw this PHI node.
10102   if (!ValueEqualPHIs.insert(PN))
10103     return true;
10104   
10105   // Don't scan crazily complex things.
10106   if (ValueEqualPHIs.size() == 16)
10107     return false;
10108  
10109   // Scan the operands to see if they are either phi nodes or are equal to
10110   // the value.
10111   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10112     Value *Op = PN->getIncomingValue(i);
10113     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10114       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10115         return false;
10116     } else if (Op != NonPhiInVal)
10117       return false;
10118   }
10119   
10120   return true;
10121 }
10122
10123
10124 // PHINode simplification
10125 //
10126 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10127   // If LCSSA is around, don't mess with Phi nodes
10128   if (MustPreserveLCSSA) return 0;
10129   
10130   if (Value *V = PN.hasConstantValue())
10131     return ReplaceInstUsesWith(PN, V);
10132
10133   // If all PHI operands are the same operation, pull them through the PHI,
10134   // reducing code size.
10135   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10136       PN.getIncomingValue(0)->hasOneUse())
10137     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10138       return Result;
10139
10140   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10141   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10142   // PHI)... break the cycle.
10143   if (PN.hasOneUse()) {
10144     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10145     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10146       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10147       PotentiallyDeadPHIs.insert(&PN);
10148       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10149         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10150     }
10151    
10152     // If this phi has a single use, and if that use just computes a value for
10153     // the next iteration of a loop, delete the phi.  This occurs with unused
10154     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10155     // common case here is good because the only other things that catch this
10156     // are induction variable analysis (sometimes) and ADCE, which is only run
10157     // late.
10158     if (PHIUser->hasOneUse() &&
10159         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10160         PHIUser->use_back() == &PN) {
10161       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10162     }
10163   }
10164
10165   // We sometimes end up with phi cycles that non-obviously end up being the
10166   // same value, for example:
10167   //   z = some value; x = phi (y, z); y = phi (x, z)
10168   // where the phi nodes don't necessarily need to be in the same block.  Do a
10169   // quick check to see if the PHI node only contains a single non-phi value, if
10170   // so, scan to see if the phi cycle is actually equal to that value.
10171   {
10172     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10173     // Scan for the first non-phi operand.
10174     while (InValNo != NumOperandVals && 
10175            isa<PHINode>(PN.getIncomingValue(InValNo)))
10176       ++InValNo;
10177
10178     if (InValNo != NumOperandVals) {
10179       Value *NonPhiInVal = PN.getOperand(InValNo);
10180       
10181       // Scan the rest of the operands to see if there are any conflicts, if so
10182       // there is no need to recursively scan other phis.
10183       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10184         Value *OpVal = PN.getIncomingValue(InValNo);
10185         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10186           break;
10187       }
10188       
10189       // If we scanned over all operands, then we have one unique value plus
10190       // phi values.  Scan PHI nodes to see if they all merge in each other or
10191       // the value.
10192       if (InValNo == NumOperandVals) {
10193         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10194         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10195           return ReplaceInstUsesWith(PN, NonPhiInVal);
10196       }
10197     }
10198   }
10199   return 0;
10200 }
10201
10202 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10203                                    Instruction *InsertPoint,
10204                                    InstCombiner *IC) {
10205   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10206   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10207   // We must cast correctly to the pointer type. Ensure that we
10208   // sign extend the integer value if it is smaller as this is
10209   // used for address computation.
10210   Instruction::CastOps opcode = 
10211      (VTySize < PtrSize ? Instruction::SExt :
10212       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10213   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10214 }
10215
10216
10217 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10218   Value *PtrOp = GEP.getOperand(0);
10219   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10220   // If so, eliminate the noop.
10221   if (GEP.getNumOperands() == 1)
10222     return ReplaceInstUsesWith(GEP, PtrOp);
10223
10224   if (isa<UndefValue>(GEP.getOperand(0)))
10225     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10226
10227   bool HasZeroPointerIndex = false;
10228   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10229     HasZeroPointerIndex = C->isNullValue();
10230
10231   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10232     return ReplaceInstUsesWith(GEP, PtrOp);
10233
10234   // Eliminate unneeded casts for indices.
10235   bool MadeChange = false;
10236   
10237   gep_type_iterator GTI = gep_type_begin(GEP);
10238   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10239        i != e; ++i, ++GTI) {
10240     if (isa<SequentialType>(*GTI)) {
10241       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10242         if (CI->getOpcode() == Instruction::ZExt ||
10243             CI->getOpcode() == Instruction::SExt) {
10244           const Type *SrcTy = CI->getOperand(0)->getType();
10245           // We can eliminate a cast from i32 to i64 iff the target 
10246           // is a 32-bit pointer target.
10247           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10248             MadeChange = true;
10249             *i = CI->getOperand(0);
10250           }
10251         }
10252       }
10253       // If we are using a wider index than needed for this platform, shrink it
10254       // to what we need.  If narrower, sign-extend it to what we need.
10255       // If the incoming value needs a cast instruction,
10256       // insert it.  This explicit cast can make subsequent optimizations more
10257       // obvious.
10258       Value *Op = *i;
10259       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10260         if (Constant *C = dyn_cast<Constant>(Op)) {
10261           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10262           MadeChange = true;
10263         } else {
10264           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10265                                 GEP);
10266           *i = Op;
10267           MadeChange = true;
10268         }
10269       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10270         if (Constant *C = dyn_cast<Constant>(Op)) {
10271           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10272           MadeChange = true;
10273         } else {
10274           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10275                                 GEP);
10276           *i = Op;
10277           MadeChange = true;
10278         }
10279       }
10280     }
10281   }
10282   if (MadeChange) return &GEP;
10283
10284   // If this GEP instruction doesn't move the pointer, and if the input operand
10285   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10286   // real input to the dest type.
10287   if (GEP.hasAllZeroIndices()) {
10288     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10289       // If the bitcast is of an allocation, and the allocation will be
10290       // converted to match the type of the cast, don't touch this.
10291       if (isa<AllocationInst>(BCI->getOperand(0))) {
10292         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10293         if (Instruction *I = visitBitCast(*BCI)) {
10294           if (I != BCI) {
10295             I->takeName(BCI);
10296             BCI->getParent()->getInstList().insert(BCI, I);
10297             ReplaceInstUsesWith(*BCI, I);
10298           }
10299           return &GEP;
10300         }
10301       }
10302       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10303     }
10304   }
10305   
10306   // Combine Indices - If the source pointer to this getelementptr instruction
10307   // is a getelementptr instruction, combine the indices of the two
10308   // getelementptr instructions into a single instruction.
10309   //
10310   SmallVector<Value*, 8> SrcGEPOperands;
10311   if (User *Src = dyn_castGetElementPtr(PtrOp))
10312     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10313
10314   if (!SrcGEPOperands.empty()) {
10315     // Note that if our source is a gep chain itself that we wait for that
10316     // chain to be resolved before we perform this transformation.  This
10317     // avoids us creating a TON of code in some cases.
10318     //
10319     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10320         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10321       return 0;   // Wait until our source is folded to completion.
10322
10323     SmallVector<Value*, 8> Indices;
10324
10325     // Find out whether the last index in the source GEP is a sequential idx.
10326     bool EndsWithSequential = false;
10327     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10328            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10329       EndsWithSequential = !isa<StructType>(*I);
10330
10331     // Can we combine the two pointer arithmetics offsets?
10332     if (EndsWithSequential) {
10333       // Replace: gep (gep %P, long B), long A, ...
10334       // With:    T = long A+B; gep %P, T, ...
10335       //
10336       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10337       if (SO1 == Constant::getNullValue(SO1->getType())) {
10338         Sum = GO1;
10339       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10340         Sum = SO1;
10341       } else {
10342         // If they aren't the same type, convert both to an integer of the
10343         // target's pointer size.
10344         if (SO1->getType() != GO1->getType()) {
10345           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10346             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10347           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10348             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10349           } else {
10350             unsigned PS = TD->getPointerSizeInBits();
10351             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10352               // Convert GO1 to SO1's type.
10353               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10354
10355             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10356               // Convert SO1 to GO1's type.
10357               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10358             } else {
10359               const Type *PT = TD->getIntPtrType();
10360               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10361               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10362             }
10363           }
10364         }
10365         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10366           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10367         else {
10368           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10369           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10370         }
10371       }
10372
10373       // Recycle the GEP we already have if possible.
10374       if (SrcGEPOperands.size() == 2) {
10375         GEP.setOperand(0, SrcGEPOperands[0]);
10376         GEP.setOperand(1, Sum);
10377         return &GEP;
10378       } else {
10379         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10380                        SrcGEPOperands.end()-1);
10381         Indices.push_back(Sum);
10382         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10383       }
10384     } else if (isa<Constant>(*GEP.idx_begin()) &&
10385                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10386                SrcGEPOperands.size() != 1) {
10387       // Otherwise we can do the fold if the first index of the GEP is a zero
10388       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10389                      SrcGEPOperands.end());
10390       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10391     }
10392
10393     if (!Indices.empty())
10394       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10395                                        Indices.end(), GEP.getName());
10396
10397   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10398     // GEP of global variable.  If all of the indices for this GEP are
10399     // constants, we can promote this to a constexpr instead of an instruction.
10400
10401     // Scan for nonconstants...
10402     SmallVector<Constant*, 8> Indices;
10403     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10404     for (; I != E && isa<Constant>(*I); ++I)
10405       Indices.push_back(cast<Constant>(*I));
10406
10407     if (I == E) {  // If they are all constants...
10408       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10409                                                     &Indices[0],Indices.size());
10410
10411       // Replace all uses of the GEP with the new constexpr...
10412       return ReplaceInstUsesWith(GEP, CE);
10413     }
10414   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10415     if (!isa<PointerType>(X->getType())) {
10416       // Not interesting.  Source pointer must be a cast from pointer.
10417     } else if (HasZeroPointerIndex) {
10418       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10419       // into     : GEP [10 x i8]* X, i32 0, ...
10420       //
10421       // This occurs when the program declares an array extern like "int X[];"
10422       //
10423       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10424       const PointerType *XTy = cast<PointerType>(X->getType());
10425       if (const ArrayType *XATy =
10426           dyn_cast<ArrayType>(XTy->getElementType()))
10427         if (const ArrayType *CATy =
10428             dyn_cast<ArrayType>(CPTy->getElementType()))
10429           if (CATy->getElementType() == XATy->getElementType()) {
10430             // At this point, we know that the cast source type is a pointer
10431             // to an array of the same type as the destination pointer
10432             // array.  Because the array type is never stepped over (there
10433             // is a leading zero) we can fold the cast into this GEP.
10434             GEP.setOperand(0, X);
10435             return &GEP;
10436           }
10437     } else if (GEP.getNumOperands() == 2) {
10438       // Transform things like:
10439       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10440       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10441       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10442       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10443       if (isa<ArrayType>(SrcElTy) &&
10444           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10445           TD->getABITypeSize(ResElTy)) {
10446         Value *Idx[2];
10447         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10448         Idx[1] = GEP.getOperand(1);
10449         Value *V = InsertNewInstBefore(
10450                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10451         // V and GEP are both pointer types --> BitCast
10452         return new BitCastInst(V, GEP.getType());
10453       }
10454       
10455       // Transform things like:
10456       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10457       //   (where tmp = 8*tmp2) into:
10458       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10459       
10460       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10461         uint64_t ArrayEltSize =
10462             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10463         
10464         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10465         // allow either a mul, shift, or constant here.
10466         Value *NewIdx = 0;
10467         ConstantInt *Scale = 0;
10468         if (ArrayEltSize == 1) {
10469           NewIdx = GEP.getOperand(1);
10470           Scale = ConstantInt::get(NewIdx->getType(), 1);
10471         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10472           NewIdx = ConstantInt::get(CI->getType(), 1);
10473           Scale = CI;
10474         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10475           if (Inst->getOpcode() == Instruction::Shl &&
10476               isa<ConstantInt>(Inst->getOperand(1))) {
10477             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10478             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10479             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10480             NewIdx = Inst->getOperand(0);
10481           } else if (Inst->getOpcode() == Instruction::Mul &&
10482                      isa<ConstantInt>(Inst->getOperand(1))) {
10483             Scale = cast<ConstantInt>(Inst->getOperand(1));
10484             NewIdx = Inst->getOperand(0);
10485           }
10486         }
10487         
10488         // If the index will be to exactly the right offset with the scale taken
10489         // out, perform the transformation. Note, we don't know whether Scale is
10490         // signed or not. We'll use unsigned version of division/modulo
10491         // operation after making sure Scale doesn't have the sign bit set.
10492         if (Scale && Scale->getSExtValue() >= 0LL &&
10493             Scale->getZExtValue() % ArrayEltSize == 0) {
10494           Scale = ConstantInt::get(Scale->getType(),
10495                                    Scale->getZExtValue() / ArrayEltSize);
10496           if (Scale->getZExtValue() != 1) {
10497             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10498                                                        false /*ZExt*/);
10499             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10500             NewIdx = InsertNewInstBefore(Sc, GEP);
10501           }
10502
10503           // Insert the new GEP instruction.
10504           Value *Idx[2];
10505           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10506           Idx[1] = NewIdx;
10507           Instruction *NewGEP =
10508             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10509           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10510           // The NewGEP must be pointer typed, so must the old one -> BitCast
10511           return new BitCastInst(NewGEP, GEP.getType());
10512         }
10513       }
10514     }
10515   }
10516
10517   return 0;
10518 }
10519
10520 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10521   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10522   if (AI.isArrayAllocation()) {  // Check C != 1
10523     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10524       const Type *NewTy = 
10525         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10526       AllocationInst *New = 0;
10527
10528       // Create and insert the replacement instruction...
10529       if (isa<MallocInst>(AI))
10530         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10531       else {
10532         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10533         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10534       }
10535
10536       InsertNewInstBefore(New, AI);
10537
10538       // Scan to the end of the allocation instructions, to skip over a block of
10539       // allocas if possible...
10540       //
10541       BasicBlock::iterator It = New;
10542       while (isa<AllocationInst>(*It)) ++It;
10543
10544       // Now that I is pointing to the first non-allocation-inst in the block,
10545       // insert our getelementptr instruction...
10546       //
10547       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10548       Value *Idx[2];
10549       Idx[0] = NullIdx;
10550       Idx[1] = NullIdx;
10551       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10552                                            New->getName()+".sub", It);
10553
10554       // Now make everything use the getelementptr instead of the original
10555       // allocation.
10556       return ReplaceInstUsesWith(AI, V);
10557     } else if (isa<UndefValue>(AI.getArraySize())) {
10558       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10559     }
10560   }
10561
10562   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10563   // Note that we only do this for alloca's, because malloc should allocate and
10564   // return a unique pointer, even for a zero byte allocation.
10565   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10566       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10567     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10568
10569   return 0;
10570 }
10571
10572 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10573   Value *Op = FI.getOperand(0);
10574
10575   // free undef -> unreachable.
10576   if (isa<UndefValue>(Op)) {
10577     // Insert a new store to null because we cannot modify the CFG here.
10578     new StoreInst(ConstantInt::getTrue(),
10579                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10580     return EraseInstFromFunction(FI);
10581   }
10582   
10583   // If we have 'free null' delete the instruction.  This can happen in stl code
10584   // when lots of inlining happens.
10585   if (isa<ConstantPointerNull>(Op))
10586     return EraseInstFromFunction(FI);
10587   
10588   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10589   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10590     FI.setOperand(0, CI->getOperand(0));
10591     return &FI;
10592   }
10593   
10594   // Change free (gep X, 0,0,0,0) into free(X)
10595   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10596     if (GEPI->hasAllZeroIndices()) {
10597       AddToWorkList(GEPI);
10598       FI.setOperand(0, GEPI->getOperand(0));
10599       return &FI;
10600     }
10601   }
10602   
10603   // Change free(malloc) into nothing, if the malloc has a single use.
10604   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10605     if (MI->hasOneUse()) {
10606       EraseInstFromFunction(FI);
10607       return EraseInstFromFunction(*MI);
10608     }
10609
10610   return 0;
10611 }
10612
10613
10614 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10615 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10616                                         const TargetData *TD) {
10617   User *CI = cast<User>(LI.getOperand(0));
10618   Value *CastOp = CI->getOperand(0);
10619
10620   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10621     // Instead of loading constant c string, use corresponding integer value
10622     // directly if string length is small enough.
10623     std::string Str;
10624     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10625       unsigned len = Str.length();
10626       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10627       unsigned numBits = Ty->getPrimitiveSizeInBits();
10628       // Replace LI with immediate integer store.
10629       if ((numBits >> 3) == len + 1) {
10630         APInt StrVal(numBits, 0);
10631         APInt SingleChar(numBits, 0);
10632         if (TD->isLittleEndian()) {
10633           for (signed i = len-1; i >= 0; i--) {
10634             SingleChar = (uint64_t) Str[i];
10635             StrVal = (StrVal << 8) | SingleChar;
10636           }
10637         } else {
10638           for (unsigned i = 0; i < len; i++) {
10639             SingleChar = (uint64_t) Str[i];
10640             StrVal = (StrVal << 8) | SingleChar;
10641           }
10642           // Append NULL at the end.
10643           SingleChar = 0;
10644           StrVal = (StrVal << 8) | SingleChar;
10645         }
10646         Value *NL = ConstantInt::get(StrVal);
10647         return IC.ReplaceInstUsesWith(LI, NL);
10648       }
10649     }
10650   }
10651
10652   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10653   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10654     const Type *SrcPTy = SrcTy->getElementType();
10655
10656     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10657          isa<VectorType>(DestPTy)) {
10658       // If the source is an array, the code below will not succeed.  Check to
10659       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10660       // constants.
10661       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10662         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10663           if (ASrcTy->getNumElements() != 0) {
10664             Value *Idxs[2];
10665             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10666             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10667             SrcTy = cast<PointerType>(CastOp->getType());
10668             SrcPTy = SrcTy->getElementType();
10669           }
10670
10671       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10672             isa<VectorType>(SrcPTy)) &&
10673           // Do not allow turning this into a load of an integer, which is then
10674           // casted to a pointer, this pessimizes pointer analysis a lot.
10675           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10676           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10677                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10678
10679         // Okay, we are casting from one integer or pointer type to another of
10680         // the same size.  Instead of casting the pointer before the load, cast
10681         // the result of the loaded value.
10682         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10683                                                              CI->getName(),
10684                                                          LI.isVolatile()),LI);
10685         // Now cast the result of the load.
10686         return new BitCastInst(NewLoad, LI.getType());
10687       }
10688     }
10689   }
10690   return 0;
10691 }
10692
10693 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10694 /// from this value cannot trap.  If it is not obviously safe to load from the
10695 /// specified pointer, we do a quick local scan of the basic block containing
10696 /// ScanFrom, to determine if the address is already accessed.
10697 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10698   // If it is an alloca it is always safe to load from.
10699   if (isa<AllocaInst>(V)) return true;
10700
10701   // If it is a global variable it is mostly safe to load from.
10702   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10703     // Don't try to evaluate aliases.  External weak GV can be null.
10704     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10705
10706   // Otherwise, be a little bit agressive by scanning the local block where we
10707   // want to check to see if the pointer is already being loaded or stored
10708   // from/to.  If so, the previous load or store would have already trapped,
10709   // so there is no harm doing an extra load (also, CSE will later eliminate
10710   // the load entirely).
10711   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10712
10713   while (BBI != E) {
10714     --BBI;
10715
10716     // If we see a free or a call (which might do a free) the pointer could be
10717     // marked invalid.
10718     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10719       return false;
10720     
10721     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10722       if (LI->getOperand(0) == V) return true;
10723     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10724       if (SI->getOperand(1) == V) return true;
10725     }
10726
10727   }
10728   return false;
10729 }
10730
10731 /// equivalentAddressValues - Test if A and B will obviously have the same
10732 /// value. This includes recognizing that %t0 and %t1 will have the same
10733 /// value in code like this:
10734 ///   %t0 = getelementptr @a, 0, 3
10735 ///   store i32 0, i32* %t0
10736 ///   %t1 = getelementptr @a, 0, 3
10737 ///   %t2 = load i32* %t1
10738 ///
10739 static bool equivalentAddressValues(Value *A, Value *B) {
10740   // Test if the values are trivially equivalent.
10741   if (A == B) return true;
10742
10743   // Test if the values come form identical arithmetic instructions.
10744   if (isa<BinaryOperator>(A) ||
10745       isa<CastInst>(A) ||
10746       isa<PHINode>(A) ||
10747       isa<GetElementPtrInst>(A))
10748     if (Instruction *BI = dyn_cast<Instruction>(B))
10749       if (cast<Instruction>(A)->isIdenticalTo(BI))
10750         return true;
10751
10752   // Otherwise they may not be equivalent.
10753   return false;
10754 }
10755
10756 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10757   Value *Op = LI.getOperand(0);
10758
10759   // Attempt to improve the alignment.
10760   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10761   if (KnownAlign >
10762       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10763                                 LI.getAlignment()))
10764     LI.setAlignment(KnownAlign);
10765
10766   // load (cast X) --> cast (load X) iff safe
10767   if (isa<CastInst>(Op))
10768     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10769       return Res;
10770
10771   // None of the following transforms are legal for volatile loads.
10772   if (LI.isVolatile()) return 0;
10773   
10774   // Do really simple store-to-load forwarding and load CSE, to catch cases
10775   // where there are several consequtive memory accesses to the same location,
10776   // separated by a few arithmetic operations.
10777   BasicBlock::iterator BBI = &LI;
10778   for (unsigned ScanInsts = 6; BBI != LI.getParent()->begin() && ScanInsts;
10779        --ScanInsts) {
10780     --BBI;
10781     
10782     if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10783       if (equivalentAddressValues(SI->getOperand(1), LI.getOperand(0)))
10784         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10785     } else if (LoadInst *LIB = dyn_cast<LoadInst>(BBI)) {
10786       if (equivalentAddressValues(LIB->getOperand(0), LI.getOperand(0)))
10787         return ReplaceInstUsesWith(LI, LIB);
10788     }
10789
10790     // Don't skip over things that can modify memory.
10791     if (BBI->mayWriteToMemory())
10792       break;
10793   }
10794
10795   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10796     const Value *GEPI0 = GEPI->getOperand(0);
10797     // TODO: Consider a target hook for valid address spaces for this xform.
10798     if (isa<ConstantPointerNull>(GEPI0) &&
10799         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10800       // Insert a new store to null instruction before the load to indicate
10801       // that this code is not reachable.  We do this instead of inserting
10802       // an unreachable instruction directly because we cannot modify the
10803       // CFG.
10804       new StoreInst(UndefValue::get(LI.getType()),
10805                     Constant::getNullValue(Op->getType()), &LI);
10806       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10807     }
10808   } 
10809
10810   if (Constant *C = dyn_cast<Constant>(Op)) {
10811     // load null/undef -> undef
10812     // TODO: Consider a target hook for valid address spaces for this xform.
10813     if (isa<UndefValue>(C) || (C->isNullValue() && 
10814         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10815       // Insert a new store to null instruction before the load to indicate that
10816       // this code is not reachable.  We do this instead of inserting an
10817       // unreachable instruction directly because we cannot modify the CFG.
10818       new StoreInst(UndefValue::get(LI.getType()),
10819                     Constant::getNullValue(Op->getType()), &LI);
10820       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10821     }
10822
10823     // Instcombine load (constant global) into the value loaded.
10824     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10825       if (GV->isConstant() && !GV->isDeclaration())
10826         return ReplaceInstUsesWith(LI, GV->getInitializer());
10827
10828     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10829     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10830       if (CE->getOpcode() == Instruction::GetElementPtr) {
10831         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10832           if (GV->isConstant() && !GV->isDeclaration())
10833             if (Constant *V = 
10834                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10835               return ReplaceInstUsesWith(LI, V);
10836         if (CE->getOperand(0)->isNullValue()) {
10837           // Insert a new store to null instruction before the load to indicate
10838           // that this code is not reachable.  We do this instead of inserting
10839           // an unreachable instruction directly because we cannot modify the
10840           // CFG.
10841           new StoreInst(UndefValue::get(LI.getType()),
10842                         Constant::getNullValue(Op->getType()), &LI);
10843           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10844         }
10845
10846       } else if (CE->isCast()) {
10847         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10848           return Res;
10849       }
10850     }
10851   }
10852     
10853   // If this load comes from anywhere in a constant global, and if the global
10854   // is all undef or zero, we know what it loads.
10855   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
10856     if (GV->isConstant() && GV->hasInitializer()) {
10857       if (GV->getInitializer()->isNullValue())
10858         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10859       else if (isa<UndefValue>(GV->getInitializer()))
10860         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10861     }
10862   }
10863
10864   if (Op->hasOneUse()) {
10865     // Change select and PHI nodes to select values instead of addresses: this
10866     // helps alias analysis out a lot, allows many others simplifications, and
10867     // exposes redundancy in the code.
10868     //
10869     // Note that we cannot do the transformation unless we know that the
10870     // introduced loads cannot trap!  Something like this is valid as long as
10871     // the condition is always false: load (select bool %C, int* null, int* %G),
10872     // but it would not be valid if we transformed it to load from null
10873     // unconditionally.
10874     //
10875     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10876       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10877       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10878           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10879         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10880                                      SI->getOperand(1)->getName()+".val"), LI);
10881         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10882                                      SI->getOperand(2)->getName()+".val"), LI);
10883         return SelectInst::Create(SI->getCondition(), V1, V2);
10884       }
10885
10886       // load (select (cond, null, P)) -> load P
10887       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10888         if (C->isNullValue()) {
10889           LI.setOperand(0, SI->getOperand(2));
10890           return &LI;
10891         }
10892
10893       // load (select (cond, P, null)) -> load P
10894       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10895         if (C->isNullValue()) {
10896           LI.setOperand(0, SI->getOperand(1));
10897           return &LI;
10898         }
10899     }
10900   }
10901   return 0;
10902 }
10903
10904 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10905 /// when possible.
10906 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10907   User *CI = cast<User>(SI.getOperand(1));
10908   Value *CastOp = CI->getOperand(0);
10909
10910   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10911   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10912     const Type *SrcPTy = SrcTy->getElementType();
10913
10914     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10915       // If the source is an array, the code below will not succeed.  Check to
10916       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10917       // constants.
10918       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10919         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10920           if (ASrcTy->getNumElements() != 0) {
10921             Value* Idxs[2];
10922             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10923             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10924             SrcTy = cast<PointerType>(CastOp->getType());
10925             SrcPTy = SrcTy->getElementType();
10926           }
10927
10928       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10929           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10930                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10931
10932         // Okay, we are casting from one integer or pointer type to another of
10933         // the same size.  Instead of casting the pointer before 
10934         // the store, cast the value to be stored.
10935         Value *NewCast;
10936         Value *SIOp0 = SI.getOperand(0);
10937         Instruction::CastOps opcode = Instruction::BitCast;
10938         const Type* CastSrcTy = SIOp0->getType();
10939         const Type* CastDstTy = SrcPTy;
10940         if (isa<PointerType>(CastDstTy)) {
10941           if (CastSrcTy->isInteger())
10942             opcode = Instruction::IntToPtr;
10943         } else if (isa<IntegerType>(CastDstTy)) {
10944           if (isa<PointerType>(SIOp0->getType()))
10945             opcode = Instruction::PtrToInt;
10946         }
10947         if (Constant *C = dyn_cast<Constant>(SIOp0))
10948           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10949         else
10950           NewCast = IC.InsertNewInstBefore(
10951             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10952             SI);
10953         return new StoreInst(NewCast, CastOp);
10954       }
10955     }
10956   }
10957   return 0;
10958 }
10959
10960 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10961   Value *Val = SI.getOperand(0);
10962   Value *Ptr = SI.getOperand(1);
10963
10964   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10965     EraseInstFromFunction(SI);
10966     ++NumCombined;
10967     return 0;
10968   }
10969   
10970   // If the RHS is an alloca with a single use, zapify the store, making the
10971   // alloca dead.
10972   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10973     if (isa<AllocaInst>(Ptr)) {
10974       EraseInstFromFunction(SI);
10975       ++NumCombined;
10976       return 0;
10977     }
10978     
10979     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10980       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10981           GEP->getOperand(0)->hasOneUse()) {
10982         EraseInstFromFunction(SI);
10983         ++NumCombined;
10984         return 0;
10985       }
10986   }
10987
10988   // Attempt to improve the alignment.
10989   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10990   if (KnownAlign >
10991       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10992                                 SI.getAlignment()))
10993     SI.setAlignment(KnownAlign);
10994
10995   // Do really simple DSE, to catch cases where there are several consequtive
10996   // stores to the same location, separated by a few arithmetic operations. This
10997   // situation often occurs with bitfield accesses.
10998   BasicBlock::iterator BBI = &SI;
10999   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11000        --ScanInsts) {
11001     --BBI;
11002     
11003     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11004       // Prev store isn't volatile, and stores to the same location?
11005       if (!PrevSI->isVolatile() && equivalentAddressValues(PrevSI->getOperand(1),
11006           SI.getOperand(1))) {
11007         ++NumDeadStore;
11008         ++BBI;
11009         EraseInstFromFunction(*PrevSI);
11010         continue;
11011       }
11012       break;
11013     }
11014     
11015     // If this is a load, we have to stop.  However, if the loaded value is from
11016     // the pointer we're loading and is producing the pointer we're storing,
11017     // then *this* store is dead (X = load P; store X -> P).
11018     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11019       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11020           !SI.isVolatile()) {
11021         EraseInstFromFunction(SI);
11022         ++NumCombined;
11023         return 0;
11024       }
11025       // Otherwise, this is a load from some other location.  Stores before it
11026       // may not be dead.
11027       break;
11028     }
11029     
11030     // Don't skip over loads or things that can modify memory.
11031     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11032       break;
11033   }
11034   
11035   
11036   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11037
11038   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11039   if (isa<ConstantPointerNull>(Ptr)) {
11040     if (!isa<UndefValue>(Val)) {
11041       SI.setOperand(0, UndefValue::get(Val->getType()));
11042       if (Instruction *U = dyn_cast<Instruction>(Val))
11043         AddToWorkList(U);  // Dropped a use.
11044       ++NumCombined;
11045     }
11046     return 0;  // Do not modify these!
11047   }
11048
11049   // store undef, Ptr -> noop
11050   if (isa<UndefValue>(Val)) {
11051     EraseInstFromFunction(SI);
11052     ++NumCombined;
11053     return 0;
11054   }
11055
11056   // If the pointer destination is a cast, see if we can fold the cast into the
11057   // source instead.
11058   if (isa<CastInst>(Ptr))
11059     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11060       return Res;
11061   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11062     if (CE->isCast())
11063       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11064         return Res;
11065
11066   
11067   // If this store is the last instruction in the basic block, and if the block
11068   // ends with an unconditional branch, try to move it to the successor block.
11069   BBI = &SI; ++BBI;
11070   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11071     if (BI->isUnconditional())
11072       if (SimplifyStoreAtEndOfBlock(SI))
11073         return 0;  // xform done!
11074   
11075   return 0;
11076 }
11077
11078 /// SimplifyStoreAtEndOfBlock - Turn things like:
11079 ///   if () { *P = v1; } else { *P = v2 }
11080 /// into a phi node with a store in the successor.
11081 ///
11082 /// Simplify things like:
11083 ///   *P = v1; if () { *P = v2; }
11084 /// into a phi node with a store in the successor.
11085 ///
11086 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11087   BasicBlock *StoreBB = SI.getParent();
11088   
11089   // Check to see if the successor block has exactly two incoming edges.  If
11090   // so, see if the other predecessor contains a store to the same location.
11091   // if so, insert a PHI node (if needed) and move the stores down.
11092   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11093   
11094   // Determine whether Dest has exactly two predecessors and, if so, compute
11095   // the other predecessor.
11096   pred_iterator PI = pred_begin(DestBB);
11097   BasicBlock *OtherBB = 0;
11098   if (*PI != StoreBB)
11099     OtherBB = *PI;
11100   ++PI;
11101   if (PI == pred_end(DestBB))
11102     return false;
11103   
11104   if (*PI != StoreBB) {
11105     if (OtherBB)
11106       return false;
11107     OtherBB = *PI;
11108   }
11109   if (++PI != pred_end(DestBB))
11110     return false;
11111
11112   // Bail out if all the relevant blocks aren't distinct (this can happen,
11113   // for example, if SI is in an infinite loop)
11114   if (StoreBB == DestBB || OtherBB == DestBB)
11115     return false;
11116
11117   // Verify that the other block ends in a branch and is not otherwise empty.
11118   BasicBlock::iterator BBI = OtherBB->getTerminator();
11119   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11120   if (!OtherBr || BBI == OtherBB->begin())
11121     return false;
11122   
11123   // If the other block ends in an unconditional branch, check for the 'if then
11124   // else' case.  there is an instruction before the branch.
11125   StoreInst *OtherStore = 0;
11126   if (OtherBr->isUnconditional()) {
11127     // If this isn't a store, or isn't a store to the same location, bail out.
11128     --BBI;
11129     OtherStore = dyn_cast<StoreInst>(BBI);
11130     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11131       return false;
11132   } else {
11133     // Otherwise, the other block ended with a conditional branch. If one of the
11134     // destinations is StoreBB, then we have the if/then case.
11135     if (OtherBr->getSuccessor(0) != StoreBB && 
11136         OtherBr->getSuccessor(1) != StoreBB)
11137       return false;
11138     
11139     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11140     // if/then triangle.  See if there is a store to the same ptr as SI that
11141     // lives in OtherBB.
11142     for (;; --BBI) {
11143       // Check to see if we find the matching store.
11144       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11145         if (OtherStore->getOperand(1) != SI.getOperand(1))
11146           return false;
11147         break;
11148       }
11149       // If we find something that may be using or overwriting the stored
11150       // value, or if we run out of instructions, we can't do the xform.
11151       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11152           BBI == OtherBB->begin())
11153         return false;
11154     }
11155     
11156     // In order to eliminate the store in OtherBr, we have to
11157     // make sure nothing reads or overwrites the stored value in
11158     // StoreBB.
11159     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11160       // FIXME: This should really be AA driven.
11161       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11162         return false;
11163     }
11164   }
11165   
11166   // Insert a PHI node now if we need it.
11167   Value *MergedVal = OtherStore->getOperand(0);
11168   if (MergedVal != SI.getOperand(0)) {
11169     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11170     PN->reserveOperandSpace(2);
11171     PN->addIncoming(SI.getOperand(0), SI.getParent());
11172     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11173     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11174   }
11175   
11176   // Advance to a place where it is safe to insert the new store and
11177   // insert it.
11178   BBI = DestBB->getFirstNonPHI();
11179   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11180                                     OtherStore->isVolatile()), *BBI);
11181   
11182   // Nuke the old stores.
11183   EraseInstFromFunction(SI);
11184   EraseInstFromFunction(*OtherStore);
11185   ++NumCombined;
11186   return true;
11187 }
11188
11189
11190 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11191   // Change br (not X), label True, label False to: br X, label False, True
11192   Value *X = 0;
11193   BasicBlock *TrueDest;
11194   BasicBlock *FalseDest;
11195   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11196       !isa<Constant>(X)) {
11197     // Swap Destinations and condition...
11198     BI.setCondition(X);
11199     BI.setSuccessor(0, FalseDest);
11200     BI.setSuccessor(1, TrueDest);
11201     return &BI;
11202   }
11203
11204   // Cannonicalize fcmp_one -> fcmp_oeq
11205   FCmpInst::Predicate FPred; Value *Y;
11206   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11207                              TrueDest, FalseDest)))
11208     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11209          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11210       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11211       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11212       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11213       NewSCC->takeName(I);
11214       // Swap Destinations and condition...
11215       BI.setCondition(NewSCC);
11216       BI.setSuccessor(0, FalseDest);
11217       BI.setSuccessor(1, TrueDest);
11218       RemoveFromWorkList(I);
11219       I->eraseFromParent();
11220       AddToWorkList(NewSCC);
11221       return &BI;
11222     }
11223
11224   // Cannonicalize icmp_ne -> icmp_eq
11225   ICmpInst::Predicate IPred;
11226   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11227                       TrueDest, FalseDest)))
11228     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11229          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11230          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11231       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11232       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11233       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11234       NewSCC->takeName(I);
11235       // Swap Destinations and condition...
11236       BI.setCondition(NewSCC);
11237       BI.setSuccessor(0, FalseDest);
11238       BI.setSuccessor(1, TrueDest);
11239       RemoveFromWorkList(I);
11240       I->eraseFromParent();;
11241       AddToWorkList(NewSCC);
11242       return &BI;
11243     }
11244
11245   return 0;
11246 }
11247
11248 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11249   Value *Cond = SI.getCondition();
11250   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11251     if (I->getOpcode() == Instruction::Add)
11252       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11253         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11254         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11255           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11256                                                 AddRHS));
11257         SI.setOperand(0, I->getOperand(0));
11258         AddToWorkList(I);
11259         return &SI;
11260       }
11261   }
11262   return 0;
11263 }
11264
11265 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11266   Value *Agg = EV.getAggregateOperand();
11267
11268   if (!EV.hasIndices())
11269     return ReplaceInstUsesWith(EV, Agg);
11270
11271   if (Constant *C = dyn_cast<Constant>(Agg)) {
11272     if (isa<UndefValue>(C))
11273       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11274       
11275     if (isa<ConstantAggregateZero>(C))
11276       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11277
11278     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11279       // Extract the element indexed by the first index out of the constant
11280       Value *V = C->getOperand(*EV.idx_begin());
11281       if (EV.getNumIndices() > 1)
11282         // Extract the remaining indices out of the constant indexed by the
11283         // first index
11284         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11285       else
11286         return ReplaceInstUsesWith(EV, V);
11287     }
11288     return 0; // Can't handle other constants
11289   } 
11290   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11291     // We're extracting from an insertvalue instruction, compare the indices
11292     const unsigned *exti, *exte, *insi, *inse;
11293     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11294          exte = EV.idx_end(), inse = IV->idx_end();
11295          exti != exte && insi != inse;
11296          ++exti, ++insi) {
11297       if (*insi != *exti)
11298         // The insert and extract both reference distinctly different elements.
11299         // This means the extract is not influenced by the insert, and we can
11300         // replace the aggregate operand of the extract with the aggregate
11301         // operand of the insert. i.e., replace
11302         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11303         // %E = extractvalue { i32, { i32 } } %I, 0
11304         // with
11305         // %E = extractvalue { i32, { i32 } } %A, 0
11306         return ExtractValueInst::Create(IV->getAggregateOperand(),
11307                                         EV.idx_begin(), EV.idx_end());
11308     }
11309     if (exti == exte && insi == inse)
11310       // Both iterators are at the end: Index lists are identical. Replace
11311       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11312       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11313       // with "i32 42"
11314       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11315     if (exti == exte) {
11316       // The extract list is a prefix of the insert list. i.e. replace
11317       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11318       // %E = extractvalue { i32, { i32 } } %I, 1
11319       // with
11320       // %X = extractvalue { i32, { i32 } } %A, 1
11321       // %E = insertvalue { i32 } %X, i32 42, 0
11322       // by switching the order of the insert and extract (though the
11323       // insertvalue should be left in, since it may have other uses).
11324       Value *NewEV = InsertNewInstBefore(
11325         ExtractValueInst::Create(IV->getAggregateOperand(),
11326                                  EV.idx_begin(), EV.idx_end()),
11327         EV);
11328       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11329                                      insi, inse);
11330     }
11331     if (insi == inse)
11332       // The insert list is a prefix of the extract list
11333       // We can simply remove the common indices from the extract and make it
11334       // operate on the inserted value instead of the insertvalue result.
11335       // i.e., replace
11336       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11337       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11338       // with
11339       // %E extractvalue { i32 } { i32 42 }, 0
11340       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11341                                       exti, exte);
11342   }
11343   // Can't simplify extracts from other values. Note that nested extracts are
11344   // already simplified implicitely by the above (extract ( extract (insert) )
11345   // will be translated into extract ( insert ( extract ) ) first and then just
11346   // the value inserted, if appropriate).
11347   return 0;
11348 }
11349
11350 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11351 /// is to leave as a vector operation.
11352 static bool CheapToScalarize(Value *V, bool isConstant) {
11353   if (isa<ConstantAggregateZero>(V)) 
11354     return true;
11355   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11356     if (isConstant) return true;
11357     // If all elts are the same, we can extract.
11358     Constant *Op0 = C->getOperand(0);
11359     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11360       if (C->getOperand(i) != Op0)
11361         return false;
11362     return true;
11363   }
11364   Instruction *I = dyn_cast<Instruction>(V);
11365   if (!I) return false;
11366   
11367   // Insert element gets simplified to the inserted element or is deleted if
11368   // this is constant idx extract element and its a constant idx insertelt.
11369   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11370       isa<ConstantInt>(I->getOperand(2)))
11371     return true;
11372   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11373     return true;
11374   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11375     if (BO->hasOneUse() &&
11376         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11377          CheapToScalarize(BO->getOperand(1), isConstant)))
11378       return true;
11379   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11380     if (CI->hasOneUse() &&
11381         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11382          CheapToScalarize(CI->getOperand(1), isConstant)))
11383       return true;
11384   
11385   return false;
11386 }
11387
11388 /// Read and decode a shufflevector mask.
11389 ///
11390 /// It turns undef elements into values that are larger than the number of
11391 /// elements in the input.
11392 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11393   unsigned NElts = SVI->getType()->getNumElements();
11394   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11395     return std::vector<unsigned>(NElts, 0);
11396   if (isa<UndefValue>(SVI->getOperand(2)))
11397     return std::vector<unsigned>(NElts, 2*NElts);
11398
11399   std::vector<unsigned> Result;
11400   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11401   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11402     if (isa<UndefValue>(*i))
11403       Result.push_back(NElts*2);  // undef -> 8
11404     else
11405       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11406   return Result;
11407 }
11408
11409 /// FindScalarElement - Given a vector and an element number, see if the scalar
11410 /// value is already around as a register, for example if it were inserted then
11411 /// extracted from the vector.
11412 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11413   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11414   const VectorType *PTy = cast<VectorType>(V->getType());
11415   unsigned Width = PTy->getNumElements();
11416   if (EltNo >= Width)  // Out of range access.
11417     return UndefValue::get(PTy->getElementType());
11418   
11419   if (isa<UndefValue>(V))
11420     return UndefValue::get(PTy->getElementType());
11421   else if (isa<ConstantAggregateZero>(V))
11422     return Constant::getNullValue(PTy->getElementType());
11423   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11424     return CP->getOperand(EltNo);
11425   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11426     // If this is an insert to a variable element, we don't know what it is.
11427     if (!isa<ConstantInt>(III->getOperand(2))) 
11428       return 0;
11429     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11430     
11431     // If this is an insert to the element we are looking for, return the
11432     // inserted value.
11433     if (EltNo == IIElt) 
11434       return III->getOperand(1);
11435     
11436     // Otherwise, the insertelement doesn't modify the value, recurse on its
11437     // vector input.
11438     return FindScalarElement(III->getOperand(0), EltNo);
11439   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11440     unsigned LHSWidth =
11441       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11442     unsigned InEl = getShuffleMask(SVI)[EltNo];
11443     if (InEl < LHSWidth)
11444       return FindScalarElement(SVI->getOperand(0), InEl);
11445     else if (InEl < LHSWidth*2)
11446       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11447     else
11448       return UndefValue::get(PTy->getElementType());
11449   }
11450   
11451   // Otherwise, we don't know.
11452   return 0;
11453 }
11454
11455 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11456   // If vector val is undef, replace extract with scalar undef.
11457   if (isa<UndefValue>(EI.getOperand(0)))
11458     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11459
11460   // If vector val is constant 0, replace extract with scalar 0.
11461   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11462     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11463   
11464   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11465     // If vector val is constant with all elements the same, replace EI with
11466     // that element. When the elements are not identical, we cannot replace yet
11467     // (we do that below, but only when the index is constant).
11468     Constant *op0 = C->getOperand(0);
11469     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11470       if (C->getOperand(i) != op0) {
11471         op0 = 0; 
11472         break;
11473       }
11474     if (op0)
11475       return ReplaceInstUsesWith(EI, op0);
11476   }
11477   
11478   // If extracting a specified index from the vector, see if we can recursively
11479   // find a previously computed scalar that was inserted into the vector.
11480   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11481     unsigned IndexVal = IdxC->getZExtValue();
11482     unsigned VectorWidth = 
11483       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11484       
11485     // If this is extracting an invalid index, turn this into undef, to avoid
11486     // crashing the code below.
11487     if (IndexVal >= VectorWidth)
11488       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11489     
11490     // This instruction only demands the single element from the input vector.
11491     // If the input vector has a single use, simplify it based on this use
11492     // property.
11493     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11494       uint64_t UndefElts;
11495       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11496                                                 1 << IndexVal,
11497                                                 UndefElts)) {
11498         EI.setOperand(0, V);
11499         return &EI;
11500       }
11501     }
11502     
11503     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11504       return ReplaceInstUsesWith(EI, Elt);
11505     
11506     // If the this extractelement is directly using a bitcast from a vector of
11507     // the same number of elements, see if we can find the source element from
11508     // it.  In this case, we will end up needing to bitcast the scalars.
11509     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11510       if (const VectorType *VT = 
11511               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11512         if (VT->getNumElements() == VectorWidth)
11513           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11514             return new BitCastInst(Elt, EI.getType());
11515     }
11516   }
11517   
11518   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11519     if (I->hasOneUse()) {
11520       // Push extractelement into predecessor operation if legal and
11521       // profitable to do so
11522       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11523         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11524         if (CheapToScalarize(BO, isConstantElt)) {
11525           ExtractElementInst *newEI0 = 
11526             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11527                                    EI.getName()+".lhs");
11528           ExtractElementInst *newEI1 =
11529             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11530                                    EI.getName()+".rhs");
11531           InsertNewInstBefore(newEI0, EI);
11532           InsertNewInstBefore(newEI1, EI);
11533           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11534         }
11535       } else if (isa<LoadInst>(I)) {
11536         unsigned AS = 
11537           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11538         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11539                                          PointerType::get(EI.getType(), AS),EI);
11540         GetElementPtrInst *GEP =
11541           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11542         InsertNewInstBefore(GEP, EI);
11543         return new LoadInst(GEP);
11544       }
11545     }
11546     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11547       // Extracting the inserted element?
11548       if (IE->getOperand(2) == EI.getOperand(1))
11549         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11550       // If the inserted and extracted elements are constants, they must not
11551       // be the same value, extract from the pre-inserted value instead.
11552       if (isa<Constant>(IE->getOperand(2)) &&
11553           isa<Constant>(EI.getOperand(1))) {
11554         AddUsesToWorkList(EI);
11555         EI.setOperand(0, IE->getOperand(0));
11556         return &EI;
11557       }
11558     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11559       // If this is extracting an element from a shufflevector, figure out where
11560       // it came from and extract from the appropriate input element instead.
11561       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11562         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11563         Value *Src;
11564         unsigned LHSWidth =
11565           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11566
11567         if (SrcIdx < LHSWidth)
11568           Src = SVI->getOperand(0);
11569         else if (SrcIdx < LHSWidth*2) {
11570           SrcIdx -= LHSWidth;
11571           Src = SVI->getOperand(1);
11572         } else {
11573           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11574         }
11575         return new ExtractElementInst(Src, SrcIdx);
11576       }
11577     }
11578   }
11579   return 0;
11580 }
11581
11582 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11583 /// elements from either LHS or RHS, return the shuffle mask and true. 
11584 /// Otherwise, return false.
11585 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11586                                          std::vector<Constant*> &Mask) {
11587   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11588          "Invalid CollectSingleShuffleElements");
11589   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11590
11591   if (isa<UndefValue>(V)) {
11592     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11593     return true;
11594   } else if (V == LHS) {
11595     for (unsigned i = 0; i != NumElts; ++i)
11596       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11597     return true;
11598   } else if (V == RHS) {
11599     for (unsigned i = 0; i != NumElts; ++i)
11600       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11601     return true;
11602   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11603     // If this is an insert of an extract from some other vector, include it.
11604     Value *VecOp    = IEI->getOperand(0);
11605     Value *ScalarOp = IEI->getOperand(1);
11606     Value *IdxOp    = IEI->getOperand(2);
11607     
11608     if (!isa<ConstantInt>(IdxOp))
11609       return false;
11610     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11611     
11612     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11613       // Okay, we can handle this if the vector we are insertinting into is
11614       // transitively ok.
11615       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11616         // If so, update the mask to reflect the inserted undef.
11617         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11618         return true;
11619       }      
11620     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11621       if (isa<ConstantInt>(EI->getOperand(1)) &&
11622           EI->getOperand(0)->getType() == V->getType()) {
11623         unsigned ExtractedIdx =
11624           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11625         
11626         // This must be extracting from either LHS or RHS.
11627         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11628           // Okay, we can handle this if the vector we are insertinting into is
11629           // transitively ok.
11630           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11631             // If so, update the mask to reflect the inserted value.
11632             if (EI->getOperand(0) == LHS) {
11633               Mask[InsertedIdx % NumElts] = 
11634                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11635             } else {
11636               assert(EI->getOperand(0) == RHS);
11637               Mask[InsertedIdx % NumElts] = 
11638                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11639               
11640             }
11641             return true;
11642           }
11643         }
11644       }
11645     }
11646   }
11647   // TODO: Handle shufflevector here!
11648   
11649   return false;
11650 }
11651
11652 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11653 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11654 /// that computes V and the LHS value of the shuffle.
11655 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11656                                      Value *&RHS) {
11657   assert(isa<VectorType>(V->getType()) && 
11658          (RHS == 0 || V->getType() == RHS->getType()) &&
11659          "Invalid shuffle!");
11660   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11661
11662   if (isa<UndefValue>(V)) {
11663     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11664     return V;
11665   } else if (isa<ConstantAggregateZero>(V)) {
11666     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11667     return V;
11668   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11669     // If this is an insert of an extract from some other vector, include it.
11670     Value *VecOp    = IEI->getOperand(0);
11671     Value *ScalarOp = IEI->getOperand(1);
11672     Value *IdxOp    = IEI->getOperand(2);
11673     
11674     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11675       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11676           EI->getOperand(0)->getType() == V->getType()) {
11677         unsigned ExtractedIdx =
11678           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11679         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11680         
11681         // Either the extracted from or inserted into vector must be RHSVec,
11682         // otherwise we'd end up with a shuffle of three inputs.
11683         if (EI->getOperand(0) == RHS || RHS == 0) {
11684           RHS = EI->getOperand(0);
11685           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11686           Mask[InsertedIdx % NumElts] = 
11687             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11688           return V;
11689         }
11690         
11691         if (VecOp == RHS) {
11692           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11693           // Everything but the extracted element is replaced with the RHS.
11694           for (unsigned i = 0; i != NumElts; ++i) {
11695             if (i != InsertedIdx)
11696               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11697           }
11698           return V;
11699         }
11700         
11701         // If this insertelement is a chain that comes from exactly these two
11702         // vectors, return the vector and the effective shuffle.
11703         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11704           return EI->getOperand(0);
11705         
11706       }
11707     }
11708   }
11709   // TODO: Handle shufflevector here!
11710   
11711   // Otherwise, can't do anything fancy.  Return an identity vector.
11712   for (unsigned i = 0; i != NumElts; ++i)
11713     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11714   return V;
11715 }
11716
11717 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11718   Value *VecOp    = IE.getOperand(0);
11719   Value *ScalarOp = IE.getOperand(1);
11720   Value *IdxOp    = IE.getOperand(2);
11721   
11722   // Inserting an undef or into an undefined place, remove this.
11723   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11724     ReplaceInstUsesWith(IE, VecOp);
11725   
11726   // If the inserted element was extracted from some other vector, and if the 
11727   // indexes are constant, try to turn this into a shufflevector operation.
11728   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11729     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11730         EI->getOperand(0)->getType() == IE.getType()) {
11731       unsigned NumVectorElts = IE.getType()->getNumElements();
11732       unsigned ExtractedIdx =
11733         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11734       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11735       
11736       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11737         return ReplaceInstUsesWith(IE, VecOp);
11738       
11739       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11740         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11741       
11742       // If we are extracting a value from a vector, then inserting it right
11743       // back into the same place, just use the input vector.
11744       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11745         return ReplaceInstUsesWith(IE, VecOp);      
11746       
11747       // We could theoretically do this for ANY input.  However, doing so could
11748       // turn chains of insertelement instructions into a chain of shufflevector
11749       // instructions, and right now we do not merge shufflevectors.  As such,
11750       // only do this in a situation where it is clear that there is benefit.
11751       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11752         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11753         // the values of VecOp, except then one read from EIOp0.
11754         // Build a new shuffle mask.
11755         std::vector<Constant*> Mask;
11756         if (isa<UndefValue>(VecOp))
11757           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11758         else {
11759           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11760           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11761                                                        NumVectorElts));
11762         } 
11763         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11764         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11765                                      ConstantVector::get(Mask));
11766       }
11767       
11768       // If this insertelement isn't used by some other insertelement, turn it
11769       // (and any insertelements it points to), into one big shuffle.
11770       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11771         std::vector<Constant*> Mask;
11772         Value *RHS = 0;
11773         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11774         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11775         // We now have a shuffle of LHS, RHS, Mask.
11776         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11777       }
11778     }
11779   }
11780
11781   return 0;
11782 }
11783
11784
11785 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11786   Value *LHS = SVI.getOperand(0);
11787   Value *RHS = SVI.getOperand(1);
11788   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11789
11790   bool MadeChange = false;
11791
11792   // Undefined shuffle mask -> undefined value.
11793   if (isa<UndefValue>(SVI.getOperand(2)))
11794     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11795
11796   uint64_t UndefElts;
11797   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11798
11799   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11800     return 0;
11801
11802   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11803   if (VWidth <= 64 &&
11804       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11805     LHS = SVI.getOperand(0);
11806     RHS = SVI.getOperand(1);
11807     MadeChange = true;
11808   }
11809   
11810   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11811   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11812   if (LHS == RHS || isa<UndefValue>(LHS)) {
11813     if (isa<UndefValue>(LHS) && LHS == RHS) {
11814       // shuffle(undef,undef,mask) -> undef.
11815       return ReplaceInstUsesWith(SVI, LHS);
11816     }
11817     
11818     // Remap any references to RHS to use LHS.
11819     std::vector<Constant*> Elts;
11820     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11821       if (Mask[i] >= 2*e)
11822         Elts.push_back(UndefValue::get(Type::Int32Ty));
11823       else {
11824         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11825             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11826           Mask[i] = 2*e;     // Turn into undef.
11827           Elts.push_back(UndefValue::get(Type::Int32Ty));
11828         } else {
11829           Mask[i] = Mask[i] % e;  // Force to LHS.
11830           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11831         }
11832       }
11833     }
11834     SVI.setOperand(0, SVI.getOperand(1));
11835     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11836     SVI.setOperand(2, ConstantVector::get(Elts));
11837     LHS = SVI.getOperand(0);
11838     RHS = SVI.getOperand(1);
11839     MadeChange = true;
11840   }
11841   
11842   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11843   bool isLHSID = true, isRHSID = true;
11844     
11845   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11846     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11847     // Is this an identity shuffle of the LHS value?
11848     isLHSID &= (Mask[i] == i);
11849       
11850     // Is this an identity shuffle of the RHS value?
11851     isRHSID &= (Mask[i]-e == i);
11852   }
11853
11854   // Eliminate identity shuffles.
11855   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11856   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11857   
11858   // If the LHS is a shufflevector itself, see if we can combine it with this
11859   // one without producing an unusual shuffle.  Here we are really conservative:
11860   // we are absolutely afraid of producing a shuffle mask not in the input
11861   // program, because the code gen may not be smart enough to turn a merged
11862   // shuffle into two specific shuffles: it may produce worse code.  As such,
11863   // we only merge two shuffles if the result is one of the two input shuffle
11864   // masks.  In this case, merging the shuffles just removes one instruction,
11865   // which we know is safe.  This is good for things like turning:
11866   // (splat(splat)) -> splat.
11867   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11868     if (isa<UndefValue>(RHS)) {
11869       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11870
11871       std::vector<unsigned> NewMask;
11872       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11873         if (Mask[i] >= 2*e)
11874           NewMask.push_back(2*e);
11875         else
11876           NewMask.push_back(LHSMask[Mask[i]]);
11877       
11878       // If the result mask is equal to the src shuffle or this shuffle mask, do
11879       // the replacement.
11880       if (NewMask == LHSMask || NewMask == Mask) {
11881         std::vector<Constant*> Elts;
11882         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11883           if (NewMask[i] >= e*2) {
11884             Elts.push_back(UndefValue::get(Type::Int32Ty));
11885           } else {
11886             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11887           }
11888         }
11889         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11890                                      LHSSVI->getOperand(1),
11891                                      ConstantVector::get(Elts));
11892       }
11893     }
11894   }
11895
11896   return MadeChange ? &SVI : 0;
11897 }
11898
11899
11900
11901
11902 /// TryToSinkInstruction - Try to move the specified instruction from its
11903 /// current block into the beginning of DestBlock, which can only happen if it's
11904 /// safe to move the instruction past all of the instructions between it and the
11905 /// end of its block.
11906 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11907   assert(I->hasOneUse() && "Invariants didn't hold!");
11908
11909   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11910   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11911     return false;
11912
11913   // Do not sink alloca instructions out of the entry block.
11914   if (isa<AllocaInst>(I) && I->getParent() ==
11915         &DestBlock->getParent()->getEntryBlock())
11916     return false;
11917
11918   // We can only sink load instructions if there is nothing between the load and
11919   // the end of block that could change the value.
11920   if (I->mayReadFromMemory()) {
11921     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11922          Scan != E; ++Scan)
11923       if (Scan->mayWriteToMemory())
11924         return false;
11925   }
11926
11927   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11928
11929   I->moveBefore(InsertPos);
11930   ++NumSunkInst;
11931   return true;
11932 }
11933
11934
11935 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11936 /// all reachable code to the worklist.
11937 ///
11938 /// This has a couple of tricks to make the code faster and more powerful.  In
11939 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11940 /// them to the worklist (this significantly speeds up instcombine on code where
11941 /// many instructions are dead or constant).  Additionally, if we find a branch
11942 /// whose condition is a known constant, we only visit the reachable successors.
11943 ///
11944 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11945                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11946                                        InstCombiner &IC,
11947                                        const TargetData *TD) {
11948   SmallVector<BasicBlock*, 256> Worklist;
11949   Worklist.push_back(BB);
11950
11951   while (!Worklist.empty()) {
11952     BB = Worklist.back();
11953     Worklist.pop_back();
11954     
11955     // We have now visited this block!  If we've already been here, ignore it.
11956     if (!Visited.insert(BB)) continue;
11957     
11958     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11959       Instruction *Inst = BBI++;
11960       
11961       // DCE instruction if trivially dead.
11962       if (isInstructionTriviallyDead(Inst)) {
11963         ++NumDeadInst;
11964         DOUT << "IC: DCE: " << *Inst;
11965         Inst->eraseFromParent();
11966         continue;
11967       }
11968       
11969       // ConstantProp instruction if trivially constant.
11970       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11971         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11972         Inst->replaceAllUsesWith(C);
11973         ++NumConstProp;
11974         Inst->eraseFromParent();
11975         continue;
11976       }
11977      
11978       IC.AddToWorkList(Inst);
11979     }
11980
11981     // Recursively visit successors.  If this is a branch or switch on a
11982     // constant, only visit the reachable successor.
11983     TerminatorInst *TI = BB->getTerminator();
11984     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11985       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11986         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11987         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11988         Worklist.push_back(ReachableBB);
11989         continue;
11990       }
11991     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11992       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11993         // See if this is an explicit destination.
11994         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11995           if (SI->getCaseValue(i) == Cond) {
11996             BasicBlock *ReachableBB = SI->getSuccessor(i);
11997             Worklist.push_back(ReachableBB);
11998             continue;
11999           }
12000         
12001         // Otherwise it is the default destination.
12002         Worklist.push_back(SI->getSuccessor(0));
12003         continue;
12004       }
12005     }
12006     
12007     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12008       Worklist.push_back(TI->getSuccessor(i));
12009   }
12010 }
12011
12012 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12013   bool Changed = false;
12014   TD = &getAnalysis<TargetData>();
12015   
12016   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12017              << F.getNameStr() << "\n");
12018
12019   {
12020     // Do a depth-first traversal of the function, populate the worklist with
12021     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12022     // track of which blocks we visit.
12023     SmallPtrSet<BasicBlock*, 64> Visited;
12024     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12025
12026     // Do a quick scan over the function.  If we find any blocks that are
12027     // unreachable, remove any instructions inside of them.  This prevents
12028     // the instcombine code from having to deal with some bad special cases.
12029     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12030       if (!Visited.count(BB)) {
12031         Instruction *Term = BB->getTerminator();
12032         while (Term != BB->begin()) {   // Remove instrs bottom-up
12033           BasicBlock::iterator I = Term; --I;
12034
12035           DOUT << "IC: DCE: " << *I;
12036           ++NumDeadInst;
12037
12038           if (!I->use_empty())
12039             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12040           I->eraseFromParent();
12041         }
12042       }
12043   }
12044
12045   while (!Worklist.empty()) {
12046     Instruction *I = RemoveOneFromWorkList();
12047     if (I == 0) continue;  // skip null values.
12048
12049     // Check to see if we can DCE the instruction.
12050     if (isInstructionTriviallyDead(I)) {
12051       // Add operands to the worklist.
12052       if (I->getNumOperands() < 4)
12053         AddUsesToWorkList(*I);
12054       ++NumDeadInst;
12055
12056       DOUT << "IC: DCE: " << *I;
12057
12058       I->eraseFromParent();
12059       RemoveFromWorkList(I);
12060       continue;
12061     }
12062
12063     // Instruction isn't dead, see if we can constant propagate it.
12064     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12065       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12066
12067       // Add operands to the worklist.
12068       AddUsesToWorkList(*I);
12069       ReplaceInstUsesWith(*I, C);
12070
12071       ++NumConstProp;
12072       I->eraseFromParent();
12073       RemoveFromWorkList(I);
12074       continue;
12075     }
12076
12077     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12078       // See if we can constant fold its operands.
12079       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12080         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12081           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12082             i->set(NewC);
12083         }
12084       }
12085     }
12086
12087     // See if we can trivially sink this instruction to a successor basic block.
12088     if (I->hasOneUse()) {
12089       BasicBlock *BB = I->getParent();
12090       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12091       if (UserParent != BB) {
12092         bool UserIsSuccessor = false;
12093         // See if the user is one of our successors.
12094         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12095           if (*SI == UserParent) {
12096             UserIsSuccessor = true;
12097             break;
12098           }
12099
12100         // If the user is one of our immediate successors, and if that successor
12101         // only has us as a predecessors (we'd have to split the critical edge
12102         // otherwise), we can keep going.
12103         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12104             next(pred_begin(UserParent)) == pred_end(UserParent))
12105           // Okay, the CFG is simple enough, try to sink this instruction.
12106           Changed |= TryToSinkInstruction(I, UserParent);
12107       }
12108     }
12109
12110     // Now that we have an instruction, try combining it to simplify it...
12111 #ifndef NDEBUG
12112     std::string OrigI;
12113 #endif
12114     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12115     if (Instruction *Result = visit(*I)) {
12116       ++NumCombined;
12117       // Should we replace the old instruction with a new one?
12118       if (Result != I) {
12119         DOUT << "IC: Old = " << *I
12120              << "    New = " << *Result;
12121
12122         // Everything uses the new instruction now.
12123         I->replaceAllUsesWith(Result);
12124
12125         // Push the new instruction and any users onto the worklist.
12126         AddToWorkList(Result);
12127         AddUsersToWorkList(*Result);
12128
12129         // Move the name to the new instruction first.
12130         Result->takeName(I);
12131
12132         // Insert the new instruction into the basic block...
12133         BasicBlock *InstParent = I->getParent();
12134         BasicBlock::iterator InsertPos = I;
12135
12136         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12137           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12138             ++InsertPos;
12139
12140         InstParent->getInstList().insert(InsertPos, Result);
12141
12142         // Make sure that we reprocess all operands now that we reduced their
12143         // use counts.
12144         AddUsesToWorkList(*I);
12145
12146         // Instructions can end up on the worklist more than once.  Make sure
12147         // we do not process an instruction that has been deleted.
12148         RemoveFromWorkList(I);
12149
12150         // Erase the old instruction.
12151         InstParent->getInstList().erase(I);
12152       } else {
12153 #ifndef NDEBUG
12154         DOUT << "IC: Mod = " << OrigI
12155              << "    New = " << *I;
12156 #endif
12157
12158         // If the instruction was modified, it's possible that it is now dead.
12159         // if so, remove it.
12160         if (isInstructionTriviallyDead(I)) {
12161           // Make sure we process all operands now that we are reducing their
12162           // use counts.
12163           AddUsesToWorkList(*I);
12164
12165           // Instructions may end up in the worklist more than once.  Erase all
12166           // occurrences of this instruction.
12167           RemoveFromWorkList(I);
12168           I->eraseFromParent();
12169         } else {
12170           AddToWorkList(I);
12171           AddUsersToWorkList(*I);
12172         }
12173       }
12174       Changed = true;
12175     }
12176   }
12177
12178   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12179     
12180   // Do an explicit clear, this shrinks the map if needed.
12181   WorklistMap.clear();
12182   return Changed;
12183 }
12184
12185
12186 bool InstCombiner::runOnFunction(Function &F) {
12187   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12188   
12189   bool EverMadeChange = false;
12190
12191   // Iterate while there is work to do.
12192   unsigned Iteration = 0;
12193   while (DoOneIteration(F, Iteration++))
12194     EverMadeChange = true;
12195   return EverMadeChange;
12196 }
12197
12198 FunctionPass *llvm::createInstructionCombiningPass() {
12199   return new InstCombiner();
12200 }
12201
12202