Some minor cleanups to instcombine; no functionality change.
[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 *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *visitOr (BinaryOperator &I);
187     Instruction *visitXor(BinaryOperator &I);
188     Instruction *visitShl(BinaryOperator &I);
189     Instruction *visitAShr(BinaryOperator &I);
190     Instruction *visitLShr(BinaryOperator &I);
191     Instruction *commonShiftTransforms(BinaryOperator &I);
192     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
193                                       Constant *RHSC);
194     Instruction *visitFCmpInst(FCmpInst &I);
195     Instruction *visitICmpInst(ICmpInst &I);
196     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
197     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
198                                                 Instruction *LHS,
199                                                 ConstantInt *RHS);
200     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
201                                 ConstantInt *DivRHS);
202
203     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
204                              ICmpInst::Predicate Cond, Instruction &I);
205     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
206                                      BinaryOperator &I);
207     Instruction *commonCastTransforms(CastInst &CI);
208     Instruction *commonIntCastTransforms(CastInst &CI);
209     Instruction *commonPointerCastTransforms(CastInst &CI);
210     Instruction *visitTrunc(TruncInst &CI);
211     Instruction *visitZExt(ZExtInst &CI);
212     Instruction *visitSExt(SExtInst &CI);
213     Instruction *visitFPTrunc(FPTruncInst &CI);
214     Instruction *visitFPExt(CastInst &CI);
215     Instruction *visitFPToUI(FPToUIInst &FI);
216     Instruction *visitFPToSI(FPToSIInst &FI);
217     Instruction *visitUIToFP(CastInst &CI);
218     Instruction *visitSIToFP(CastInst &CI);
219     Instruction *visitPtrToInt(CastInst &CI);
220     Instruction *visitIntToPtr(IntToPtrInst &CI);
221     Instruction *visitBitCast(BitCastInst &CI);
222     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
223                                 Instruction *FI);
224     Instruction *visitSelectInst(SelectInst &SI);
225     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
226     Instruction *visitCallInst(CallInst &CI);
227     Instruction *visitInvokeInst(InvokeInst &II);
228     Instruction *visitPHINode(PHINode &PN);
229     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
230     Instruction *visitAllocationInst(AllocationInst &AI);
231     Instruction *visitFreeInst(FreeInst &FI);
232     Instruction *visitLoadInst(LoadInst &LI);
233     Instruction *visitStoreInst(StoreInst &SI);
234     Instruction *visitBranchInst(BranchInst &BI);
235     Instruction *visitSwitchInst(SwitchInst &SI);
236     Instruction *visitInsertElementInst(InsertElementInst &IE);
237     Instruction *visitExtractElementInst(ExtractElementInst &EI);
238     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
239     Instruction *visitExtractValueInst(ExtractValueInst &EV);
240
241     // visitInstruction - Specify what to return for unhandled instructions...
242     Instruction *visitInstruction(Instruction &I) { return 0; }
243
244   private:
245     Instruction *visitCallSite(CallSite CS);
246     bool transformConstExprCastCall(CallSite CS);
247     Instruction *transformCallThroughTrampoline(CallSite CS);
248     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
249                                    bool DoXform = true);
250     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
251
252   public:
253     // InsertNewInstBefore - insert an instruction New before instruction Old
254     // in the program.  Add the new instruction to the worklist.
255     //
256     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
257       assert(New && New->getParent() == 0 &&
258              "New instruction already inserted into a basic block!");
259       BasicBlock *BB = Old.getParent();
260       BB->getInstList().insert(&Old, New);  // Insert inst
261       AddToWorkList(New);
262       return New;
263     }
264
265     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
266     /// This also adds the cast to the worklist.  Finally, this returns the
267     /// cast.
268     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
269                             Instruction &Pos) {
270       if (V->getType() == Ty) return V;
271
272       if (Constant *CV = dyn_cast<Constant>(V))
273         return ConstantExpr::getCast(opc, CV, Ty);
274       
275       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
276       AddToWorkList(C);
277       return C;
278     }
279         
280     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
281       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
282     }
283
284
285     // ReplaceInstUsesWith - This method is to be used when an instruction is
286     // found to be dead, replacable with another preexisting expression.  Here
287     // we add all uses of I to the worklist, replace all uses of I with the new
288     // value, then return I, so that the inst combiner will know that I was
289     // modified.
290     //
291     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
292       AddUsersToWorkList(I);         // Add all modified instrs to worklist
293       if (&I != V) {
294         I.replaceAllUsesWith(V);
295         return &I;
296       } else {
297         // If we are replacing the instruction with itself, this must be in a
298         // segment of unreachable code, so just clobber the instruction.
299         I.replaceAllUsesWith(UndefValue::get(I.getType()));
300         return &I;
301       }
302     }
303
304     // UpdateValueUsesWith - This method is to be used when an value is
305     // found to be replacable with another preexisting expression or was
306     // updated.  Here we add all uses of I to the worklist, replace all uses of
307     // I with the new value (unless the instruction was just updated), then
308     // return true, so that the inst combiner will know that I was modified.
309     //
310     bool UpdateValueUsesWith(Value *Old, Value *New) {
311       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
312       if (Old != New)
313         Old->replaceAllUsesWith(New);
314       if (Instruction *I = dyn_cast<Instruction>(Old))
315         AddToWorkList(I);
316       if (Instruction *I = dyn_cast<Instruction>(New))
317         AddToWorkList(I);
318       return true;
319     }
320     
321     // EraseInstFromFunction - When dealing with an instruction that has side
322     // effects or produces a void value, we can't rely on DCE to delete the
323     // instruction.  Instead, visit methods should return the value returned by
324     // this function.
325     Instruction *EraseInstFromFunction(Instruction &I) {
326       assert(I.use_empty() && "Cannot erase instruction that is used!");
327       AddUsesToWorkList(I);
328       RemoveFromWorkList(&I);
329       I.eraseFromParent();
330       return 0;  // Don't do anything with FI
331     }
332         
333     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
334                            APInt &KnownOne, unsigned Depth = 0) const {
335       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
336     }
337     
338     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
339                            unsigned Depth = 0) const {
340       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
341     }
342     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
343       return llvm::ComputeNumSignBits(Op, TD, Depth);
344     }
345
346   private:
347
348     /// SimplifyCommutative - This performs a few simplifications for 
349     /// commutative operators.
350     bool SimplifyCommutative(BinaryOperator &I);
351
352     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
353     /// most-complex to least-complex order.
354     bool SimplifyCompare(CmpInst &I);
355
356     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
357     /// on the demanded bits.
358     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
359                               APInt& KnownZero, APInt& KnownOne,
360                               unsigned Depth = 0);
361
362     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
363                                       uint64_t &UndefElts, unsigned Depth = 0);
364       
365     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
366     // PHI node as operand #0, see if we can fold the instruction into the PHI
367     // (which is only possible if all operands to the PHI are constants).
368     Instruction *FoldOpIntoPhi(Instruction &I);
369
370     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
371     // operator and they all are only used by the PHI, PHI together their
372     // inputs, and do the operation once, to the result of the PHI.
373     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
374     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
375     
376     
377     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
379     
380     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381                               bool isSub, Instruction &I);
382     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383                                  bool isSigned, bool Inside, Instruction &IB);
384     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385     Instruction *MatchBSwap(BinaryOperator &I);
386     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
387     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
388     Instruction *SimplifyMemSet(MemSetInst *MI);
389
390
391     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
392
393     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
394                                     unsigned CastOpc,
395                                     int &NumCastsRemoved);
396     unsigned GetOrEnforceKnownAlignment(Value *V,
397                                         unsigned PrefAlign = 0);
398
399   };
400 }
401
402 char InstCombiner::ID = 0;
403 static RegisterPass<InstCombiner>
404 X("instcombine", "Combine redundant instructions");
405
406 // getComplexity:  Assign a complexity or rank value to LLVM Values...
407 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
408 static unsigned getComplexity(Value *V) {
409   if (isa<Instruction>(V)) {
410     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
411       return 3;
412     return 4;
413   }
414   if (isa<Argument>(V)) return 3;
415   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
416 }
417
418 // isOnlyUse - Return true if this instruction will be deleted if we stop using
419 // it.
420 static bool isOnlyUse(Value *V) {
421   return V->hasOneUse() || isa<Constant>(V);
422 }
423
424 // getPromotedType - Return the specified type promoted as it would be to pass
425 // though a va_arg area...
426 static const Type *getPromotedType(const Type *Ty) {
427   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428     if (ITy->getBitWidth() < 32)
429       return Type::Int32Ty;
430   }
431   return Ty;
432 }
433
434 /// getBitCastOperand - If the specified operand is a CastInst, a constant
435 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436 /// operand value, otherwise return null.
437 static Value *getBitCastOperand(Value *V) {
438   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439     // BitCastInst?
440     return I->getOperand(0);
441   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442     // GetElementPtrInst?
443     if (GEP->hasAllZeroIndices())
444       return GEP->getOperand(0);
445   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
446     if (CE->getOpcode() == Instruction::BitCast)
447       // BitCast ConstantExp?
448       return CE->getOperand(0);
449     else if (CE->getOpcode() == Instruction::GetElementPtr) {
450       // GetElementPtr ConstantExp?
451       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452            I != E; ++I) {
453         ConstantInt *CI = dyn_cast<ConstantInt>(I);
454         if (!CI || !CI->isZero())
455           // Any non-zero indices? Not cast-like.
456           return 0;
457       }
458       // All-zero indices? This is just like casting.
459       return CE->getOperand(0);
460     }
461   }
462   return 0;
463 }
464
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps 
468 isEliminableCastPair(
469   const CastInst *CI, ///< The first cast instruction
470   unsigned opcode,       ///< The opcode of the second cast instruction
471   const Type *DstTy,     ///< The target type for the second cast instruction
472   TargetData *TD         ///< The target data for pointer size
473 ) {
474   
475   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
476   const Type *MidTy = CI->getType();                  // B from above
477
478   // Get the opcodes of the two Cast instructions
479   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
482   return Instruction::CastOps(
483       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
484                                      DstTy, TD->getIntPtrType()));
485 }
486
487 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488 /// in any code being generated.  It does not require codegen if V is simple
489 /// enough or if the cast can be folded into other casts.
490 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
491                               const Type *Ty, TargetData *TD) {
492   if (V->getType() == Ty || isa<Constant>(V)) return false;
493   
494   // If this is another cast that can be eliminated, it isn't codegen either.
495   if (const CastInst *CI = dyn_cast<CastInst>(V))
496     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
497       return false;
498   return true;
499 }
500
501 // SimplifyCommutative - This performs a few simplifications for commutative
502 // operators:
503 //
504 //  1. Order operands such that they are listed from right (least complex) to
505 //     left (most complex).  This puts constants before unary operators before
506 //     binary operators.
507 //
508 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
510 //
511 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
512   bool Changed = false;
513   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
514     Changed = !I.swapOperands();
515
516   if (!I.isAssociative()) return Changed;
517   Instruction::BinaryOps Opcode = I.getOpcode();
518   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
519     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
520       if (isa<Constant>(I.getOperand(1))) {
521         Constant *Folded = ConstantExpr::get(I.getOpcode(),
522                                              cast<Constant>(I.getOperand(1)),
523                                              cast<Constant>(Op->getOperand(1)));
524         I.setOperand(0, Op->getOperand(0));
525         I.setOperand(1, Folded);
526         return true;
527       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
528         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
529             isOnlyUse(Op) && isOnlyUse(Op1)) {
530           Constant *C1 = cast<Constant>(Op->getOperand(1));
531           Constant *C2 = cast<Constant>(Op1->getOperand(1));
532
533           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
534           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
535           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
536                                                     Op1->getOperand(0),
537                                                     Op1->getName(), &I);
538           AddToWorkList(New);
539           I.setOperand(0, New);
540           I.setOperand(1, Folded);
541           return true;
542         }
543     }
544   return Changed;
545 }
546
547 /// SimplifyCompare - For a CmpInst this function just orders the operands
548 /// so that theyare listed from right (least complex) to left (most complex).
549 /// This puts constants before unary operators before binary operators.
550 bool InstCombiner::SimplifyCompare(CmpInst &I) {
551   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
552     return false;
553   I.swapOperands();
554   // Compare instructions are not associative so there's nothing else we can do.
555   return true;
556 }
557
558 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
559 // if the LHS is a constant zero (which is the 'negate' form).
560 //
561 static inline Value *dyn_castNegVal(Value *V) {
562   if (BinaryOperator::isNeg(V))
563     return BinaryOperator::getNegArgument(V);
564
565   // Constants can be considered to be negated values if they can be folded.
566   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567     return ConstantExpr::getNeg(C);
568
569   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
570     if (C->getType()->getElementType()->isInteger())
571       return ConstantExpr::getNeg(C);
572
573   return 0;
574 }
575
576 static inline Value *dyn_castNotVal(Value *V) {
577   if (BinaryOperator::isNot(V))
578     return BinaryOperator::getNotArgument(V);
579
580   // Constants can be considered to be not'ed values...
581   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
582     return ConstantInt::get(~C->getValue());
583   return 0;
584 }
585
586 // dyn_castFoldableMul - If this value is a multiply that can be folded into
587 // other computations (because it has a constant operand), return the
588 // non-constant operand of the multiply, and set CST to point to the multiplier.
589 // Otherwise, return null.
590 //
591 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
592   if (V->hasOneUse() && V->getType()->isInteger())
593     if (Instruction *I = dyn_cast<Instruction>(V)) {
594       if (I->getOpcode() == Instruction::Mul)
595         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
596           return I->getOperand(0);
597       if (I->getOpcode() == Instruction::Shl)
598         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
599           // The multiplier is really 1 << CST.
600           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
601           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
602           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
603           return I->getOperand(0);
604         }
605     }
606   return 0;
607 }
608
609 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
610 /// expression, return it.
611 static User *dyn_castGetElementPtr(Value *V) {
612   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
613   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
614     if (CE->getOpcode() == Instruction::GetElementPtr)
615       return cast<User>(V);
616   return false;
617 }
618
619 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
620 /// opcode value. Otherwise return UserOp1.
621 static unsigned getOpcode(const Value *V) {
622   if (const Instruction *I = dyn_cast<Instruction>(V))
623     return I->getOpcode();
624   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
625     return CE->getOpcode();
626   // Use UserOp1 to mean there's no opcode.
627   return Instruction::UserOp1;
628 }
629
630 /// AddOne - Add one to a ConstantInt
631 static ConstantInt *AddOne(ConstantInt *C) {
632   APInt Val(C->getValue());
633   return ConstantInt::get(++Val);
634 }
635 /// SubOne - Subtract one from a ConstantInt
636 static ConstantInt *SubOne(ConstantInt *C) {
637   APInt Val(C->getValue());
638   return ConstantInt::get(--Val);
639 }
640 /// Add - Add two ConstantInts together
641 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
642   return ConstantInt::get(C1->getValue() + C2->getValue());
643 }
644 /// And - Bitwise AND two ConstantInts together
645 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
646   return ConstantInt::get(C1->getValue() & C2->getValue());
647 }
648 /// Subtract - Subtract one ConstantInt from another
649 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
650   return ConstantInt::get(C1->getValue() - C2->getValue());
651 }
652 /// Multiply - Multiply two ConstantInts together
653 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
654   return ConstantInt::get(C1->getValue() * C2->getValue());
655 }
656 /// MultiplyOverflows - True if the multiply can not be expressed in an int
657 /// this size.
658 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
659   uint32_t W = C1->getBitWidth();
660   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
661   if (sign) {
662     LHSExt.sext(W * 2);
663     RHSExt.sext(W * 2);
664   } else {
665     LHSExt.zext(W * 2);
666     RHSExt.zext(W * 2);
667   }
668
669   APInt MulExt = LHSExt * RHSExt;
670
671   if (sign) {
672     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
673     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
674     return MulExt.slt(Min) || MulExt.sgt(Max);
675   } else 
676     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
677 }
678
679
680 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
681 /// specified instruction is a constant integer.  If so, check to see if there
682 /// are any bits set in the constant that are not demanded.  If so, shrink the
683 /// constant and return true.
684 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
685                                    APInt Demanded) {
686   assert(I && "No instruction?");
687   assert(OpNo < I->getNumOperands() && "Operand index too large");
688
689   // If the operand is not a constant integer, nothing to do.
690   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
691   if (!OpC) return false;
692
693   // If there are no bits set that aren't demanded, nothing to do.
694   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
695   if ((~Demanded & OpC->getValue()) == 0)
696     return false;
697
698   // This instruction is producing bits that are not demanded. Shrink the RHS.
699   Demanded &= OpC->getValue();
700   I->setOperand(OpNo, ConstantInt::get(Demanded));
701   return true;
702 }
703
704 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
705 // set of known zero and one bits, compute the maximum and minimum values that
706 // could have the specified known zero and known one bits, returning them in
707 // min/max.
708 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
709                                                    const APInt& KnownZero,
710                                                    const APInt& KnownOne,
711                                                    APInt& Min, APInt& Max) {
712   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
713   assert(KnownZero.getBitWidth() == BitWidth && 
714          KnownOne.getBitWidth() == BitWidth &&
715          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
716          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
717   APInt UnknownBits = ~(KnownZero|KnownOne);
718
719   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
720   // bit if it is unknown.
721   Min = KnownOne;
722   Max = KnownOne|UnknownBits;
723   
724   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
725     Min.set(BitWidth-1);
726     Max.clear(BitWidth-1);
727   }
728 }
729
730 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
731 // a set of known zero and one bits, compute the maximum and minimum values that
732 // could have the specified known zero and known one bits, returning them in
733 // min/max.
734 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
735                                                      const APInt &KnownZero,
736                                                      const APInt &KnownOne,
737                                                      APInt &Min, APInt &Max) {
738   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
739   assert(KnownZero.getBitWidth() == BitWidth && 
740          KnownOne.getBitWidth() == BitWidth &&
741          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
742          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
743   APInt UnknownBits = ~(KnownZero|KnownOne);
744   
745   // The minimum value is when the unknown bits are all zeros.
746   Min = KnownOne;
747   // The maximum value is when the unknown bits are all ones.
748   Max = KnownOne|UnknownBits;
749 }
750
751 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
752 /// value based on the demanded bits. When this function is called, it is known
753 /// that only the bits set in DemandedMask of the result of V are ever used
754 /// downstream. Consequently, depending on the mask and V, it may be possible
755 /// to replace V with a constant or one of its operands. In such cases, this
756 /// function does the replacement and returns true. In all other cases, it
757 /// returns false after analyzing the expression and setting KnownOne and known
758 /// to be one in the expression. KnownZero contains all the bits that are known
759 /// to be zero in the expression. These are provided to potentially allow the
760 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
761 /// the expression. KnownOne and KnownZero always follow the invariant that 
762 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
763 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
764 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
765 /// and KnownOne must all be the same.
766 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
767                                         APInt& KnownZero, APInt& KnownOne,
768                                         unsigned Depth) {
769   assert(V != 0 && "Null pointer of Value???");
770   assert(Depth <= 6 && "Limit Search Depth");
771   uint32_t BitWidth = DemandedMask.getBitWidth();
772   const IntegerType *VTy = cast<IntegerType>(V->getType());
773   assert(VTy->getBitWidth() == BitWidth && 
774          KnownZero.getBitWidth() == BitWidth && 
775          KnownOne.getBitWidth() == BitWidth &&
776          "Value *V, DemandedMask, KnownZero and KnownOne \
777           must have same BitWidth");
778   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
779     // We know all of the bits for a constant!
780     KnownOne = CI->getValue() & DemandedMask;
781     KnownZero = ~KnownOne & DemandedMask;
782     return false;
783   }
784   
785   KnownZero.clear(); 
786   KnownOne.clear();
787   if (!V->hasOneUse()) {    // Other users may use these bits.
788     if (Depth != 0) {       // Not at the root.
789       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
790       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
791       return false;
792     }
793     // If this is the root being simplified, allow it to have multiple uses,
794     // just set the DemandedMask to all bits.
795     DemandedMask = APInt::getAllOnesValue(BitWidth);
796   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
797     if (V != UndefValue::get(VTy))
798       return UpdateValueUsesWith(V, UndefValue::get(VTy));
799     return false;
800   } else if (Depth == 6) {        // Limit search depth.
801     return false;
802   }
803   
804   Instruction *I = dyn_cast<Instruction>(V);
805   if (!I) return false;        // Only analyze instructions.
806
807   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
808   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
809   switch (I->getOpcode()) {
810   default:
811     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
812     break;
813   case Instruction::And:
814     // If either the LHS or the RHS are Zero, the result is zero.
815     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
816                              RHSKnownZero, RHSKnownOne, Depth+1))
817       return true;
818     assert((RHSKnownZero & RHSKnownOne) == 0 && 
819            "Bits known to be one AND zero?"); 
820
821     // If something is known zero on the RHS, the bits aren't demanded on the
822     // LHS.
823     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
824                              LHSKnownZero, LHSKnownOne, Depth+1))
825       return true;
826     assert((LHSKnownZero & LHSKnownOne) == 0 && 
827            "Bits known to be one AND zero?"); 
828
829     // If all of the demanded bits are known 1 on one side, return the other.
830     // These bits cannot contribute to the result of the 'and'.
831     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
832         (DemandedMask & ~LHSKnownZero))
833       return UpdateValueUsesWith(I, I->getOperand(0));
834     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
835         (DemandedMask & ~RHSKnownZero))
836       return UpdateValueUsesWith(I, I->getOperand(1));
837     
838     // If all of the demanded bits in the inputs are known zeros, return zero.
839     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
840       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
841       
842     // If the RHS is a constant, see if we can simplify it.
843     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
844       return UpdateValueUsesWith(I, I);
845       
846     // Output known-1 bits are only known if set in both the LHS & RHS.
847     RHSKnownOne &= LHSKnownOne;
848     // Output known-0 are known to be clear if zero in either the LHS | RHS.
849     RHSKnownZero |= LHSKnownZero;
850     break;
851   case Instruction::Or:
852     // If either the LHS or the RHS are One, the result is One.
853     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
854                              RHSKnownZero, RHSKnownOne, Depth+1))
855       return true;
856     assert((RHSKnownZero & RHSKnownOne) == 0 && 
857            "Bits known to be one AND zero?"); 
858     // If something is known one on the RHS, the bits aren't demanded on the
859     // LHS.
860     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
861                              LHSKnownZero, LHSKnownOne, Depth+1))
862       return true;
863     assert((LHSKnownZero & LHSKnownOne) == 0 && 
864            "Bits known to be one AND zero?"); 
865     
866     // If all of the demanded bits are known zero on one side, return the other.
867     // These bits cannot contribute to the result of the 'or'.
868     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
869         (DemandedMask & ~LHSKnownOne))
870       return UpdateValueUsesWith(I, I->getOperand(0));
871     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
872         (DemandedMask & ~RHSKnownOne))
873       return UpdateValueUsesWith(I, I->getOperand(1));
874
875     // If all of the potentially set bits on one side are known to be set on
876     // the other side, just use the 'other' side.
877     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
878         (DemandedMask & (~RHSKnownZero)))
879       return UpdateValueUsesWith(I, I->getOperand(0));
880     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
881         (DemandedMask & (~LHSKnownZero)))
882       return UpdateValueUsesWith(I, I->getOperand(1));
883         
884     // If the RHS is a constant, see if we can simplify it.
885     if (ShrinkDemandedConstant(I, 1, DemandedMask))
886       return UpdateValueUsesWith(I, I);
887           
888     // Output known-0 bits are only known if clear in both the LHS & RHS.
889     RHSKnownZero &= LHSKnownZero;
890     // Output known-1 are known to be set if set in either the LHS | RHS.
891     RHSKnownOne |= LHSKnownOne;
892     break;
893   case Instruction::Xor: {
894     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895                              RHSKnownZero, RHSKnownOne, Depth+1))
896       return true;
897     assert((RHSKnownZero & RHSKnownOne) == 0 && 
898            "Bits known to be one AND zero?"); 
899     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
900                              LHSKnownZero, LHSKnownOne, Depth+1))
901       return true;
902     assert((LHSKnownZero & LHSKnownOne) == 0 && 
903            "Bits known to be one AND zero?"); 
904     
905     // If all of the demanded bits are known zero on one side, return the other.
906     // These bits cannot contribute to the result of the 'xor'.
907     if ((DemandedMask & RHSKnownZero) == DemandedMask)
908       return UpdateValueUsesWith(I, I->getOperand(0));
909     if ((DemandedMask & LHSKnownZero) == DemandedMask)
910       return UpdateValueUsesWith(I, I->getOperand(1));
911     
912     // Output known-0 bits are known if clear or set in both the LHS & RHS.
913     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
914                          (RHSKnownOne & LHSKnownOne);
915     // Output known-1 are known to be set if set in only one of the LHS, RHS.
916     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
917                         (RHSKnownOne & LHSKnownZero);
918     
919     // If all of the demanded bits are known to be zero on one side or the
920     // other, turn this into an *inclusive* or.
921     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
922     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
923       Instruction *Or =
924         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
925                                  I->getName());
926       InsertNewInstBefore(Or, *I);
927       return UpdateValueUsesWith(I, Or);
928     }
929     
930     // If all of the demanded bits on one side are known, and all of the set
931     // bits on that side are also known to be set on the other side, turn this
932     // into an AND, as we know the bits will be cleared.
933     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
934     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
935       // all known
936       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
937         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
938         Instruction *And = 
939           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
940         InsertNewInstBefore(And, *I);
941         return UpdateValueUsesWith(I, And);
942       }
943     }
944     
945     // If the RHS is a constant, see if we can simplify it.
946     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
947     if (ShrinkDemandedConstant(I, 1, DemandedMask))
948       return UpdateValueUsesWith(I, I);
949     
950     RHSKnownZero = KnownZeroOut;
951     RHSKnownOne  = KnownOneOut;
952     break;
953   }
954   case Instruction::Select:
955     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
956                              RHSKnownZero, RHSKnownOne, Depth+1))
957       return true;
958     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
959                              LHSKnownZero, LHSKnownOne, Depth+1))
960       return true;
961     assert((RHSKnownZero & RHSKnownOne) == 0 && 
962            "Bits known to be one AND zero?"); 
963     assert((LHSKnownZero & LHSKnownOne) == 0 && 
964            "Bits known to be one AND zero?"); 
965     
966     // If the operands are constants, see if we can simplify them.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask))
968       return UpdateValueUsesWith(I, I);
969     if (ShrinkDemandedConstant(I, 2, DemandedMask))
970       return UpdateValueUsesWith(I, I);
971     
972     // Only known if known in both the LHS and RHS.
973     RHSKnownOne &= LHSKnownOne;
974     RHSKnownZero &= LHSKnownZero;
975     break;
976   case Instruction::Trunc: {
977     uint32_t truncBf = 
978       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
979     DemandedMask.zext(truncBf);
980     RHSKnownZero.zext(truncBf);
981     RHSKnownOne.zext(truncBf);
982     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
983                              RHSKnownZero, RHSKnownOne, Depth+1))
984       return true;
985     DemandedMask.trunc(BitWidth);
986     RHSKnownZero.trunc(BitWidth);
987     RHSKnownOne.trunc(BitWidth);
988     assert((RHSKnownZero & RHSKnownOne) == 0 && 
989            "Bits known to be one AND zero?"); 
990     break;
991   }
992   case Instruction::BitCast:
993     if (!I->getOperand(0)->getType()->isInteger())
994       return false;
995       
996     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
997                              RHSKnownZero, RHSKnownOne, Depth+1))
998       return true;
999     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1000            "Bits known to be one AND zero?"); 
1001     break;
1002   case Instruction::ZExt: {
1003     // Compute the bits in the result that are not present in the input.
1004     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1005     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1006     
1007     DemandedMask.trunc(SrcBitWidth);
1008     RHSKnownZero.trunc(SrcBitWidth);
1009     RHSKnownOne.trunc(SrcBitWidth);
1010     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1011                              RHSKnownZero, RHSKnownOne, Depth+1))
1012       return true;
1013     DemandedMask.zext(BitWidth);
1014     RHSKnownZero.zext(BitWidth);
1015     RHSKnownOne.zext(BitWidth);
1016     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1017            "Bits known to be one AND zero?"); 
1018     // The top bits are known to be zero.
1019     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1020     break;
1021   }
1022   case Instruction::SExt: {
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     APInt InputDemandedBits = DemandedMask & 
1028                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1029
1030     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1031     // If any of the sign extended bits are demanded, we know that the sign
1032     // bit is demanded.
1033     if ((NewBits & DemandedMask) != 0)
1034       InputDemandedBits.set(SrcBitWidth-1);
1035       
1036     InputDemandedBits.trunc(SrcBitWidth);
1037     RHSKnownZero.trunc(SrcBitWidth);
1038     RHSKnownOne.trunc(SrcBitWidth);
1039     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1040                              RHSKnownZero, RHSKnownOne, Depth+1))
1041       return true;
1042     InputDemandedBits.zext(BitWidth);
1043     RHSKnownZero.zext(BitWidth);
1044     RHSKnownOne.zext(BitWidth);
1045     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1046            "Bits known to be one AND zero?"); 
1047       
1048     // If the sign bit of the input is known set or clear, then we know the
1049     // top bits of the result.
1050
1051     // If the input sign bit is known zero, or if the NewBits are not demanded
1052     // convert this into a zero extension.
1053     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1054     {
1055       // Convert to ZExt cast
1056       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1057       return UpdateValueUsesWith(I, NewCast);
1058     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1059       RHSKnownOne |= NewBits;
1060     }
1061     break;
1062   }
1063   case Instruction::Add: {
1064     // Figure out what the input bits are.  If the top bits of the and result
1065     // are not demanded, then the add doesn't demand them from its input
1066     // either.
1067     uint32_t NLZ = DemandedMask.countLeadingZeros();
1068       
1069     // If there is a constant on the RHS, there are a variety of xformations
1070     // we can do.
1071     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072       // If null, this should be simplified elsewhere.  Some of the xforms here
1073       // won't work if the RHS is zero.
1074       if (RHS->isZero())
1075         break;
1076       
1077       // If the top bit of the output is demanded, demand everything from the
1078       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1079       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1080
1081       // Find information about known zero/one bits in the input.
1082       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1083                                LHSKnownZero, LHSKnownOne, Depth+1))
1084         return true;
1085
1086       // If the RHS of the add has bits set that can't affect the input, reduce
1087       // the constant.
1088       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1089         return UpdateValueUsesWith(I, I);
1090       
1091       // Avoid excess work.
1092       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1093         break;
1094       
1095       // Turn it into OR if input bits are zero.
1096       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1097         Instruction *Or =
1098           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1099                                    I->getName());
1100         InsertNewInstBefore(Or, *I);
1101         return UpdateValueUsesWith(I, Or);
1102       }
1103       
1104       // We can say something about the output known-zero and known-one bits,
1105       // depending on potential carries from the input constant and the
1106       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1107       // bits set and the RHS constant is 0x01001, then we know we have a known
1108       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1109       
1110       // To compute this, we first compute the potential carry bits.  These are
1111       // the bits which may be modified.  I'm not aware of a better way to do
1112       // this scan.
1113       const APInt& RHSVal = RHS->getValue();
1114       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1115       
1116       // Now that we know which bits have carries, compute the known-1/0 sets.
1117       
1118       // Bits are known one if they are known zero in one operand and one in the
1119       // other, and there is no input carry.
1120       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1121                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1122       
1123       // Bits are known zero if they are known zero in both operands and there
1124       // is no input carry.
1125       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1126     } else {
1127       // If the high-bits of this ADD are not demanded, then it does not demand
1128       // the high bits of its LHS or RHS.
1129       if (DemandedMask[BitWidth-1] == 0) {
1130         // Right fill the mask of bits for this ADD to demand the most
1131         // significant bit and all those below it.
1132         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1133         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1134                                  LHSKnownZero, LHSKnownOne, Depth+1))
1135           return true;
1136         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1137                                  LHSKnownZero, LHSKnownOne, Depth+1))
1138           return true;
1139       }
1140     }
1141     break;
1142   }
1143   case Instruction::Sub:
1144     // If the high-bits of this SUB are not demanded, then it does not demand
1145     // the high bits of its LHS or RHS.
1146     if (DemandedMask[BitWidth-1] == 0) {
1147       // Right fill the mask of bits for this SUB to demand the most
1148       // significant bit and all those below it.
1149       uint32_t NLZ = DemandedMask.countLeadingZeros();
1150       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1151       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1152                                LHSKnownZero, LHSKnownOne, Depth+1))
1153         return true;
1154       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1155                                LHSKnownZero, LHSKnownOne, Depth+1))
1156         return true;
1157     }
1158     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1159     // the known zeros and ones.
1160     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1161     break;
1162   case Instruction::Shl:
1163     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1164       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1165       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1166       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1167                                RHSKnownZero, RHSKnownOne, Depth+1))
1168         return true;
1169       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1170              "Bits known to be one AND zero?"); 
1171       RHSKnownZero <<= ShiftAmt;
1172       RHSKnownOne  <<= ShiftAmt;
1173       // low bits known zero.
1174       if (ShiftAmt)
1175         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1176     }
1177     break;
1178   case Instruction::LShr:
1179     // For a logical shift right
1180     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1182       
1183       // Unsigned shift right.
1184       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1185       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1186                                RHSKnownZero, RHSKnownOne, Depth+1))
1187         return true;
1188       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1189              "Bits known to be one AND zero?"); 
1190       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1191       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1192       if (ShiftAmt) {
1193         // Compute the new bits that are at the top now.
1194         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1195         RHSKnownZero |= HighBits;  // high bits known zero.
1196       }
1197     }
1198     break;
1199   case Instruction::AShr:
1200     // If this is an arithmetic shift right and only the low-bit is set, we can
1201     // always convert this into a logical shr, even if the shift amount is
1202     // variable.  The low bit of the shift cannot be an input sign bit unless
1203     // the shift amount is >= the size of the datatype, which is undefined.
1204     if (DemandedMask == 1) {
1205       // Perform the logical shift right.
1206       Value *NewVal = BinaryOperator::CreateLShr(
1207                         I->getOperand(0), I->getOperand(1), I->getName());
1208       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1209       return UpdateValueUsesWith(I, NewVal);
1210     }    
1211
1212     // If the sign bit is the only bit demanded by this ashr, then there is no
1213     // need to do it, the shift doesn't change the high bit.
1214     if (DemandedMask.isSignBit())
1215       return UpdateValueUsesWith(I, I->getOperand(0));
1216     
1217     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1219       
1220       // Signed shift right.
1221       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1222       // If any of the "high bits" are demanded, we should set the sign bit as
1223       // demanded.
1224       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1225         DemandedMaskIn.set(BitWidth-1);
1226       if (SimplifyDemandedBits(I->getOperand(0),
1227                                DemandedMaskIn,
1228                                RHSKnownZero, RHSKnownOne, Depth+1))
1229         return true;
1230       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1231              "Bits known to be one AND zero?"); 
1232       // Compute the new bits that are at the top now.
1233       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1234       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1235       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1236         
1237       // Handle the sign bits.
1238       APInt SignBit(APInt::getSignBit(BitWidth));
1239       // Adjust to where it is now in the mask.
1240       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1241         
1242       // If the input sign bit is known to be zero, or if none of the top bits
1243       // are demanded, turn this into an unsigned shift right.
1244       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1245           (HighBits & ~DemandedMask) == HighBits) {
1246         // Perform the logical shift right.
1247         Value *NewVal = BinaryOperator::CreateLShr(
1248                           I->getOperand(0), SA, I->getName());
1249         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1250         return UpdateValueUsesWith(I, NewVal);
1251       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1252         RHSKnownOne |= HighBits;
1253       }
1254     }
1255     break;
1256   case Instruction::SRem:
1257     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258       APInt RA = Rem->getValue().abs();
1259       if (RA.isPowerOf2()) {
1260         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1261           return UpdateValueUsesWith(I, I->getOperand(0));
1262
1263         APInt LowBits = RA - 1;
1264         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1265         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1266                                  LHSKnownZero, LHSKnownOne, Depth+1))
1267           return true;
1268
1269         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1270           LHSKnownZero |= ~LowBits;
1271
1272         KnownZero |= LHSKnownZero & DemandedMask;
1273
1274         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1275       }
1276     }
1277     break;
1278   case Instruction::URem: {
1279     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1280     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1281     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1282                              KnownZero2, KnownOne2, Depth+1))
1283       return true;
1284
1285     uint32_t Leaders = KnownZero2.countLeadingOnes();
1286     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1287                              KnownZero2, KnownOne2, Depth+1))
1288       return true;
1289
1290     Leaders = std::max(Leaders,
1291                        KnownZero2.countLeadingOnes());
1292     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1293     break;
1294   }
1295   case Instruction::Call:
1296     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1297       switch (II->getIntrinsicID()) {
1298       default: break;
1299       case Intrinsic::bswap: {
1300         // If the only bits demanded come from one byte of the bswap result,
1301         // just shift the input byte into position to eliminate the bswap.
1302         unsigned NLZ = DemandedMask.countLeadingZeros();
1303         unsigned NTZ = DemandedMask.countTrailingZeros();
1304           
1305         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1306         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1307         // have 14 leading zeros, round to 8.
1308         NLZ &= ~7;
1309         NTZ &= ~7;
1310         // If we need exactly one byte, we can do this transformation.
1311         if (BitWidth-NLZ-NTZ == 8) {
1312           unsigned ResultBit = NTZ;
1313           unsigned InputBit = BitWidth-NTZ-8;
1314           
1315           // Replace this with either a left or right shift to get the byte into
1316           // the right place.
1317           Instruction *NewVal;
1318           if (InputBit > ResultBit)
1319             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1320                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1321           else
1322             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1323                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1324           NewVal->takeName(I);
1325           InsertNewInstBefore(NewVal, *I);
1326           return UpdateValueUsesWith(I, NewVal);
1327         }
1328           
1329         // TODO: Could compute known zero/one bits based on the input.
1330         break;
1331       }
1332       }
1333     }
1334     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1335     break;
1336   }
1337   
1338   // If the client is only demanding bits that we know, return the known
1339   // constant.
1340   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1341     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1342   return false;
1343 }
1344
1345
1346 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1347 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1348 /// actually used by the caller.  This method analyzes which elements of the
1349 /// operand are undef and returns that information in UndefElts.
1350 ///
1351 /// If the information about demanded elements can be used to simplify the
1352 /// operation, the operation is simplified, then the resultant value is
1353 /// returned.  This returns null if no change was made.
1354 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1355                                                 uint64_t &UndefElts,
1356                                                 unsigned Depth) {
1357   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1358   assert(VWidth <= 64 && "Vector too wide to analyze!");
1359   uint64_t EltMask = ~0ULL >> (64-VWidth);
1360   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1361
1362   if (isa<UndefValue>(V)) {
1363     // If the entire vector is undefined, just return this info.
1364     UndefElts = EltMask;
1365     return 0;
1366   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1367     UndefElts = EltMask;
1368     return UndefValue::get(V->getType());
1369   }
1370
1371   UndefElts = 0;
1372   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1373     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1374     Constant *Undef = UndefValue::get(EltTy);
1375
1376     std::vector<Constant*> Elts;
1377     for (unsigned i = 0; i != VWidth; ++i)
1378       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1379         Elts.push_back(Undef);
1380         UndefElts |= (1ULL << i);
1381       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1382         Elts.push_back(Undef);
1383         UndefElts |= (1ULL << i);
1384       } else {                               // Otherwise, defined.
1385         Elts.push_back(CP->getOperand(i));
1386       }
1387
1388     // If we changed the constant, return it.
1389     Constant *NewCP = ConstantVector::get(Elts);
1390     return NewCP != CP ? NewCP : 0;
1391   } else if (isa<ConstantAggregateZero>(V)) {
1392     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1393     // set to undef.
1394     
1395     // Check if this is identity. If so, return 0 since we are not simplifying
1396     // anything.
1397     if (DemandedElts == ((1ULL << VWidth) -1))
1398       return 0;
1399     
1400     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1401     Constant *Zero = Constant::getNullValue(EltTy);
1402     Constant *Undef = UndefValue::get(EltTy);
1403     std::vector<Constant*> Elts;
1404     for (unsigned i = 0; i != VWidth; ++i)
1405       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1406     UndefElts = DemandedElts ^ EltMask;
1407     return ConstantVector::get(Elts);
1408   }
1409   
1410   // Limit search depth.
1411   if (Depth == 10)
1412     return false;
1413
1414   // If multiple users are using the root value, procede with
1415   // simplification conservatively assuming that all elements
1416   // are needed.
1417   if (!V->hasOneUse()) {
1418     // Quit if we find multiple users of a non-root value though.
1419     // They'll be handled when it's their turn to be visited by
1420     // the main instcombine process.
1421     if (Depth != 0)
1422       // TODO: Just compute the UndefElts information recursively.
1423       return false;
1424
1425     // Conservatively assume that all elements are needed.
1426     DemandedElts = EltMask;
1427   }
1428   
1429   Instruction *I = dyn_cast<Instruction>(V);
1430   if (!I) return false;        // Only analyze instructions.
1431   
1432   bool MadeChange = false;
1433   uint64_t UndefElts2;
1434   Value *TmpV;
1435   switch (I->getOpcode()) {
1436   default: break;
1437     
1438   case Instruction::InsertElement: {
1439     // If this is a variable index, we don't know which element it overwrites.
1440     // demand exactly the same input as we produce.
1441     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1442     if (Idx == 0) {
1443       // Note that we can't propagate undef elt info, because we don't know
1444       // which elt is getting updated.
1445       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1446                                         UndefElts2, Depth+1);
1447       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1448       break;
1449     }
1450     
1451     // If this is inserting an element that isn't demanded, remove this
1452     // insertelement.
1453     unsigned IdxNo = Idx->getZExtValue();
1454     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1455       return AddSoonDeadInstToWorklist(*I, 0);
1456     
1457     // Otherwise, the element inserted overwrites whatever was there, so the
1458     // input demanded set is simpler than the output set.
1459     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1460                                       DemandedElts & ~(1ULL << IdxNo),
1461                                       UndefElts, Depth+1);
1462     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1463
1464     // The inserted element is defined.
1465     UndefElts &= ~(1ULL << IdxNo);
1466     break;
1467   }
1468   case Instruction::ShuffleVector: {
1469     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1470     uint64_t LHSVWidth =
1471       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1472     uint64_t LeftDemanded = 0, RightDemanded = 0;
1473     for (unsigned i = 0; i < VWidth; i++) {
1474       if (DemandedElts & (1ULL << i)) {
1475         unsigned MaskVal = Shuffle->getMaskValue(i);
1476         if (MaskVal != -1u) {
1477           assert(MaskVal < LHSVWidth * 2 &&
1478                  "shufflevector mask index out of range!");
1479           if (MaskVal < LHSVWidth)
1480             LeftDemanded |= 1ULL << MaskVal;
1481           else
1482             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1483         }
1484       }
1485     }
1486
1487     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1488                                       UndefElts2, Depth+1);
1489     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1490
1491     uint64_t UndefElts3;
1492     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1493                                       UndefElts3, Depth+1);
1494     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1495
1496     bool NewUndefElts = false;
1497     for (unsigned i = 0; i < VWidth; i++) {
1498       unsigned MaskVal = Shuffle->getMaskValue(i);
1499       if (MaskVal == -1u) {
1500         uint64_t NewBit = 1ULL << i;
1501         UndefElts |= NewBit;
1502       } else if (MaskVal < LHSVWidth) {
1503         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1504         NewUndefElts |= NewBit;
1505         UndefElts |= NewBit;
1506       } else {
1507         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1508         NewUndefElts |= NewBit;
1509         UndefElts |= NewBit;
1510       }
1511     }
1512
1513     if (NewUndefElts) {
1514       // Add additional discovered undefs.
1515       std::vector<Constant*> Elts;
1516       for (unsigned i = 0; i < VWidth; ++i) {
1517         if (UndefElts & (1ULL << i))
1518           Elts.push_back(UndefValue::get(Type::Int32Ty));
1519         else
1520           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1521                                           Shuffle->getMaskValue(i)));
1522       }
1523       I->setOperand(2, ConstantVector::get(Elts));
1524       MadeChange = true;
1525     }
1526     break;
1527   }
1528   case Instruction::BitCast: {
1529     // Vector->vector casts only.
1530     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1531     if (!VTy) break;
1532     unsigned InVWidth = VTy->getNumElements();
1533     uint64_t InputDemandedElts = 0;
1534     unsigned Ratio;
1535
1536     if (VWidth == InVWidth) {
1537       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1538       // elements as are demanded of us.
1539       Ratio = 1;
1540       InputDemandedElts = DemandedElts;
1541     } else if (VWidth > InVWidth) {
1542       // Untested so far.
1543       break;
1544       
1545       // If there are more elements in the result than there are in the source,
1546       // then an input element is live if any of the corresponding output
1547       // elements are live.
1548       Ratio = VWidth/InVWidth;
1549       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1550         if (DemandedElts & (1ULL << OutIdx))
1551           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1552       }
1553     } else {
1554       // Untested so far.
1555       break;
1556       
1557       // If there are more elements in the source than there are in the result,
1558       // then an input element is live if the corresponding output element is
1559       // live.
1560       Ratio = InVWidth/VWidth;
1561       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1562         if (DemandedElts & (1ULL << InIdx/Ratio))
1563           InputDemandedElts |= 1ULL << InIdx;
1564     }
1565     
1566     // div/rem demand all inputs, because they don't want divide by zero.
1567     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1568                                       UndefElts2, Depth+1);
1569     if (TmpV) {
1570       I->setOperand(0, TmpV);
1571       MadeChange = true;
1572     }
1573     
1574     UndefElts = UndefElts2;
1575     if (VWidth > InVWidth) {
1576       assert(0 && "Unimp");
1577       // If there are more elements in the result than there are in the source,
1578       // then an output element is undef if the corresponding input element is
1579       // undef.
1580       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1581         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1582           UndefElts |= 1ULL << OutIdx;
1583     } else if (VWidth < InVWidth) {
1584       assert(0 && "Unimp");
1585       // If there are more elements in the source than there are in the result,
1586       // then a result element is undef if all of the corresponding input
1587       // elements are undef.
1588       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1589       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1590         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1591           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1592     }
1593     break;
1594   }
1595   case Instruction::And:
1596   case Instruction::Or:
1597   case Instruction::Xor:
1598   case Instruction::Add:
1599   case Instruction::Sub:
1600   case Instruction::Mul:
1601     // div/rem demand all inputs, because they don't want divide by zero.
1602     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1603                                       UndefElts, Depth+1);
1604     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1605     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1606                                       UndefElts2, Depth+1);
1607     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1608       
1609     // Output elements are undefined if both are undefined.  Consider things
1610     // like undef&0.  The result is known zero, not undef.
1611     UndefElts &= UndefElts2;
1612     break;
1613     
1614   case Instruction::Call: {
1615     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1616     if (!II) break;
1617     switch (II->getIntrinsicID()) {
1618     default: break;
1619       
1620     // Binary vector operations that work column-wise.  A dest element is a
1621     // function of the corresponding input elements from the two inputs.
1622     case Intrinsic::x86_sse_sub_ss:
1623     case Intrinsic::x86_sse_mul_ss:
1624     case Intrinsic::x86_sse_min_ss:
1625     case Intrinsic::x86_sse_max_ss:
1626     case Intrinsic::x86_sse2_sub_sd:
1627     case Intrinsic::x86_sse2_mul_sd:
1628     case Intrinsic::x86_sse2_min_sd:
1629     case Intrinsic::x86_sse2_max_sd:
1630       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1631                                         UndefElts, Depth+1);
1632       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1633       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1634                                         UndefElts2, Depth+1);
1635       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1636
1637       // If only the low elt is demanded and this is a scalarizable intrinsic,
1638       // scalarize it now.
1639       if (DemandedElts == 1) {
1640         switch (II->getIntrinsicID()) {
1641         default: break;
1642         case Intrinsic::x86_sse_sub_ss:
1643         case Intrinsic::x86_sse_mul_ss:
1644         case Intrinsic::x86_sse2_sub_sd:
1645         case Intrinsic::x86_sse2_mul_sd:
1646           // TODO: Lower MIN/MAX/ABS/etc
1647           Value *LHS = II->getOperand(1);
1648           Value *RHS = II->getOperand(2);
1649           // Extract the element as scalars.
1650           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1651           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1652           
1653           switch (II->getIntrinsicID()) {
1654           default: assert(0 && "Case stmts out of sync!");
1655           case Intrinsic::x86_sse_sub_ss:
1656           case Intrinsic::x86_sse2_sub_sd:
1657             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1658                                                         II->getName()), *II);
1659             break;
1660           case Intrinsic::x86_sse_mul_ss:
1661           case Intrinsic::x86_sse2_mul_sd:
1662             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1663                                                          II->getName()), *II);
1664             break;
1665           }
1666           
1667           Instruction *New =
1668             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1669                                       II->getName());
1670           InsertNewInstBefore(New, *II);
1671           AddSoonDeadInstToWorklist(*II, 0);
1672           return New;
1673         }            
1674       }
1675         
1676       // Output elements are undefined if both are undefined.  Consider things
1677       // like undef&0.  The result is known zero, not undef.
1678       UndefElts &= UndefElts2;
1679       break;
1680     }
1681     break;
1682   }
1683   }
1684   return MadeChange ? I : 0;
1685 }
1686
1687
1688 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1689 /// function is designed to check a chain of associative operators for a
1690 /// potential to apply a certain optimization.  Since the optimization may be
1691 /// applicable if the expression was reassociated, this checks the chain, then
1692 /// reassociates the expression as necessary to expose the optimization
1693 /// opportunity.  This makes use of a special Functor, which must define
1694 /// 'shouldApply' and 'apply' methods.
1695 ///
1696 template<typename Functor>
1697 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1698   unsigned Opcode = Root.getOpcode();
1699   Value *LHS = Root.getOperand(0);
1700
1701   // Quick check, see if the immediate LHS matches...
1702   if (F.shouldApply(LHS))
1703     return F.apply(Root);
1704
1705   // Otherwise, if the LHS is not of the same opcode as the root, return.
1706   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1707   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1708     // Should we apply this transform to the RHS?
1709     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1710
1711     // If not to the RHS, check to see if we should apply to the LHS...
1712     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1713       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1714       ShouldApply = true;
1715     }
1716
1717     // If the functor wants to apply the optimization to the RHS of LHSI,
1718     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1719     if (ShouldApply) {
1720       // Now all of the instructions are in the current basic block, go ahead
1721       // and perform the reassociation.
1722       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1723
1724       // First move the selected RHS to the LHS of the root...
1725       Root.setOperand(0, LHSI->getOperand(1));
1726
1727       // Make what used to be the LHS of the root be the user of the root...
1728       Value *ExtraOperand = TmpLHSI->getOperand(1);
1729       if (&Root == TmpLHSI) {
1730         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1731         return 0;
1732       }
1733       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1734       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1735       BasicBlock::iterator ARI = &Root; ++ARI;
1736       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1737       ARI = Root;
1738
1739       // Now propagate the ExtraOperand down the chain of instructions until we
1740       // get to LHSI.
1741       while (TmpLHSI != LHSI) {
1742         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1743         // Move the instruction to immediately before the chain we are
1744         // constructing to avoid breaking dominance properties.
1745         NextLHSI->moveBefore(ARI);
1746         ARI = NextLHSI;
1747
1748         Value *NextOp = NextLHSI->getOperand(1);
1749         NextLHSI->setOperand(1, ExtraOperand);
1750         TmpLHSI = NextLHSI;
1751         ExtraOperand = NextOp;
1752       }
1753
1754       // Now that the instructions are reassociated, have the functor perform
1755       // the transformation...
1756       return F.apply(Root);
1757     }
1758
1759     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1760   }
1761   return 0;
1762 }
1763
1764 namespace {
1765
1766 // AddRHS - Implements: X + X --> X << 1
1767 struct AddRHS {
1768   Value *RHS;
1769   AddRHS(Value *rhs) : RHS(rhs) {}
1770   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1771   Instruction *apply(BinaryOperator &Add) const {
1772     return BinaryOperator::CreateShl(Add.getOperand(0),
1773                                      ConstantInt::get(Add.getType(), 1));
1774   }
1775 };
1776
1777 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1778 //                 iff C1&C2 == 0
1779 struct AddMaskingAnd {
1780   Constant *C2;
1781   AddMaskingAnd(Constant *c) : C2(c) {}
1782   bool shouldApply(Value *LHS) const {
1783     ConstantInt *C1;
1784     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1785            ConstantExpr::getAnd(C1, C2)->isNullValue();
1786   }
1787   Instruction *apply(BinaryOperator &Add) const {
1788     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1789   }
1790 };
1791
1792 }
1793
1794 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1795                                              InstCombiner *IC) {
1796   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1797     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1798   }
1799
1800   // Figure out if the constant is the left or the right argument.
1801   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1802   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1803
1804   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1805     if (ConstIsRHS)
1806       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1807     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1808   }
1809
1810   Value *Op0 = SO, *Op1 = ConstOperand;
1811   if (!ConstIsRHS)
1812     std::swap(Op0, Op1);
1813   Instruction *New;
1814   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1815     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1816   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1817     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1818                           SO->getName()+".cmp");
1819   else {
1820     assert(0 && "Unknown binary instruction type!");
1821     abort();
1822   }
1823   return IC->InsertNewInstBefore(New, I);
1824 }
1825
1826 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1827 // constant as the other operand, try to fold the binary operator into the
1828 // select arguments.  This also works for Cast instructions, which obviously do
1829 // not have a second operand.
1830 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1831                                      InstCombiner *IC) {
1832   // Don't modify shared select instructions
1833   if (!SI->hasOneUse()) return 0;
1834   Value *TV = SI->getOperand(1);
1835   Value *FV = SI->getOperand(2);
1836
1837   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1838     // Bool selects with constant operands can be folded to logical ops.
1839     if (SI->getType() == Type::Int1Ty) return 0;
1840
1841     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1842     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1843
1844     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1845                               SelectFalseVal);
1846   }
1847   return 0;
1848 }
1849
1850
1851 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1852 /// node as operand #0, see if we can fold the instruction into the PHI (which
1853 /// is only possible if all operands to the PHI are constants).
1854 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1855   PHINode *PN = cast<PHINode>(I.getOperand(0));
1856   unsigned NumPHIValues = PN->getNumIncomingValues();
1857   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1858
1859   // Check to see if all of the operands of the PHI are constants.  If there is
1860   // one non-constant value, remember the BB it is.  If there is more than one
1861   // or if *it* is a PHI, bail out.
1862   BasicBlock *NonConstBB = 0;
1863   for (unsigned i = 0; i != NumPHIValues; ++i)
1864     if (!isa<Constant>(PN->getIncomingValue(i))) {
1865       if (NonConstBB) return 0;  // More than one non-const value.
1866       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1867       NonConstBB = PN->getIncomingBlock(i);
1868       
1869       // If the incoming non-constant value is in I's block, we have an infinite
1870       // loop.
1871       if (NonConstBB == I.getParent())
1872         return 0;
1873     }
1874   
1875   // If there is exactly one non-constant value, we can insert a copy of the
1876   // operation in that block.  However, if this is a critical edge, we would be
1877   // inserting the computation one some other paths (e.g. inside a loop).  Only
1878   // do this if the pred block is unconditionally branching into the phi block.
1879   if (NonConstBB) {
1880     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1881     if (!BI || !BI->isUnconditional()) return 0;
1882   }
1883
1884   // Okay, we can do the transformation: create the new PHI node.
1885   PHINode *NewPN = PHINode::Create(I.getType(), "");
1886   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1887   InsertNewInstBefore(NewPN, *PN);
1888   NewPN->takeName(PN);
1889
1890   // Next, add all of the operands to the PHI.
1891   if (I.getNumOperands() == 2) {
1892     Constant *C = cast<Constant>(I.getOperand(1));
1893     for (unsigned i = 0; i != NumPHIValues; ++i) {
1894       Value *InV = 0;
1895       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1896         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1897           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1898         else
1899           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1900       } else {
1901         assert(PN->getIncomingBlock(i) == NonConstBB);
1902         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1903           InV = BinaryOperator::Create(BO->getOpcode(),
1904                                        PN->getIncomingValue(i), C, "phitmp",
1905                                        NonConstBB->getTerminator());
1906         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1907           InV = CmpInst::Create(CI->getOpcode(), 
1908                                 CI->getPredicate(),
1909                                 PN->getIncomingValue(i), C, "phitmp",
1910                                 NonConstBB->getTerminator());
1911         else
1912           assert(0 && "Unknown binop!");
1913         
1914         AddToWorkList(cast<Instruction>(InV));
1915       }
1916       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1917     }
1918   } else { 
1919     CastInst *CI = cast<CastInst>(&I);
1920     const Type *RetTy = CI->getType();
1921     for (unsigned i = 0; i != NumPHIValues; ++i) {
1922       Value *InV;
1923       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1924         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1925       } else {
1926         assert(PN->getIncomingBlock(i) == NonConstBB);
1927         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1928                                I.getType(), "phitmp", 
1929                                NonConstBB->getTerminator());
1930         AddToWorkList(cast<Instruction>(InV));
1931       }
1932       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1933     }
1934   }
1935   return ReplaceInstUsesWith(I, NewPN);
1936 }
1937
1938
1939 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1940 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1941 /// This basically requires proving that the add in the original type would not
1942 /// overflow to change the sign bit or have a carry out.
1943 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1944   // There are different heuristics we can use for this.  Here are some simple
1945   // ones.
1946   
1947   // Add has the property that adding any two 2's complement numbers can only 
1948   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1949   // have at least two sign bits, we know that the addition of the two values will
1950   // sign extend fine.
1951   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1952     return true;
1953   
1954   
1955   // If one of the operands only has one non-zero bit, and if the other operand
1956   // has a known-zero bit in a more significant place than it (not including the
1957   // sign bit) the ripple may go up to and fill the zero, but won't change the
1958   // sign.  For example, (X & ~4) + 1.
1959   
1960   // TODO: Implement.
1961   
1962   return false;
1963 }
1964
1965
1966 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1967   bool Changed = SimplifyCommutative(I);
1968   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1969
1970   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1971     // X + undef -> undef
1972     if (isa<UndefValue>(RHS))
1973       return ReplaceInstUsesWith(I, RHS);
1974
1975     // X + 0 --> X
1976     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1977       if (RHSC->isNullValue())
1978         return ReplaceInstUsesWith(I, LHS);
1979     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1980       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1981                               (I.getType())->getValueAPF()))
1982         return ReplaceInstUsesWith(I, LHS);
1983     }
1984
1985     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1986       // X + (signbit) --> X ^ signbit
1987       const APInt& Val = CI->getValue();
1988       uint32_t BitWidth = Val.getBitWidth();
1989       if (Val == APInt::getSignBit(BitWidth))
1990         return BinaryOperator::CreateXor(LHS, RHS);
1991       
1992       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1993       // (X & 254)+1 -> (X&254)|1
1994       if (!isa<VectorType>(I.getType())) {
1995         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1996         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1997                                  KnownZero, KnownOne))
1998           return &I;
1999       }
2000
2001       // zext(i1) - 1  ->  select i1, 0, -1
2002       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2003         if (CI->isAllOnesValue() &&
2004             ZI->getOperand(0)->getType() == Type::Int1Ty)
2005           return SelectInst::Create(ZI->getOperand(0),
2006                                     Constant::getNullValue(I.getType()),
2007                                     ConstantInt::getAllOnesValue(I.getType()));
2008     }
2009
2010     if (isa<PHINode>(LHS))
2011       if (Instruction *NV = FoldOpIntoPhi(I))
2012         return NV;
2013     
2014     ConstantInt *XorRHS = 0;
2015     Value *XorLHS = 0;
2016     if (isa<ConstantInt>(RHSC) &&
2017         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2018       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2019       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2020       
2021       uint32_t Size = TySizeBits / 2;
2022       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2023       APInt CFF80Val(-C0080Val);
2024       do {
2025         if (TySizeBits > Size) {
2026           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2027           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2028           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2029               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2030             // This is a sign extend if the top bits are known zero.
2031             if (!MaskedValueIsZero(XorLHS, 
2032                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2033               Size = 0;  // Not a sign ext, but can't be any others either.
2034             break;
2035           }
2036         }
2037         Size >>= 1;
2038         C0080Val = APIntOps::lshr(C0080Val, Size);
2039         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2040       } while (Size >= 1);
2041       
2042       // FIXME: This shouldn't be necessary. When the backends can handle types
2043       // with funny bit widths then this switch statement should be removed. It
2044       // is just here to get the size of the "middle" type back up to something
2045       // that the back ends can handle.
2046       const Type *MiddleType = 0;
2047       switch (Size) {
2048         default: break;
2049         case 32: MiddleType = Type::Int32Ty; break;
2050         case 16: MiddleType = Type::Int16Ty; break;
2051         case  8: MiddleType = Type::Int8Ty; break;
2052       }
2053       if (MiddleType) {
2054         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2055         InsertNewInstBefore(NewTrunc, I);
2056         return new SExtInst(NewTrunc, I.getType(), I.getName());
2057       }
2058     }
2059   }
2060
2061   if (I.getType() == Type::Int1Ty)
2062     return BinaryOperator::CreateXor(LHS, RHS);
2063
2064   // X + X --> X << 1
2065   if (I.getType()->isInteger()) {
2066     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2067
2068     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2069       if (RHSI->getOpcode() == Instruction::Sub)
2070         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2071           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2072     }
2073     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2074       if (LHSI->getOpcode() == Instruction::Sub)
2075         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2076           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2077     }
2078   }
2079
2080   // -A + B  -->  B - A
2081   // -A + -B  -->  -(A + B)
2082   if (Value *LHSV = dyn_castNegVal(LHS)) {
2083     if (LHS->getType()->isIntOrIntVector()) {
2084       if (Value *RHSV = dyn_castNegVal(RHS)) {
2085         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2086         InsertNewInstBefore(NewAdd, I);
2087         return BinaryOperator::CreateNeg(NewAdd);
2088       }
2089     }
2090     
2091     return BinaryOperator::CreateSub(RHS, LHSV);
2092   }
2093
2094   // A + -B  -->  A - B
2095   if (!isa<Constant>(RHS))
2096     if (Value *V = dyn_castNegVal(RHS))
2097       return BinaryOperator::CreateSub(LHS, V);
2098
2099
2100   ConstantInt *C2;
2101   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2102     if (X == RHS)   // X*C + X --> X * (C+1)
2103       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2104
2105     // X*C1 + X*C2 --> X * (C1+C2)
2106     ConstantInt *C1;
2107     if (X == dyn_castFoldableMul(RHS, C1))
2108       return BinaryOperator::CreateMul(X, Add(C1, C2));
2109   }
2110
2111   // X + X*C --> X * (C+1)
2112   if (dyn_castFoldableMul(RHS, C2) == LHS)
2113     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2114
2115   // X + ~X --> -1   since   ~X = -X-1
2116   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2117     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2118   
2119
2120   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2121   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2122     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2123       return R;
2124   
2125   // A+B --> A|B iff A and B have no bits set in common.
2126   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2127     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2128     APInt LHSKnownOne(IT->getBitWidth(), 0);
2129     APInt LHSKnownZero(IT->getBitWidth(), 0);
2130     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2131     if (LHSKnownZero != 0) {
2132       APInt RHSKnownOne(IT->getBitWidth(), 0);
2133       APInt RHSKnownZero(IT->getBitWidth(), 0);
2134       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2135       
2136       // No bits in common -> bitwise or.
2137       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2138         return BinaryOperator::CreateOr(LHS, RHS);
2139     }
2140   }
2141
2142   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2143   if (I.getType()->isIntOrIntVector()) {
2144     Value *W, *X, *Y, *Z;
2145     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2146         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2147       if (W != Y) {
2148         if (W == Z) {
2149           std::swap(Y, Z);
2150         } else if (Y == X) {
2151           std::swap(W, X);
2152         } else if (X == Z) {
2153           std::swap(Y, Z);
2154           std::swap(W, X);
2155         }
2156       }
2157
2158       if (W == Y) {
2159         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2160                                                             LHS->getName()), I);
2161         return BinaryOperator::CreateMul(W, NewAdd);
2162       }
2163     }
2164   }
2165
2166   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2167     Value *X = 0;
2168     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2169       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2170
2171     // (X & FF00) + xx00  -> (X+xx00) & FF00
2172     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2173       Constant *Anded = And(CRHS, C2);
2174       if (Anded == CRHS) {
2175         // See if all bits from the first bit set in the Add RHS up are included
2176         // in the mask.  First, get the rightmost bit.
2177         const APInt& AddRHSV = CRHS->getValue();
2178
2179         // Form a mask of all bits from the lowest bit added through the top.
2180         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2181
2182         // See if the and mask includes all of these bits.
2183         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2184
2185         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2186           // Okay, the xform is safe.  Insert the new add pronto.
2187           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2188                                                             LHS->getName()), I);
2189           return BinaryOperator::CreateAnd(NewAdd, C2);
2190         }
2191       }
2192     }
2193
2194     // Try to fold constant add into select arguments.
2195     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2196       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2197         return R;
2198   }
2199
2200   // add (cast *A to intptrtype) B -> 
2201   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2202   {
2203     CastInst *CI = dyn_cast<CastInst>(LHS);
2204     Value *Other = RHS;
2205     if (!CI) {
2206       CI = dyn_cast<CastInst>(RHS);
2207       Other = LHS;
2208     }
2209     if (CI && CI->getType()->isSized() && 
2210         (CI->getType()->getPrimitiveSizeInBits() == 
2211          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2212         && isa<PointerType>(CI->getOperand(0)->getType())) {
2213       unsigned AS =
2214         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2215       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2216                                       PointerType::get(Type::Int8Ty, AS), I);
2217       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2218       return new PtrToIntInst(I2, CI->getType());
2219     }
2220   }
2221   
2222   // add (select X 0 (sub n A)) A  -->  select X A n
2223   {
2224     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2225     Value *A = RHS;
2226     if (!SI) {
2227       SI = dyn_cast<SelectInst>(RHS);
2228       A = LHS;
2229     }
2230     if (SI && SI->hasOneUse()) {
2231       Value *TV = SI->getTrueValue();
2232       Value *FV = SI->getFalseValue();
2233       Value *N;
2234
2235       // Can we fold the add into the argument of the select?
2236       // We check both true and false select arguments for a matching subtract.
2237       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2238         // Fold the add into the true select value.
2239         return SelectInst::Create(SI->getCondition(), N, A);
2240       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2241         // Fold the add into the false select value.
2242         return SelectInst::Create(SI->getCondition(), A, N);
2243     }
2244   }
2245   
2246   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2247   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2248     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2249       return ReplaceInstUsesWith(I, LHS);
2250
2251   // Check for (add (sext x), y), see if we can merge this into an
2252   // integer add followed by a sext.
2253   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2254     // (add (sext x), cst) --> (sext (add x, cst'))
2255     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2256       Constant *CI = 
2257         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2258       if (LHSConv->hasOneUse() &&
2259           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2260           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2261         // Insert the new, smaller add.
2262         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2263                                                         CI, "addconv");
2264         InsertNewInstBefore(NewAdd, I);
2265         return new SExtInst(NewAdd, I.getType());
2266       }
2267     }
2268     
2269     // (add (sext x), (sext y)) --> (sext (add int x, y))
2270     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2271       // Only do this if x/y have the same type, if at last one of them has a
2272       // single use (so we don't increase the number of sexts), and if the
2273       // integer add will not overflow.
2274       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2275           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2276           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2277                                    RHSConv->getOperand(0))) {
2278         // Insert the new integer add.
2279         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2280                                                         RHSConv->getOperand(0),
2281                                                         "addconv");
2282         InsertNewInstBefore(NewAdd, I);
2283         return new SExtInst(NewAdd, I.getType());
2284       }
2285     }
2286   }
2287   
2288   // Check for (add double (sitofp x), y), see if we can merge this into an
2289   // integer add followed by a promotion.
2290   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2291     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2292     // ... if the constant fits in the integer value.  This is useful for things
2293     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2294     // requires a constant pool load, and generally allows the add to be better
2295     // instcombined.
2296     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2297       Constant *CI = 
2298       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2299       if (LHSConv->hasOneUse() &&
2300           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2301           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2302         // Insert the new integer add.
2303         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2304                                                         CI, "addconv");
2305         InsertNewInstBefore(NewAdd, I);
2306         return new SIToFPInst(NewAdd, I.getType());
2307       }
2308     }
2309     
2310     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2311     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2312       // Only do this if x/y have the same type, if at last one of them has a
2313       // single use (so we don't increase the number of int->fp conversions),
2314       // and if the integer add will not overflow.
2315       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2316           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2317           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2318                                    RHSConv->getOperand(0))) {
2319         // Insert the new integer add.
2320         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2321                                                         RHSConv->getOperand(0),
2322                                                         "addconv");
2323         InsertNewInstBefore(NewAdd, I);
2324         return new SIToFPInst(NewAdd, I.getType());
2325       }
2326     }
2327   }
2328   
2329   return Changed ? &I : 0;
2330 }
2331
2332 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2333   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2334
2335   if (Op0 == Op1 &&                        // sub X, X  -> 0
2336       !I.getType()->isFPOrFPVector())
2337     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2338
2339   // If this is a 'B = x-(-A)', change to B = x+A...
2340   if (Value *V = dyn_castNegVal(Op1))
2341     return BinaryOperator::CreateAdd(Op0, V);
2342
2343   if (isa<UndefValue>(Op0))
2344     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2345   if (isa<UndefValue>(Op1))
2346     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2347
2348   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2349     // Replace (-1 - A) with (~A)...
2350     if (C->isAllOnesValue())
2351       return BinaryOperator::CreateNot(Op1);
2352
2353     // C - ~X == X + (1+C)
2354     Value *X = 0;
2355     if (match(Op1, m_Not(m_Value(X))))
2356       return BinaryOperator::CreateAdd(X, AddOne(C));
2357
2358     // -(X >>u 31) -> (X >>s 31)
2359     // -(X >>s 31) -> (X >>u 31)
2360     if (C->isZero()) {
2361       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2362         if (SI->getOpcode() == Instruction::LShr) {
2363           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2364             // Check to see if we are shifting out everything but the sign bit.
2365             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2366                 SI->getType()->getPrimitiveSizeInBits()-1) {
2367               // Ok, the transformation is safe.  Insert AShr.
2368               return BinaryOperator::Create(Instruction::AShr, 
2369                                           SI->getOperand(0), CU, SI->getName());
2370             }
2371           }
2372         }
2373         else if (SI->getOpcode() == Instruction::AShr) {
2374           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2375             // Check to see if we are shifting out everything but the sign bit.
2376             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2377                 SI->getType()->getPrimitiveSizeInBits()-1) {
2378               // Ok, the transformation is safe.  Insert LShr. 
2379               return BinaryOperator::CreateLShr(
2380                                           SI->getOperand(0), CU, SI->getName());
2381             }
2382           }
2383         }
2384       }
2385     }
2386
2387     // Try to fold constant sub into select arguments.
2388     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2389       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2390         return R;
2391   }
2392
2393   if (I.getType() == Type::Int1Ty)
2394     return BinaryOperator::CreateXor(Op0, Op1);
2395
2396   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2397     if (Op1I->getOpcode() == Instruction::Add &&
2398         !Op0->getType()->isFPOrFPVector()) {
2399       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2400         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2401       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2402         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2403       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2404         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2405           // C1-(X+C2) --> (C1-C2)-X
2406           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2407                                            Op1I->getOperand(0));
2408       }
2409     }
2410
2411     if (Op1I->hasOneUse()) {
2412       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2413       // is not used by anyone else...
2414       //
2415       if (Op1I->getOpcode() == Instruction::Sub &&
2416           !Op1I->getType()->isFPOrFPVector()) {
2417         // Swap the two operands of the subexpr...
2418         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2419         Op1I->setOperand(0, IIOp1);
2420         Op1I->setOperand(1, IIOp0);
2421
2422         // Create the new top level add instruction...
2423         return BinaryOperator::CreateAdd(Op0, Op1);
2424       }
2425
2426       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2427       //
2428       if (Op1I->getOpcode() == Instruction::And &&
2429           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2430         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2431
2432         Value *NewNot =
2433           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2434         return BinaryOperator::CreateAnd(Op0, NewNot);
2435       }
2436
2437       // 0 - (X sdiv C)  -> (X sdiv -C)
2438       if (Op1I->getOpcode() == Instruction::SDiv)
2439         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2440           if (CSI->isZero())
2441             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2442               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2443                                                ConstantExpr::getNeg(DivRHS));
2444
2445       // X - X*C --> X * (1-C)
2446       ConstantInt *C2 = 0;
2447       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2448         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2449         return BinaryOperator::CreateMul(Op0, CP1);
2450       }
2451     }
2452   }
2453
2454   if (!Op0->getType()->isFPOrFPVector())
2455     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2456       if (Op0I->getOpcode() == Instruction::Add) {
2457         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2458           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2459         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2460           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2461       } else if (Op0I->getOpcode() == Instruction::Sub) {
2462         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2463           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2464       }
2465     }
2466
2467   ConstantInt *C1;
2468   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2469     if (X == Op1)  // X*C - X --> X * (C-1)
2470       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2471
2472     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2473     if (X == dyn_castFoldableMul(Op1, C2))
2474       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2475   }
2476   return 0;
2477 }
2478
2479 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2480 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2481 /// TrueIfSigned if the result of the comparison is true when the input value is
2482 /// signed.
2483 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2484                            bool &TrueIfSigned) {
2485   switch (pred) {
2486   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2487     TrueIfSigned = true;
2488     return RHS->isZero();
2489   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2490     TrueIfSigned = true;
2491     return RHS->isAllOnesValue();
2492   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2493     TrueIfSigned = false;
2494     return RHS->isAllOnesValue();
2495   case ICmpInst::ICMP_UGT:
2496     // True if LHS u> RHS and RHS == high-bit-mask - 1
2497     TrueIfSigned = true;
2498     return RHS->getValue() ==
2499       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2500   case ICmpInst::ICMP_UGE: 
2501     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2502     TrueIfSigned = true;
2503     return RHS->getValue().isSignBit();
2504   default:
2505     return false;
2506   }
2507 }
2508
2509 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2510   bool Changed = SimplifyCommutative(I);
2511   Value *Op0 = I.getOperand(0);
2512
2513   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2514     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2515
2516   // Simplify mul instructions with a constant RHS...
2517   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2518     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2519
2520       // ((X << C1)*C2) == (X * (C2 << C1))
2521       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2522         if (SI->getOpcode() == Instruction::Shl)
2523           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2524             return BinaryOperator::CreateMul(SI->getOperand(0),
2525                                              ConstantExpr::getShl(CI, ShOp));
2526
2527       if (CI->isZero())
2528         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2529       if (CI->equalsInt(1))                  // X * 1  == X
2530         return ReplaceInstUsesWith(I, Op0);
2531       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2532         return BinaryOperator::CreateNeg(Op0, I.getName());
2533
2534       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2535       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2536         return BinaryOperator::CreateShl(Op0,
2537                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2538       }
2539     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2540       if (Op1F->isNullValue())
2541         return ReplaceInstUsesWith(I, Op1);
2542
2543       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2544       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2545       if (Op1F->isExactlyValue(1.0))
2546         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2547     } else if (isa<VectorType>(Op1->getType())) {
2548       if (isa<ConstantAggregateZero>(Op1))
2549         return ReplaceInstUsesWith(I, Op1);
2550
2551       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2552         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2553           return BinaryOperator::CreateNeg(Op0, I.getName());
2554
2555         // As above, vector X*splat(1.0) -> X in all defined cases.
2556         if (Constant *Splat = Op1V->getSplatValue()) {
2557           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2558             if (F->isExactlyValue(1.0))
2559               return ReplaceInstUsesWith(I, Op0);
2560           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2561             if (CI->equalsInt(1))
2562               return ReplaceInstUsesWith(I, Op0);
2563         }
2564       }
2565     }
2566     
2567     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2568       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2569           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2570         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2571         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2572                                                      Op1, "tmp");
2573         InsertNewInstBefore(Add, I);
2574         Value *C1C2 = ConstantExpr::getMul(Op1, 
2575                                            cast<Constant>(Op0I->getOperand(1)));
2576         return BinaryOperator::CreateAdd(Add, C1C2);
2577         
2578       }
2579
2580     // Try to fold constant mul into select arguments.
2581     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2582       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2583         return R;
2584
2585     if (isa<PHINode>(Op0))
2586       if (Instruction *NV = FoldOpIntoPhi(I))
2587         return NV;
2588   }
2589
2590   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2591     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2592       return BinaryOperator::CreateMul(Op0v, Op1v);
2593
2594   // (X / Y) *  Y = X - (X % Y)
2595   // (X / Y) * -Y = (X % Y) - X
2596   {
2597     Value *Op1 = I.getOperand(1);
2598     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2599     if (!BO ||
2600         (BO->getOpcode() != Instruction::UDiv && 
2601          BO->getOpcode() != Instruction::SDiv)) {
2602       Op1 = Op0;
2603       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2604     }
2605     Value *Neg = dyn_castNegVal(Op1);
2606     if (BO && BO->hasOneUse() &&
2607         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2608         (BO->getOpcode() == Instruction::UDiv ||
2609          BO->getOpcode() == Instruction::SDiv)) {
2610       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2611
2612       Instruction *Rem;
2613       if (BO->getOpcode() == Instruction::UDiv)
2614         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2615       else
2616         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2617
2618       InsertNewInstBefore(Rem, I);
2619       Rem->takeName(BO);
2620
2621       if (Op1BO == Op1)
2622         return BinaryOperator::CreateSub(Op0BO, Rem);
2623       else
2624         return BinaryOperator::CreateSub(Rem, Op0BO);
2625     }
2626   }
2627
2628   if (I.getType() == Type::Int1Ty)
2629     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2630
2631   // If one of the operands of the multiply is a cast from a boolean value, then
2632   // we know the bool is either zero or one, so this is a 'masking' multiply.
2633   // See if we can simplify things based on how the boolean was originally
2634   // formed.
2635   CastInst *BoolCast = 0;
2636   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2637     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2638       BoolCast = CI;
2639   if (!BoolCast)
2640     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2641       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2642         BoolCast = CI;
2643   if (BoolCast) {
2644     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2645       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2646       const Type *SCOpTy = SCIOp0->getType();
2647       bool TIS = false;
2648       
2649       // If the icmp is true iff the sign bit of X is set, then convert this
2650       // multiply into a shift/and combination.
2651       if (isa<ConstantInt>(SCIOp1) &&
2652           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2653           TIS) {
2654         // Shift the X value right to turn it into "all signbits".
2655         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2656                                           SCOpTy->getPrimitiveSizeInBits()-1);
2657         Value *V =
2658           InsertNewInstBefore(
2659             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2660                                             BoolCast->getOperand(0)->getName()+
2661                                             ".mask"), I);
2662
2663         // If the multiply type is not the same as the source type, sign extend
2664         // or truncate to the multiply type.
2665         if (I.getType() != V->getType()) {
2666           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2667           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2668           Instruction::CastOps opcode = 
2669             (SrcBits == DstBits ? Instruction::BitCast : 
2670              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2671           V = InsertCastBefore(opcode, V, I.getType(), I);
2672         }
2673
2674         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2675         return BinaryOperator::CreateAnd(V, OtherOp);
2676       }
2677     }
2678   }
2679
2680   return Changed ? &I : 0;
2681 }
2682
2683 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2684 /// instruction.
2685 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2686   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2687   
2688   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2689   int NonNullOperand = -1;
2690   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2691     if (ST->isNullValue())
2692       NonNullOperand = 2;
2693   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2694   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2695     if (ST->isNullValue())
2696       NonNullOperand = 1;
2697   
2698   if (NonNullOperand == -1)
2699     return false;
2700   
2701   Value *SelectCond = SI->getOperand(0);
2702   
2703   // Change the div/rem to use 'Y' instead of the select.
2704   I.setOperand(1, SI->getOperand(NonNullOperand));
2705   
2706   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2707   // problem.  However, the select, or the condition of the select may have
2708   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2709   // propagate the known value for the select into other uses of it, and
2710   // propagate a known value of the condition into its other users.
2711   
2712   // If the select and condition only have a single use, don't bother with this,
2713   // early exit.
2714   if (SI->use_empty() && SelectCond->hasOneUse())
2715     return true;
2716   
2717   // Scan the current block backward, looking for other uses of SI.
2718   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2719   
2720   while (BBI != BBFront) {
2721     --BBI;
2722     // If we found a call to a function, we can't assume it will return, so
2723     // information from below it cannot be propagated above it.
2724     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2725       break;
2726     
2727     // Replace uses of the select or its condition with the known values.
2728     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2729          I != E; ++I) {
2730       if (*I == SI) {
2731         *I = SI->getOperand(NonNullOperand);
2732         AddToWorkList(BBI);
2733       } else if (*I == SelectCond) {
2734         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2735                                    ConstantInt::getFalse();
2736         AddToWorkList(BBI);
2737       }
2738     }
2739     
2740     // If we past the instruction, quit looking for it.
2741     if (&*BBI == SI)
2742       SI = 0;
2743     if (&*BBI == SelectCond)
2744       SelectCond = 0;
2745     
2746     // If we ran out of things to eliminate, break out of the loop.
2747     if (SelectCond == 0 && SI == 0)
2748       break;
2749     
2750   }
2751   return true;
2752 }
2753
2754
2755 /// This function implements the transforms on div instructions that work
2756 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2757 /// used by the visitors to those instructions.
2758 /// @brief Transforms common to all three div instructions
2759 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2760   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2761
2762   // undef / X -> 0        for integer.
2763   // undef / X -> undef    for FP (the undef could be a snan).
2764   if (isa<UndefValue>(Op0)) {
2765     if (Op0->getType()->isFPOrFPVector())
2766       return ReplaceInstUsesWith(I, Op0);
2767     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2768   }
2769
2770   // X / undef -> undef
2771   if (isa<UndefValue>(Op1))
2772     return ReplaceInstUsesWith(I, Op1);
2773
2774   return 0;
2775 }
2776
2777 /// This function implements the transforms common to both integer division
2778 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2779 /// division instructions.
2780 /// @brief Common integer divide transforms
2781 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2782   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2783
2784   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2785   if (Op0 == Op1) {
2786     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2787       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2788       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2789       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2790     }
2791
2792     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2793     return ReplaceInstUsesWith(I, CI);
2794   }
2795   
2796   if (Instruction *Common = commonDivTransforms(I))
2797     return Common;
2798   
2799   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2800   // This does not apply for fdiv.
2801   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2802     return &I;
2803
2804   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2805     // div X, 1 == X
2806     if (RHS->equalsInt(1))
2807       return ReplaceInstUsesWith(I, Op0);
2808
2809     // (X / C1) / C2  -> X / (C1*C2)
2810     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2811       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2812         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2813           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2814             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2815           else 
2816             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2817                                           Multiply(RHS, LHSRHS));
2818         }
2819
2820     if (!RHS->isZero()) { // avoid X udiv 0
2821       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2822         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2823           return R;
2824       if (isa<PHINode>(Op0))
2825         if (Instruction *NV = FoldOpIntoPhi(I))
2826           return NV;
2827     }
2828   }
2829
2830   // 0 / X == 0, we don't need to preserve faults!
2831   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2832     if (LHS->equalsInt(0))
2833       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2834
2835   // It can't be division by zero, hence it must be division by one.
2836   if (I.getType() == Type::Int1Ty)
2837     return ReplaceInstUsesWith(I, Op0);
2838
2839   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2840     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2841       // div X, 1 == X
2842       if (X->isOne())
2843         return ReplaceInstUsesWith(I, Op0);
2844   }
2845
2846   return 0;
2847 }
2848
2849 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2850   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2851
2852   // Handle the integer div common cases
2853   if (Instruction *Common = commonIDivTransforms(I))
2854     return Common;
2855
2856   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2857     // X udiv C^2 -> X >> C
2858     // Check to see if this is an unsigned division with an exact power of 2,
2859     // if so, convert to a right shift.
2860     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2861       return BinaryOperator::CreateLShr(Op0, 
2862                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2863
2864     // X udiv C, where C >= signbit
2865     if (C->getValue().isNegative()) {
2866       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2867                                       I);
2868       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2869                                 ConstantInt::get(I.getType(), 1));
2870     }
2871   }
2872
2873   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2874   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2875     if (RHSI->getOpcode() == Instruction::Shl &&
2876         isa<ConstantInt>(RHSI->getOperand(0))) {
2877       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2878       if (C1.isPowerOf2()) {
2879         Value *N = RHSI->getOperand(1);
2880         const Type *NTy = N->getType();
2881         if (uint32_t C2 = C1.logBase2()) {
2882           Constant *C2V = ConstantInt::get(NTy, C2);
2883           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2884         }
2885         return BinaryOperator::CreateLShr(Op0, N);
2886       }
2887     }
2888   }
2889   
2890   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2891   // where C1&C2 are powers of two.
2892   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2893     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2894       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2895         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2896         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2897           // Compute the shift amounts
2898           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2899           // Construct the "on true" case of the select
2900           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2901           Instruction *TSI = BinaryOperator::CreateLShr(
2902                                                  Op0, TC, SI->getName()+".t");
2903           TSI = InsertNewInstBefore(TSI, I);
2904   
2905           // Construct the "on false" case of the select
2906           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2907           Instruction *FSI = BinaryOperator::CreateLShr(
2908                                                  Op0, FC, SI->getName()+".f");
2909           FSI = InsertNewInstBefore(FSI, I);
2910
2911           // construct the select instruction and return it.
2912           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2913         }
2914       }
2915   return 0;
2916 }
2917
2918 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2919   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2920
2921   // Handle the integer div common cases
2922   if (Instruction *Common = commonIDivTransforms(I))
2923     return Common;
2924
2925   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2926     // sdiv X, -1 == -X
2927     if (RHS->isAllOnesValue())
2928       return BinaryOperator::CreateNeg(Op0);
2929
2930     ConstantInt *RHSNeg = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
2931     APInt RHSNegAPI(RHSNeg->getValue());
2932
2933     APInt NegOne = -APInt(RHSNeg->getBitWidth(), 1, true);
2934     APInt TwoToExp(RHSNeg->getBitWidth(), 1 << (RHSNeg->getBitWidth() - 1));
2935
2936     // -X/C -> X/-C, if and only if negation doesn't overflow.
2937     if ((RHS->getValue().isNegative() && RHSNegAPI.slt(TwoToExp - 1)) ||
2938         (RHS->getValue().isNonNegative() && RHSNegAPI.sgt(TwoToExp * NegOne))) {
2939       if (Value *LHSNeg = dyn_castNegVal(Op0)) {
2940         if (ConstantInt *CI = dyn_cast<ConstantInt>(LHSNeg)) {
2941           ConstantInt *CINeg = cast<ConstantInt>(ConstantExpr::getNeg(CI));
2942           APInt CINegAPI(CINeg->getValue());
2943
2944           if ((CI->getValue().isNegative() && CINegAPI.slt(TwoToExp - 1)) ||
2945               (CI->getValue().isNonNegative() && CINegAPI.sgt(TwoToExp*NegOne)))
2946             return BinaryOperator::CreateSDiv(LHSNeg,
2947                                               ConstantExpr::getNeg(RHS));
2948         }
2949       }
2950     }
2951   }
2952
2953   // If the sign bits of both operands are zero (i.e. we can prove they are
2954   // unsigned inputs), turn this into a udiv.
2955   if (I.getType()->isInteger()) {
2956     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2957     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2958       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2959       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2960     }
2961   }      
2962   
2963   return 0;
2964 }
2965
2966 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2967   return commonDivTransforms(I);
2968 }
2969
2970 /// This function implements the transforms on rem instructions that work
2971 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2972 /// is used by the visitors to those instructions.
2973 /// @brief Transforms common to all three rem instructions
2974 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2975   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2976
2977   // 0 % X == 0 for integer, we don't need to preserve faults!
2978   if (Constant *LHS = dyn_cast<Constant>(Op0))
2979     if (LHS->isNullValue())
2980       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2981
2982   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2983     if (I.getType()->isFPOrFPVector())
2984       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2985     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2986   }
2987   if (isa<UndefValue>(Op1))
2988     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2989
2990   // Handle cases involving: rem X, (select Cond, Y, Z)
2991   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2992     return &I;
2993
2994   return 0;
2995 }
2996
2997 /// This function implements the transforms common to both integer remainder
2998 /// instructions (urem and srem). It is called by the visitors to those integer
2999 /// remainder instructions.
3000 /// @brief Common integer remainder transforms
3001 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3002   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3003
3004   if (Instruction *common = commonRemTransforms(I))
3005     return common;
3006
3007   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3008     // X % 0 == undef, we don't need to preserve faults!
3009     if (RHS->equalsInt(0))
3010       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3011     
3012     if (RHS->equalsInt(1))  // X % 1 == 0
3013       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3014
3015     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3016       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3017         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3018           return R;
3019       } else if (isa<PHINode>(Op0I)) {
3020         if (Instruction *NV = FoldOpIntoPhi(I))
3021           return NV;
3022       }
3023
3024       // See if we can fold away this rem instruction.
3025       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3026       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3027       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3028                                KnownZero, KnownOne))
3029         return &I;
3030     }
3031   }
3032
3033   return 0;
3034 }
3035
3036 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3037   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039   if (Instruction *common = commonIRemTransforms(I))
3040     return common;
3041   
3042   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3043     // X urem C^2 -> X and C
3044     // Check to see if this is an unsigned remainder with an exact power of 2,
3045     // if so, convert to a bitwise and.
3046     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3047       if (C->getValue().isPowerOf2())
3048         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3049   }
3050
3051   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3052     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3053     if (RHSI->getOpcode() == Instruction::Shl &&
3054         isa<ConstantInt>(RHSI->getOperand(0))) {
3055       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3056         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3057         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3058                                                                    "tmp"), I);
3059         return BinaryOperator::CreateAnd(Op0, Add);
3060       }
3061     }
3062   }
3063
3064   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3065   // where C1&C2 are powers of two.
3066   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3067     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3068       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3069         // STO == 0 and SFO == 0 handled above.
3070         if ((STO->getValue().isPowerOf2()) && 
3071             (SFO->getValue().isPowerOf2())) {
3072           Value *TrueAnd = InsertNewInstBefore(
3073             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3074           Value *FalseAnd = InsertNewInstBefore(
3075             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3076           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3077         }
3078       }
3079   }
3080   
3081   return 0;
3082 }
3083
3084 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3085   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3086
3087   // Handle the integer rem common cases
3088   if (Instruction *common = commonIRemTransforms(I))
3089     return common;
3090   
3091   if (Value *RHSNeg = dyn_castNegVal(Op1))
3092     if (!isa<Constant>(RHSNeg) ||
3093         (isa<ConstantInt>(RHSNeg) &&
3094          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3095       // X % -Y -> X % Y
3096       AddUsesToWorkList(I);
3097       I.setOperand(1, RHSNeg);
3098       return &I;
3099     }
3100
3101   // If the sign bits of both operands are zero (i.e. we can prove they are
3102   // unsigned inputs), turn this into a urem.
3103   if (I.getType()->isInteger()) {
3104     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3105     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3106       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3107       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3108     }
3109   }
3110
3111   return 0;
3112 }
3113
3114 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3115   return commonRemTransforms(I);
3116 }
3117
3118 // isOneBitSet - Return true if there is exactly one bit set in the specified
3119 // constant.
3120 static bool isOneBitSet(const ConstantInt *CI) {
3121   return CI->getValue().isPowerOf2();
3122 }
3123
3124 // isHighOnes - Return true if the constant is of the form 1+0+.
3125 // This is the same as lowones(~X).
3126 static bool isHighOnes(const ConstantInt *CI) {
3127   return (~CI->getValue() + 1).isPowerOf2();
3128 }
3129
3130 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3131 /// are carefully arranged to allow folding of expressions such as:
3132 ///
3133 ///      (A < B) | (A > B) --> (A != B)
3134 ///
3135 /// Note that this is only valid if the first and second predicates have the
3136 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3137 ///
3138 /// Three bits are used to represent the condition, as follows:
3139 ///   0  A > B
3140 ///   1  A == B
3141 ///   2  A < B
3142 ///
3143 /// <=>  Value  Definition
3144 /// 000     0   Always false
3145 /// 001     1   A >  B
3146 /// 010     2   A == B
3147 /// 011     3   A >= B
3148 /// 100     4   A <  B
3149 /// 101     5   A != B
3150 /// 110     6   A <= B
3151 /// 111     7   Always true
3152 ///  
3153 static unsigned getICmpCode(const ICmpInst *ICI) {
3154   switch (ICI->getPredicate()) {
3155     // False -> 0
3156   case ICmpInst::ICMP_UGT: return 1;  // 001
3157   case ICmpInst::ICMP_SGT: return 1;  // 001
3158   case ICmpInst::ICMP_EQ:  return 2;  // 010
3159   case ICmpInst::ICMP_UGE: return 3;  // 011
3160   case ICmpInst::ICMP_SGE: return 3;  // 011
3161   case ICmpInst::ICMP_ULT: return 4;  // 100
3162   case ICmpInst::ICMP_SLT: return 4;  // 100
3163   case ICmpInst::ICMP_NE:  return 5;  // 101
3164   case ICmpInst::ICMP_ULE: return 6;  // 110
3165   case ICmpInst::ICMP_SLE: return 6;  // 110
3166     // True -> 7
3167   default:
3168     assert(0 && "Invalid ICmp predicate!");
3169     return 0;
3170   }
3171 }
3172
3173 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3174 /// predicate into a three bit mask. It also returns whether it is an ordered
3175 /// predicate by reference.
3176 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3177   isOrdered = false;
3178   switch (CC) {
3179   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3180   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3181   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3182   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3183   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3184   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3185   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3186   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3187   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3188   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3189   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3190   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3191   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3192   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3193     // True -> 7
3194   default:
3195     // Not expecting FCMP_FALSE and FCMP_TRUE;
3196     assert(0 && "Unexpected FCmp predicate!");
3197     return 0;
3198   }
3199 }
3200
3201 /// getICmpValue - This is the complement of getICmpCode, which turns an
3202 /// opcode and two operands into either a constant true or false, or a brand 
3203 /// new ICmp instruction. The sign is passed in to determine which kind
3204 /// of predicate to use in the new icmp instruction.
3205 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3206   switch (code) {
3207   default: assert(0 && "Illegal ICmp code!");
3208   case  0: return ConstantInt::getFalse();
3209   case  1: 
3210     if (sign)
3211       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3212     else
3213       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3214   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3215   case  3: 
3216     if (sign)
3217       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3218     else
3219       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3220   case  4: 
3221     if (sign)
3222       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3223     else
3224       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3225   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3226   case  6: 
3227     if (sign)
3228       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3229     else
3230       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3231   case  7: return ConstantInt::getTrue();
3232   }
3233 }
3234
3235 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3236 /// opcode and two operands into either a FCmp instruction. isordered is passed
3237 /// in to determine which kind of predicate to use in the new fcmp instruction.
3238 static Value *getFCmpValue(bool isordered, unsigned code,
3239                            Value *LHS, Value *RHS) {
3240   switch (code) {
3241   default: assert(0 && "Illegal FCmp code!");
3242   case  0:
3243     if (isordered)
3244       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3245     else
3246       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3247   case  1: 
3248     if (isordered)
3249       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3250     else
3251       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3252   case  2: 
3253     if (isordered)
3254       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3255     else
3256       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3257   case  3: 
3258     if (isordered)
3259       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3260     else
3261       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3262   case  4: 
3263     if (isordered)
3264       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3265     else
3266       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3267   case  5: 
3268     if (isordered)
3269       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3270     else
3271       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3272   case  6: 
3273     if (isordered)
3274       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3275     else
3276       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3277   case  7: return ConstantInt::getTrue();
3278   }
3279 }
3280
3281 /// PredicatesFoldable - Return true if both predicates match sign or if at
3282 /// least one of them is an equality comparison (which is signless).
3283 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3284   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3285          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3286          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3287 }
3288
3289 namespace { 
3290 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3291 struct FoldICmpLogical {
3292   InstCombiner &IC;
3293   Value *LHS, *RHS;
3294   ICmpInst::Predicate pred;
3295   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3296     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3297       pred(ICI->getPredicate()) {}
3298   bool shouldApply(Value *V) const {
3299     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3300       if (PredicatesFoldable(pred, ICI->getPredicate()))
3301         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3302                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3303     return false;
3304   }
3305   Instruction *apply(Instruction &Log) const {
3306     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3307     if (ICI->getOperand(0) != LHS) {
3308       assert(ICI->getOperand(1) == LHS);
3309       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3310     }
3311
3312     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3313     unsigned LHSCode = getICmpCode(ICI);
3314     unsigned RHSCode = getICmpCode(RHSICI);
3315     unsigned Code;
3316     switch (Log.getOpcode()) {
3317     case Instruction::And: Code = LHSCode & RHSCode; break;
3318     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3319     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3320     default: assert(0 && "Illegal logical opcode!"); return 0;
3321     }
3322
3323     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3324                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3325       
3326     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3327     if (Instruction *I = dyn_cast<Instruction>(RV))
3328       return I;
3329     // Otherwise, it's a constant boolean value...
3330     return IC.ReplaceInstUsesWith(Log, RV);
3331   }
3332 };
3333 } // end anonymous namespace
3334
3335 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3336 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3337 // guaranteed to be a binary operator.
3338 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3339                                     ConstantInt *OpRHS,
3340                                     ConstantInt *AndRHS,
3341                                     BinaryOperator &TheAnd) {
3342   Value *X = Op->getOperand(0);
3343   Constant *Together = 0;
3344   if (!Op->isShift())
3345     Together = And(AndRHS, OpRHS);
3346
3347   switch (Op->getOpcode()) {
3348   case Instruction::Xor:
3349     if (Op->hasOneUse()) {
3350       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3351       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3352       InsertNewInstBefore(And, TheAnd);
3353       And->takeName(Op);
3354       return BinaryOperator::CreateXor(And, Together);
3355     }
3356     break;
3357   case Instruction::Or:
3358     if (Together == AndRHS) // (X | C) & C --> C
3359       return ReplaceInstUsesWith(TheAnd, AndRHS);
3360
3361     if (Op->hasOneUse() && Together != OpRHS) {
3362       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3363       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3364       InsertNewInstBefore(Or, TheAnd);
3365       Or->takeName(Op);
3366       return BinaryOperator::CreateAnd(Or, AndRHS);
3367     }
3368     break;
3369   case Instruction::Add:
3370     if (Op->hasOneUse()) {
3371       // Adding a one to a single bit bit-field should be turned into an XOR
3372       // of the bit.  First thing to check is to see if this AND is with a
3373       // single bit constant.
3374       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3375
3376       // If there is only one bit set...
3377       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3378         // Ok, at this point, we know that we are masking the result of the
3379         // ADD down to exactly one bit.  If the constant we are adding has
3380         // no bits set below this bit, then we can eliminate the ADD.
3381         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3382
3383         // Check to see if any bits below the one bit set in AndRHSV are set.
3384         if ((AddRHS & (AndRHSV-1)) == 0) {
3385           // If not, the only thing that can effect the output of the AND is
3386           // the bit specified by AndRHSV.  If that bit is set, the effect of
3387           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3388           // no effect.
3389           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3390             TheAnd.setOperand(0, X);
3391             return &TheAnd;
3392           } else {
3393             // Pull the XOR out of the AND.
3394             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3395             InsertNewInstBefore(NewAnd, TheAnd);
3396             NewAnd->takeName(Op);
3397             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3398           }
3399         }
3400       }
3401     }
3402     break;
3403
3404   case Instruction::Shl: {
3405     // We know that the AND will not produce any of the bits shifted in, so if
3406     // the anded constant includes them, clear them now!
3407     //
3408     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3409     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3410     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3411     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3412
3413     if (CI->getValue() == ShlMask) { 
3414     // Masking out bits that the shift already masks
3415       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3416     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3417       TheAnd.setOperand(1, CI);
3418       return &TheAnd;
3419     }
3420     break;
3421   }
3422   case Instruction::LShr:
3423   {
3424     // We know that the AND will not produce any of the bits shifted in, so if
3425     // the anded constant includes them, clear them now!  This only applies to
3426     // unsigned shifts, because a signed shr may bring in set bits!
3427     //
3428     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3429     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3430     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3431     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3432
3433     if (CI->getValue() == ShrMask) {   
3434     // Masking out bits that the shift already masks.
3435       return ReplaceInstUsesWith(TheAnd, Op);
3436     } else if (CI != AndRHS) {
3437       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3438       return &TheAnd;
3439     }
3440     break;
3441   }
3442   case Instruction::AShr:
3443     // Signed shr.
3444     // See if this is shifting in some sign extension, then masking it out
3445     // with an and.
3446     if (Op->hasOneUse()) {
3447       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3448       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3449       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3450       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3451       if (C == AndRHS) {          // Masking out bits shifted in.
3452         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3453         // Make the argument unsigned.
3454         Value *ShVal = Op->getOperand(0);
3455         ShVal = InsertNewInstBefore(
3456             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3457                                    Op->getName()), TheAnd);
3458         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3459       }
3460     }
3461     break;
3462   }
3463   return 0;
3464 }
3465
3466
3467 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3468 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3469 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3470 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3471 /// insert new instructions.
3472 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3473                                            bool isSigned, bool Inside, 
3474                                            Instruction &IB) {
3475   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3476             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3477          "Lo is not <= Hi in range emission code!");
3478     
3479   if (Inside) {
3480     if (Lo == Hi)  // Trivially false.
3481       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3482
3483     // V >= Min && V < Hi --> V < Hi
3484     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3485       ICmpInst::Predicate pred = (isSigned ? 
3486         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3487       return new ICmpInst(pred, V, Hi);
3488     }
3489
3490     // Emit V-Lo <u Hi-Lo
3491     Constant *NegLo = ConstantExpr::getNeg(Lo);
3492     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3493     InsertNewInstBefore(Add, IB);
3494     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3495     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3496   }
3497
3498   if (Lo == Hi)  // Trivially true.
3499     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3500
3501   // V < Min || V >= Hi -> V > Hi-1
3502   Hi = SubOne(cast<ConstantInt>(Hi));
3503   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3504     ICmpInst::Predicate pred = (isSigned ? 
3505         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3506     return new ICmpInst(pred, V, Hi);
3507   }
3508
3509   // Emit V-Lo >u Hi-1-Lo
3510   // Note that Hi has already had one subtracted from it, above.
3511   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3512   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3513   InsertNewInstBefore(Add, IB);
3514   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3515   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3516 }
3517
3518 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3519 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3520 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3521 // not, since all 1s are not contiguous.
3522 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3523   const APInt& V = Val->getValue();
3524   uint32_t BitWidth = Val->getType()->getBitWidth();
3525   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3526
3527   // look for the first zero bit after the run of ones
3528   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3529   // look for the first non-zero bit
3530   ME = V.getActiveBits(); 
3531   return true;
3532 }
3533
3534 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3535 /// where isSub determines whether the operator is a sub.  If we can fold one of
3536 /// the following xforms:
3537 /// 
3538 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3539 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3540 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3541 ///
3542 /// return (A +/- B).
3543 ///
3544 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3545                                         ConstantInt *Mask, bool isSub,
3546                                         Instruction &I) {
3547   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3548   if (!LHSI || LHSI->getNumOperands() != 2 ||
3549       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3550
3551   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3552
3553   switch (LHSI->getOpcode()) {
3554   default: return 0;
3555   case Instruction::And:
3556     if (And(N, Mask) == Mask) {
3557       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3558       if ((Mask->getValue().countLeadingZeros() + 
3559            Mask->getValue().countPopulation()) == 
3560           Mask->getValue().getBitWidth())
3561         break;
3562
3563       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3564       // part, we don't need any explicit masks to take them out of A.  If that
3565       // is all N is, ignore it.
3566       uint32_t MB = 0, ME = 0;
3567       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3568         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3569         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3570         if (MaskedValueIsZero(RHS, Mask))
3571           break;
3572       }
3573     }
3574     return 0;
3575   case Instruction::Or:
3576   case Instruction::Xor:
3577     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3578     if ((Mask->getValue().countLeadingZeros() + 
3579          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3580         && And(N, Mask)->isZero())
3581       break;
3582     return 0;
3583   }
3584   
3585   Instruction *New;
3586   if (isSub)
3587     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3588   else
3589     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3590   return InsertNewInstBefore(New, I);
3591 }
3592
3593 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3594 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3595                                           ICmpInst *LHS, ICmpInst *RHS) {
3596   Value *Val, *Val2;
3597   ConstantInt *LHSCst, *RHSCst;
3598   ICmpInst::Predicate LHSCC, RHSCC;
3599   
3600   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3601   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3602       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3603     return 0;
3604   
3605   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3606   // where C is a power of 2
3607   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3608       LHSCst->getValue().isPowerOf2()) {
3609     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3610     InsertNewInstBefore(NewOr, I);
3611     return new ICmpInst(LHSCC, NewOr, LHSCst);
3612   }
3613   
3614   // From here on, we only handle:
3615   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3616   if (Val != Val2) return 0;
3617   
3618   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3619   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3620       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3621       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3622       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3623     return 0;
3624   
3625   // We can't fold (ugt x, C) & (sgt x, C2).
3626   if (!PredicatesFoldable(LHSCC, RHSCC))
3627     return 0;
3628     
3629   // Ensure that the larger constant is on the RHS.
3630   bool ShouldSwap;
3631   if (ICmpInst::isSignedPredicate(LHSCC) ||
3632       (ICmpInst::isEquality(LHSCC) && 
3633        ICmpInst::isSignedPredicate(RHSCC)))
3634     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3635   else
3636     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3637     
3638   if (ShouldSwap) {
3639     std::swap(LHS, RHS);
3640     std::swap(LHSCst, RHSCst);
3641     std::swap(LHSCC, RHSCC);
3642   }
3643
3644   // At this point, we know we have have two icmp instructions
3645   // comparing a value against two constants and and'ing the result
3646   // together.  Because of the above check, we know that we only have
3647   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3648   // (from the FoldICmpLogical check above), that the two constants 
3649   // are not equal and that the larger constant is on the RHS
3650   assert(LHSCst != RHSCst && "Compares not folded above?");
3651
3652   switch (LHSCC) {
3653   default: assert(0 && "Unknown integer condition code!");
3654   case ICmpInst::ICMP_EQ:
3655     switch (RHSCC) {
3656     default: assert(0 && "Unknown integer condition code!");
3657     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3658     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3659     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3660       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3661     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3662     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3663     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3664       return ReplaceInstUsesWith(I, LHS);
3665     }
3666   case ICmpInst::ICMP_NE:
3667     switch (RHSCC) {
3668     default: assert(0 && "Unknown integer condition code!");
3669     case ICmpInst::ICMP_ULT:
3670       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3671         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3672       break;                        // (X != 13 & X u< 15) -> no change
3673     case ICmpInst::ICMP_SLT:
3674       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3675         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3676       break;                        // (X != 13 & X s< 15) -> no change
3677     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3678     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3679     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3680       return ReplaceInstUsesWith(I, RHS);
3681     case ICmpInst::ICMP_NE:
3682       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3683         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3684         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3685                                                      Val->getName()+".off");
3686         InsertNewInstBefore(Add, I);
3687         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3688                             ConstantInt::get(Add->getType(), 1));
3689       }
3690       break;                        // (X != 13 & X != 15) -> no change
3691     }
3692     break;
3693   case ICmpInst::ICMP_ULT:
3694     switch (RHSCC) {
3695     default: assert(0 && "Unknown integer condition code!");
3696     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3697     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3698       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3699     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3700       break;
3701     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3702     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3703       return ReplaceInstUsesWith(I, LHS);
3704     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3705       break;
3706     }
3707     break;
3708   case ICmpInst::ICMP_SLT:
3709     switch (RHSCC) {
3710     default: assert(0 && "Unknown integer condition code!");
3711     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3712     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3713       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3714     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3715       break;
3716     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3717     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3718       return ReplaceInstUsesWith(I, LHS);
3719     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3720       break;
3721     }
3722     break;
3723   case ICmpInst::ICMP_UGT:
3724     switch (RHSCC) {
3725     default: assert(0 && "Unknown integer condition code!");
3726     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3727     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3728       return ReplaceInstUsesWith(I, RHS);
3729     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3730       break;
3731     case ICmpInst::ICMP_NE:
3732       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3733         return new ICmpInst(LHSCC, Val, RHSCst);
3734       break;                        // (X u> 13 & X != 15) -> no change
3735     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3736       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3737     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3738       break;
3739     }
3740     break;
3741   case ICmpInst::ICMP_SGT:
3742     switch (RHSCC) {
3743     default: assert(0 && "Unknown integer condition code!");
3744     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3745     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3746       return ReplaceInstUsesWith(I, RHS);
3747     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3748       break;
3749     case ICmpInst::ICMP_NE:
3750       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3751         return new ICmpInst(LHSCC, Val, RHSCst);
3752       break;                        // (X s> 13 & X != 15) -> no change
3753     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3754       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3755     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3756       break;
3757     }
3758     break;
3759   }
3760  
3761   return 0;
3762 }
3763
3764
3765 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3766   bool Changed = SimplifyCommutative(I);
3767   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3768
3769   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3770     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3771
3772   // and X, X = X
3773   if (Op0 == Op1)
3774     return ReplaceInstUsesWith(I, Op1);
3775
3776   // See if we can simplify any instructions used by the instruction whose sole 
3777   // purpose is to compute bits we don't care about.
3778   if (!isa<VectorType>(I.getType())) {
3779     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3780     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3781     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3782                              KnownZero, KnownOne))
3783       return &I;
3784   } else {
3785     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3786       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3787         return ReplaceInstUsesWith(I, I.getOperand(0));
3788     } else if (isa<ConstantAggregateZero>(Op1)) {
3789       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3790     }
3791   }
3792   
3793   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3794     const APInt& AndRHSMask = AndRHS->getValue();
3795     APInt NotAndRHS(~AndRHSMask);
3796
3797     // Optimize a variety of ((val OP C1) & C2) combinations...
3798     if (isa<BinaryOperator>(Op0)) {
3799       Instruction *Op0I = cast<Instruction>(Op0);
3800       Value *Op0LHS = Op0I->getOperand(0);
3801       Value *Op0RHS = Op0I->getOperand(1);
3802       switch (Op0I->getOpcode()) {
3803       case Instruction::Xor:
3804       case Instruction::Or:
3805         // If the mask is only needed on one incoming arm, push it up.
3806         if (Op0I->hasOneUse()) {
3807           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3808             // Not masking anything out for the LHS, move to RHS.
3809             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3810                                                    Op0RHS->getName()+".masked");
3811             InsertNewInstBefore(NewRHS, I);
3812             return BinaryOperator::Create(
3813                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3814           }
3815           if (!isa<Constant>(Op0RHS) &&
3816               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3817             // Not masking anything out for the RHS, move to LHS.
3818             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3819                                                    Op0LHS->getName()+".masked");
3820             InsertNewInstBefore(NewLHS, I);
3821             return BinaryOperator::Create(
3822                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3823           }
3824         }
3825
3826         break;
3827       case Instruction::Add:
3828         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3829         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3830         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3831         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3832           return BinaryOperator::CreateAnd(V, AndRHS);
3833         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3834           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3835         break;
3836
3837       case Instruction::Sub:
3838         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3839         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3840         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3841         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3842           return BinaryOperator::CreateAnd(V, AndRHS);
3843
3844         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3845         // has 1's for all bits that the subtraction with A might affect.
3846         if (Op0I->hasOneUse()) {
3847           uint32_t BitWidth = AndRHSMask.getBitWidth();
3848           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3849           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3850
3851           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3852           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3853               MaskedValueIsZero(Op0LHS, Mask)) {
3854             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3855             InsertNewInstBefore(NewNeg, I);
3856             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3857           }
3858         }
3859         break;
3860
3861       case Instruction::Shl:
3862       case Instruction::LShr:
3863         // (1 << x) & 1 --> zext(x == 0)
3864         // (1 >> x) & 1 --> zext(x == 0)
3865         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3866           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3867                                            Constant::getNullValue(I.getType()));
3868           InsertNewInstBefore(NewICmp, I);
3869           return new ZExtInst(NewICmp, I.getType());
3870         }
3871         break;
3872       }
3873
3874       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3875         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3876           return Res;
3877     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3878       // If this is an integer truncation or change from signed-to-unsigned, and
3879       // if the source is an and/or with immediate, transform it.  This
3880       // frequently occurs for bitfield accesses.
3881       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3882         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3883             CastOp->getNumOperands() == 2)
3884           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3885             if (CastOp->getOpcode() == Instruction::And) {
3886               // Change: and (cast (and X, C1) to T), C2
3887               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3888               // This will fold the two constants together, which may allow 
3889               // other simplifications.
3890               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3891                 CastOp->getOperand(0), I.getType(), 
3892                 CastOp->getName()+".shrunk");
3893               NewCast = InsertNewInstBefore(NewCast, I);
3894               // trunc_or_bitcast(C1)&C2
3895               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3896               C3 = ConstantExpr::getAnd(C3, AndRHS);
3897               return BinaryOperator::CreateAnd(NewCast, C3);
3898             } else if (CastOp->getOpcode() == Instruction::Or) {
3899               // Change: and (cast (or X, C1) to T), C2
3900               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3901               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3902               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3903                 return ReplaceInstUsesWith(I, AndRHS);
3904             }
3905           }
3906       }
3907     }
3908
3909     // Try to fold constant and into select arguments.
3910     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3911       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3912         return R;
3913     if (isa<PHINode>(Op0))
3914       if (Instruction *NV = FoldOpIntoPhi(I))
3915         return NV;
3916   }
3917
3918   Value *Op0NotVal = dyn_castNotVal(Op0);
3919   Value *Op1NotVal = dyn_castNotVal(Op1);
3920
3921   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3922     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3923
3924   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3925   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3926     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3927                                                I.getName()+".demorgan");
3928     InsertNewInstBefore(Or, I);
3929     return BinaryOperator::CreateNot(Or);
3930   }
3931   
3932   {
3933     Value *A = 0, *B = 0, *C = 0, *D = 0;
3934     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3935       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3936         return ReplaceInstUsesWith(I, Op1);
3937     
3938       // (A|B) & ~(A&B) -> A^B
3939       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3940         if ((A == C && B == D) || (A == D && B == C))
3941           return BinaryOperator::CreateXor(A, B);
3942       }
3943     }
3944     
3945     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3946       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3947         return ReplaceInstUsesWith(I, Op0);
3948
3949       // ~(A&B) & (A|B) -> A^B
3950       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3951         if ((A == C && B == D) || (A == D && B == C))
3952           return BinaryOperator::CreateXor(A, B);
3953       }
3954     }
3955     
3956     if (Op0->hasOneUse() &&
3957         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3958       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3959         I.swapOperands();     // Simplify below
3960         std::swap(Op0, Op1);
3961       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3962         cast<BinaryOperator>(Op0)->swapOperands();
3963         I.swapOperands();     // Simplify below
3964         std::swap(Op0, Op1);
3965       }
3966     }
3967
3968     if (Op1->hasOneUse() &&
3969         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3970       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3971         cast<BinaryOperator>(Op1)->swapOperands();
3972         std::swap(A, B);
3973       }
3974       if (A == Op0) {                                // A&(A^B) -> A & ~B
3975         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3976         InsertNewInstBefore(NotB, I);
3977         return BinaryOperator::CreateAnd(A, NotB);
3978       }
3979     }
3980
3981     // (A&((~A)|B)) -> A&B
3982     if (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B)))) {
3983       if (A == Op1)
3984         return BinaryOperator::CreateAnd(A, B);
3985     }
3986     if (match(Op0, m_Or(m_Value(A), m_Not(m_Value(B))))) {
3987       if (B == Op1)
3988         return BinaryOperator::CreateAnd(A, B);
3989     }
3990     if (match(Op1, m_Or(m_Not(m_Value(A)), m_Value(B)))) {
3991       if (A == Op0)
3992         return BinaryOperator::CreateAnd(A, B);
3993     }
3994     if (match(Op1, m_Or(m_Value(A), m_Not(m_Value(B))))) {
3995       if (B == Op0)
3996         return BinaryOperator::CreateAnd(A, B);
3997     }
3998   }
3999   
4000   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4001     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4002     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4003       return R;
4004
4005     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4006       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4007         return Res;
4008   }
4009
4010   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4011   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4012     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4013       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4014         const Type *SrcTy = Op0C->getOperand(0)->getType();
4015         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4016             // Only do this if the casts both really cause code to be generated.
4017             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4018                               I.getType(), TD) &&
4019             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4020                               I.getType(), TD)) {
4021           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4022                                                          Op1C->getOperand(0),
4023                                                          I.getName());
4024           InsertNewInstBefore(NewOp, I);
4025           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4026         }
4027       }
4028     
4029   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4030   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4033           SI0->getOperand(1) == SI1->getOperand(1) &&
4034           (SI0->hasOneUse() || SI1->hasOneUse())) {
4035         Instruction *NewOp =
4036           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4037                                                         SI1->getOperand(0),
4038                                                         SI0->getName()), I);
4039         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4040                                       SI1->getOperand(1));
4041       }
4042   }
4043
4044   // If and'ing two fcmp, try combine them into one.
4045   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4046     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4047       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4048           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4049         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4050         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4051           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4052             // If either of the constants are nans, then the whole thing returns
4053             // false.
4054             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4055               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4057                                 RHS->getOperand(0));
4058           }
4059       } else {
4060         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4061         FCmpInst::Predicate Op0CC, Op1CC;
4062         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4063             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4064           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4065             // Swap RHS operands to match LHS.
4066             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4067             std::swap(Op1LHS, Op1RHS);
4068           }
4069           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4070             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4071             if (Op0CC == Op1CC)
4072               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4073             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4074                      Op1CC == FCmpInst::FCMP_FALSE)
4075               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4076             else if (Op0CC == FCmpInst::FCMP_TRUE)
4077               return ReplaceInstUsesWith(I, Op1);
4078             else if (Op1CC == FCmpInst::FCMP_TRUE)
4079               return ReplaceInstUsesWith(I, Op0);
4080             bool Op0Ordered;
4081             bool Op1Ordered;
4082             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4083             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4084             if (Op1Pred == 0) {
4085               std::swap(Op0, Op1);
4086               std::swap(Op0Pred, Op1Pred);
4087               std::swap(Op0Ordered, Op1Ordered);
4088             }
4089             if (Op0Pred == 0) {
4090               // uno && ueq -> uno && (uno || eq) -> ueq
4091               // ord && olt -> ord && (ord && lt) -> olt
4092               if (Op0Ordered == Op1Ordered)
4093                 return ReplaceInstUsesWith(I, Op1);
4094               // uno && oeq -> uno && (ord && eq) -> false
4095               // uno && ord -> false
4096               if (!Op0Ordered)
4097                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098               // ord && ueq -> ord && (uno || eq) -> oeq
4099               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4100                                                     Op0LHS, Op0RHS));
4101             }
4102           }
4103         }
4104       }
4105     }
4106   }
4107
4108   return Changed ? &I : 0;
4109 }
4110
4111 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4112 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4113 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4114 /// the expression came from the corresponding "byte swapped" byte in some other
4115 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4116 /// we know that the expression deposits the low byte of %X into the high byte
4117 /// of the bswap result and that all other bytes are zero.  This expression is
4118 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4119 /// match.
4120 ///
4121 /// This function returns true if the match was unsuccessful and false if so.
4122 /// On entry to the function the "OverallLeftShift" is a signed integer value
4123 /// indicating the number of bytes that the subexpression is later shifted.  For
4124 /// example, if the expression is later right shifted by 16 bits, the
4125 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4126 /// byte of ByteValues is actually being set.
4127 ///
4128 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4129 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4130 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4131 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4132 /// always in the local (OverallLeftShift) coordinate space.
4133 ///
4134 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4135                               SmallVector<Value*, 8> &ByteValues) {
4136   if (Instruction *I = dyn_cast<Instruction>(V)) {
4137     // If this is an or instruction, it may be an inner node of the bswap.
4138     if (I->getOpcode() == Instruction::Or) {
4139       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4140                                ByteValues) ||
4141              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4142                                ByteValues);
4143     }
4144   
4145     // If this is a logical shift by a constant multiple of 8, recurse with
4146     // OverallLeftShift and ByteMask adjusted.
4147     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4148       unsigned ShAmt = 
4149         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4150       // Ensure the shift amount is defined and of a byte value.
4151       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4152         return true;
4153
4154       unsigned ByteShift = ShAmt >> 3;
4155       if (I->getOpcode() == Instruction::Shl) {
4156         // X << 2 -> collect(X, +2)
4157         OverallLeftShift += ByteShift;
4158         ByteMask >>= ByteShift;
4159       } else {
4160         // X >>u 2 -> collect(X, -2)
4161         OverallLeftShift -= ByteShift;
4162         ByteMask <<= ByteShift;
4163         ByteMask &= (~0U >> (32-ByteValues.size()));
4164       }
4165
4166       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4167       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4168
4169       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4170                                ByteValues);
4171     }
4172
4173     // If this is a logical 'and' with a mask that clears bytes, clear the
4174     // corresponding bytes in ByteMask.
4175     if (I->getOpcode() == Instruction::And &&
4176         isa<ConstantInt>(I->getOperand(1))) {
4177       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4178       unsigned NumBytes = ByteValues.size();
4179       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4180       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4181       
4182       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4183         // If this byte is masked out by a later operation, we don't care what
4184         // the and mask is.
4185         if ((ByteMask & (1 << i)) == 0)
4186           continue;
4187         
4188         // If the AndMask is all zeros for this byte, clear the bit.
4189         APInt MaskB = AndMask & Byte;
4190         if (MaskB == 0) {
4191           ByteMask &= ~(1U << i);
4192           continue;
4193         }
4194         
4195         // If the AndMask is not all ones for this byte, it's not a bytezap.
4196         if (MaskB != Byte)
4197           return true;
4198
4199         // Otherwise, this byte is kept.
4200       }
4201
4202       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4203                                ByteValues);
4204     }
4205   }
4206   
4207   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4208   // the input value to the bswap.  Some observations: 1) if more than one byte
4209   // is demanded from this input, then it could not be successfully assembled
4210   // into a byteswap.  At least one of the two bytes would not be aligned with
4211   // their ultimate destination.
4212   if (!isPowerOf2_32(ByteMask)) return true;
4213   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4214   
4215   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4216   // is demanded, it needs to go into byte 0 of the result.  This means that the
4217   // byte needs to be shifted until it lands in the right byte bucket.  The
4218   // shift amount depends on the position: if the byte is coming from the high
4219   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4220   // low part, it must be shifted left.
4221   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4222   if (InputByteNo < ByteValues.size()/2) {
4223     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4224       return true;
4225   } else {
4226     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4227       return true;
4228   }
4229   
4230   // If the destination byte value is already defined, the values are or'd
4231   // together, which isn't a bswap (unless it's an or of the same bits).
4232   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4233     return true;
4234   ByteValues[DestByteNo] = V;
4235   return false;
4236 }
4237
4238 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4239 /// If so, insert the new bswap intrinsic and return it.
4240 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4241   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4242   if (!ITy || ITy->getBitWidth() % 16 || 
4243       // ByteMask only allows up to 32-byte values.
4244       ITy->getBitWidth() > 32*8) 
4245     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4246   
4247   /// ByteValues - For each byte of the result, we keep track of which value
4248   /// defines each byte.
4249   SmallVector<Value*, 8> ByteValues;
4250   ByteValues.resize(ITy->getBitWidth()/8);
4251     
4252   // Try to find all the pieces corresponding to the bswap.
4253   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4254   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4255     return 0;
4256   
4257   // Check to see if all of the bytes come from the same value.
4258   Value *V = ByteValues[0];
4259   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4260   
4261   // Check to make sure that all of the bytes come from the same value.
4262   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4263     if (ByteValues[i] != V)
4264       return 0;
4265   const Type *Tys[] = { ITy };
4266   Module *M = I.getParent()->getParent()->getParent();
4267   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4268   return CallInst::Create(F, V);
4269 }
4270
4271 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4272 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4273 /// we can simplify this expression to "cond ? C : D or B".
4274 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4275                                          Value *C, Value *D) {
4276   // If A is not a select of -1/0, this cannot match.
4277   Value *Cond = 0;
4278   if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4279     return 0;
4280
4281   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4282   if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4283     return SelectInst::Create(Cond, C, B);
4284   if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4285     return SelectInst::Create(Cond, C, B);
4286   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4287   if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4288     return SelectInst::Create(Cond, C, D);
4289   if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4290     return SelectInst::Create(Cond, C, D);
4291   return 0;
4292 }
4293
4294 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4295 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4296                                          ICmpInst *LHS, ICmpInst *RHS) {
4297   Value *Val, *Val2;
4298   ConstantInt *LHSCst, *RHSCst;
4299   ICmpInst::Predicate LHSCC, RHSCC;
4300   
4301   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4302   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4303       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4304     return 0;
4305   
4306   // From here on, we only handle:
4307   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4308   if (Val != Val2) return 0;
4309   
4310   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4311   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4312       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4313       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4314       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4315     return 0;
4316   
4317   // We can't fold (ugt x, C) | (sgt x, C2).
4318   if (!PredicatesFoldable(LHSCC, RHSCC))
4319     return 0;
4320   
4321   // Ensure that the larger constant is on the RHS.
4322   bool ShouldSwap;
4323   if (ICmpInst::isSignedPredicate(LHSCC) ||
4324       (ICmpInst::isEquality(LHSCC) && 
4325        ICmpInst::isSignedPredicate(RHSCC)))
4326     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4327   else
4328     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4329   
4330   if (ShouldSwap) {
4331     std::swap(LHS, RHS);
4332     std::swap(LHSCst, RHSCst);
4333     std::swap(LHSCC, RHSCC);
4334   }
4335   
4336   // At this point, we know we have have two icmp instructions
4337   // comparing a value against two constants and or'ing the result
4338   // together.  Because of the above check, we know that we only have
4339   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4340   // FoldICmpLogical check above), that the two constants are not
4341   // equal.
4342   assert(LHSCst != RHSCst && "Compares not folded above?");
4343
4344   switch (LHSCC) {
4345   default: assert(0 && "Unknown integer condition code!");
4346   case ICmpInst::ICMP_EQ:
4347     switch (RHSCC) {
4348     default: assert(0 && "Unknown integer condition code!");
4349     case ICmpInst::ICMP_EQ:
4350       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4351         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4352         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4353                                                      Val->getName()+".off");
4354         InsertNewInstBefore(Add, I);
4355         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4356         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4357       }
4358       break;                         // (X == 13 | X == 15) -> no change
4359     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4360     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4361       break;
4362     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4363     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4364     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4365       return ReplaceInstUsesWith(I, RHS);
4366     }
4367     break;
4368   case ICmpInst::ICMP_NE:
4369     switch (RHSCC) {
4370     default: assert(0 && "Unknown integer condition code!");
4371     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4372     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4373     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4374       return ReplaceInstUsesWith(I, LHS);
4375     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4376     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4377     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4378       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4379     }
4380     break;
4381   case ICmpInst::ICMP_ULT:
4382     switch (RHSCC) {
4383     default: assert(0 && "Unknown integer condition code!");
4384     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4385       break;
4386     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4387       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4388       // this can cause overflow.
4389       if (RHSCst->isMaxValue(false))
4390         return ReplaceInstUsesWith(I, LHS);
4391       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4392     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4393       break;
4394     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4395     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4396       return ReplaceInstUsesWith(I, RHS);
4397     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4398       break;
4399     }
4400     break;
4401   case ICmpInst::ICMP_SLT:
4402     switch (RHSCC) {
4403     default: assert(0 && "Unknown integer condition code!");
4404     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4405       break;
4406     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4407       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4408       // this can cause overflow.
4409       if (RHSCst->isMaxValue(true))
4410         return ReplaceInstUsesWith(I, LHS);
4411       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4412     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4413       break;
4414     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4415     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4416       return ReplaceInstUsesWith(I, RHS);
4417     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4418       break;
4419     }
4420     break;
4421   case ICmpInst::ICMP_UGT:
4422     switch (RHSCC) {
4423     default: assert(0 && "Unknown integer condition code!");
4424     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4425     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4426       return ReplaceInstUsesWith(I, LHS);
4427     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4428       break;
4429     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4430     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4431       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4433       break;
4434     }
4435     break;
4436   case ICmpInst::ICMP_SGT:
4437     switch (RHSCC) {
4438     default: assert(0 && "Unknown integer condition code!");
4439     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4440     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4441       return ReplaceInstUsesWith(I, LHS);
4442     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4443       break;
4444     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4445     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4446       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4447     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4448       break;
4449     }
4450     break;
4451   }
4452   return 0;
4453 }
4454
4455 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4456   bool Changed = SimplifyCommutative(I);
4457   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4458
4459   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4460     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4461
4462   // or X, X = X
4463   if (Op0 == Op1)
4464     return ReplaceInstUsesWith(I, Op0);
4465
4466   // See if we can simplify any instructions used by the instruction whose sole 
4467   // purpose is to compute bits we don't care about.
4468   if (!isa<VectorType>(I.getType())) {
4469     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4470     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4471     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4472                              KnownZero, KnownOne))
4473       return &I;
4474   } else if (isa<ConstantAggregateZero>(Op1)) {
4475     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4476   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4477     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4478       return ReplaceInstUsesWith(I, I.getOperand(1));
4479   }
4480     
4481
4482   
4483   // or X, -1 == -1
4484   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4485     ConstantInt *C1 = 0; Value *X = 0;
4486     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4487     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4488       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4489       InsertNewInstBefore(Or, I);
4490       Or->takeName(Op0);
4491       return BinaryOperator::CreateAnd(Or, 
4492                ConstantInt::get(RHS->getValue() | C1->getValue()));
4493     }
4494
4495     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4496     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4497       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4498       InsertNewInstBefore(Or, I);
4499       Or->takeName(Op0);
4500       return BinaryOperator::CreateXor(Or,
4501                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4502     }
4503
4504     // Try to fold constant and into select arguments.
4505     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4506       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4507         return R;
4508     if (isa<PHINode>(Op0))
4509       if (Instruction *NV = FoldOpIntoPhi(I))
4510         return NV;
4511   }
4512
4513   Value *A = 0, *B = 0;
4514   ConstantInt *C1 = 0, *C2 = 0;
4515
4516   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4517     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4518       return ReplaceInstUsesWith(I, Op1);
4519   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4520     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4521       return ReplaceInstUsesWith(I, Op0);
4522
4523   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4524   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4525   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4526       match(Op1, m_Or(m_Value(), m_Value())) ||
4527       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4528        match(Op1, m_Shift(m_Value(), m_Value())))) {
4529     if (Instruction *BSwap = MatchBSwap(I))
4530       return BSwap;
4531   }
4532   
4533   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4534   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4535       MaskedValueIsZero(Op1, C1->getValue())) {
4536     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4537     InsertNewInstBefore(NOr, I);
4538     NOr->takeName(Op0);
4539     return BinaryOperator::CreateXor(NOr, C1);
4540   }
4541
4542   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4543   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4544       MaskedValueIsZero(Op0, C1->getValue())) {
4545     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4546     InsertNewInstBefore(NOr, I);
4547     NOr->takeName(Op0);
4548     return BinaryOperator::CreateXor(NOr, C1);
4549   }
4550
4551   // (A & C)|(B & D)
4552   Value *C = 0, *D = 0;
4553   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4554       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4555     Value *V1 = 0, *V2 = 0, *V3 = 0;
4556     C1 = dyn_cast<ConstantInt>(C);
4557     C2 = dyn_cast<ConstantInt>(D);
4558     if (C1 && C2) {  // (A & C1)|(B & C2)
4559       // If we have: ((V + N) & C1) | (V & C2)
4560       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4561       // replace with V+N.
4562       if (C1->getValue() == ~C2->getValue()) {
4563         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4564             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4565           // Add commutes, try both ways.
4566           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4567             return ReplaceInstUsesWith(I, A);
4568           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4569             return ReplaceInstUsesWith(I, A);
4570         }
4571         // Or commutes, try both ways.
4572         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4573             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4574           // Add commutes, try both ways.
4575           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4576             return ReplaceInstUsesWith(I, B);
4577           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4578             return ReplaceInstUsesWith(I, B);
4579         }
4580       }
4581       V1 = 0; V2 = 0; V3 = 0;
4582     }
4583     
4584     // Check to see if we have any common things being and'ed.  If so, find the
4585     // terms for V1 & (V2|V3).
4586     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4587       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4588         V1 = A, V2 = C, V3 = D;
4589       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4590         V1 = A, V2 = B, V3 = C;
4591       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4592         V1 = C, V2 = A, V3 = D;
4593       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4594         V1 = C, V2 = A, V3 = B;
4595       
4596       if (V1) {
4597         Value *Or =
4598           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4599         return BinaryOperator::CreateAnd(V1, Or);
4600       }
4601     }
4602
4603     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4604     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4605       return Match;
4606     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4607       return Match;
4608     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4609       return Match;
4610     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4611       return Match;
4612
4613     V1 = V2 = 0;
4614
4615     // ((A&~B)|(~A&B)) -> A^B
4616     if ((match(C, m_Not(m_Value(V1))) &&
4617          match(B, m_Not(m_Value(V2)))))
4618       if (V1 == D && V2 == A)
4619         return BinaryOperator::CreateXor(V1, V2);
4620     // ((~B&A)|(~A&B)) -> A^B
4621     if ((match(A, m_Not(m_Value(V1))) &&
4622          match(B, m_Not(m_Value(V2)))))
4623       if (V1 == D && V2 == C)
4624         return BinaryOperator::CreateXor(V1, V2);
4625     // ((A&~B)|(B&~A)) -> A^B
4626     if ((match(C, m_Not(m_Value(V1))) &&
4627          match(D, m_Not(m_Value(V2)))))
4628       if (V1 == B && V2 == A)
4629         return BinaryOperator::CreateXor(V1, V2);
4630     // ((~B&A)|(B&~A)) -> A^B
4631     if ((match(A, m_Not(m_Value(V1))) &&
4632          match(D, m_Not(m_Value(V2)))))
4633       if (V1 == B && V2 == C)
4634         return BinaryOperator::CreateXor(V1, V2);
4635   }
4636   
4637   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4638   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4639     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4640       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4641           SI0->getOperand(1) == SI1->getOperand(1) &&
4642           (SI0->hasOneUse() || SI1->hasOneUse())) {
4643         Instruction *NewOp =
4644         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4645                                                      SI1->getOperand(0),
4646                                                      SI0->getName()), I);
4647         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4648                                       SI1->getOperand(1));
4649       }
4650   }
4651
4652   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4653     if (A == Op1)   // ~A | A == -1
4654       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4655   } else {
4656     A = 0;
4657   }
4658   // Note, A is still live here!
4659   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4660     if (Op0 == B)
4661       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4662
4663     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4664     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4665       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4666                                               I.getName()+".demorgan"), I);
4667       return BinaryOperator::CreateNot(And);
4668     }
4669   }
4670
4671   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4672   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4673     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4674       return R;
4675
4676     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4677       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4678         return Res;
4679   }
4680     
4681   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4682   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4683     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4684       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4685         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4686             !isa<ICmpInst>(Op1C->getOperand(0))) {
4687           const Type *SrcTy = Op0C->getOperand(0)->getType();
4688           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4689               // Only do this if the casts both really cause code to be
4690               // generated.
4691               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4692                                 I.getType(), TD) &&
4693               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4694                                 I.getType(), TD)) {
4695             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4696                                                           Op1C->getOperand(0),
4697                                                           I.getName());
4698             InsertNewInstBefore(NewOp, I);
4699             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4700           }
4701         }
4702       }
4703   }
4704   
4705     
4706   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4707   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4708     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4709       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4710           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4711           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4712         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4713           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4714             // If either of the constants are nans, then the whole thing returns
4715             // true.
4716             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4717               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4718             
4719             // Otherwise, no need to compare the two constants, compare the
4720             // rest.
4721             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4722                                 RHS->getOperand(0));
4723           }
4724       } else {
4725         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4726         FCmpInst::Predicate Op0CC, Op1CC;
4727         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4728             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4729           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4730             // Swap RHS operands to match LHS.
4731             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4732             std::swap(Op1LHS, Op1RHS);
4733           }
4734           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4735             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4736             if (Op0CC == Op1CC)
4737               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4738             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4739                      Op1CC == FCmpInst::FCMP_TRUE)
4740               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4741             else if (Op0CC == FCmpInst::FCMP_FALSE)
4742               return ReplaceInstUsesWith(I, Op1);
4743             else if (Op1CC == FCmpInst::FCMP_FALSE)
4744               return ReplaceInstUsesWith(I, Op0);
4745             bool Op0Ordered;
4746             bool Op1Ordered;
4747             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4748             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4749             if (Op0Ordered == Op1Ordered) {
4750               // If both are ordered or unordered, return a new fcmp with
4751               // or'ed predicates.
4752               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4753                                        Op0LHS, Op0RHS);
4754               if (Instruction *I = dyn_cast<Instruction>(RV))
4755                 return I;
4756               // Otherwise, it's a constant boolean value...
4757               return ReplaceInstUsesWith(I, RV);
4758             }
4759           }
4760         }
4761       }
4762     }
4763   }
4764
4765   return Changed ? &I : 0;
4766 }
4767
4768 namespace {
4769
4770 // XorSelf - Implements: X ^ X --> 0
4771 struct XorSelf {
4772   Value *RHS;
4773   XorSelf(Value *rhs) : RHS(rhs) {}
4774   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4775   Instruction *apply(BinaryOperator &Xor) const {
4776     return &Xor;
4777   }
4778 };
4779
4780 }
4781
4782 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4783   bool Changed = SimplifyCommutative(I);
4784   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4785
4786   if (isa<UndefValue>(Op1)) {
4787     if (isa<UndefValue>(Op0))
4788       // Handle undef ^ undef -> 0 special case. This is a common
4789       // idiom (misuse).
4790       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4791     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4792   }
4793
4794   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4795   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4796     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4797     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4798   }
4799   
4800   // See if we can simplify any instructions used by the instruction whose sole 
4801   // purpose is to compute bits we don't care about.
4802   if (!isa<VectorType>(I.getType())) {
4803     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4804     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4805     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4806                              KnownZero, KnownOne))
4807       return &I;
4808   } else if (isa<ConstantAggregateZero>(Op1)) {
4809     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4810   }
4811
4812   // Is this a ~ operation?
4813   if (Value *NotOp = dyn_castNotVal(&I)) {
4814     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4815     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4816     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4817       if (Op0I->getOpcode() == Instruction::And || 
4818           Op0I->getOpcode() == Instruction::Or) {
4819         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4820         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4821           Instruction *NotY =
4822             BinaryOperator::CreateNot(Op0I->getOperand(1),
4823                                       Op0I->getOperand(1)->getName()+".not");
4824           InsertNewInstBefore(NotY, I);
4825           if (Op0I->getOpcode() == Instruction::And)
4826             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4827           else
4828             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4829         }
4830       }
4831     }
4832   }
4833   
4834   
4835   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4836     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4837     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4838       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4839         return new ICmpInst(ICI->getInversePredicate(),
4840                             ICI->getOperand(0), ICI->getOperand(1));
4841
4842       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4843         return new FCmpInst(FCI->getInversePredicate(),
4844                             FCI->getOperand(0), FCI->getOperand(1));
4845     }
4846
4847     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4848     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4849       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4850         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4851           Instruction::CastOps Opcode = Op0C->getOpcode();
4852           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4853             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4854                                              Op0C->getDestTy())) {
4855               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4856                                      CI->getOpcode(), CI->getInversePredicate(),
4857                                      CI->getOperand(0), CI->getOperand(1)), I);
4858               NewCI->takeName(CI);
4859               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4860             }
4861           }
4862         }
4863       }
4864     }
4865
4866     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4867       // ~(c-X) == X-c-1 == X+(-c-1)
4868       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4869         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4870           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4871           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4872                                               ConstantInt::get(I.getType(), 1));
4873           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4874         }
4875           
4876       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4877         if (Op0I->getOpcode() == Instruction::Add) {
4878           // ~(X-c) --> (-c-1)-X
4879           if (RHS->isAllOnesValue()) {
4880             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4881             return BinaryOperator::CreateSub(
4882                            ConstantExpr::getSub(NegOp0CI,
4883                                              ConstantInt::get(I.getType(), 1)),
4884                                           Op0I->getOperand(0));
4885           } else if (RHS->getValue().isSignBit()) {
4886             // (X + C) ^ signbit -> (X + C + signbit)
4887             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4888             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4889
4890           }
4891         } else if (Op0I->getOpcode() == Instruction::Or) {
4892           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4893           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4894             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4895             // Anything in both C1 and C2 is known to be zero, remove it from
4896             // NewRHS.
4897             Constant *CommonBits = And(Op0CI, RHS);
4898             NewRHS = ConstantExpr::getAnd(NewRHS, 
4899                                           ConstantExpr::getNot(CommonBits));
4900             AddToWorkList(Op0I);
4901             I.setOperand(0, Op0I->getOperand(0));
4902             I.setOperand(1, NewRHS);
4903             return &I;
4904           }
4905         }
4906       }
4907     }
4908
4909     // Try to fold constant and into select arguments.
4910     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4911       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4912         return R;
4913     if (isa<PHINode>(Op0))
4914       if (Instruction *NV = FoldOpIntoPhi(I))
4915         return NV;
4916   }
4917
4918   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4919     if (X == Op1)
4920       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4921
4922   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4923     if (X == Op0)
4924       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4925
4926   
4927   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4928   if (Op1I) {
4929     Value *A, *B;
4930     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4931       if (A == Op0) {              // B^(B|A) == (A|B)^B
4932         Op1I->swapOperands();
4933         I.swapOperands();
4934         std::swap(Op0, Op1);
4935       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4936         I.swapOperands();     // Simplified below.
4937         std::swap(Op0, Op1);
4938       }
4939     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4940       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
4941     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4942       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
4943     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4944       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4945         Op1I->swapOperands();
4946         std::swap(A, B);
4947       }
4948       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4949         I.swapOperands();     // Simplified below.
4950         std::swap(Op0, Op1);
4951       }
4952     }
4953   }
4954   
4955   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4956   if (Op0I) {
4957     Value *A, *B;
4958     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4959       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4960         std::swap(A, B);
4961       if (B == Op1) {                                // (A|B)^B == A & ~B
4962         Instruction *NotB =
4963           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4964         return BinaryOperator::CreateAnd(A, NotB);
4965       }
4966     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4967       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
4968     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4969       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
4970     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4971       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4972         std::swap(A, B);
4973       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4974           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4975         Instruction *N =
4976           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4977         return BinaryOperator::CreateAnd(N, Op1);
4978       }
4979     }
4980   }
4981   
4982   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4983   if (Op0I && Op1I && Op0I->isShift() && 
4984       Op0I->getOpcode() == Op1I->getOpcode() && 
4985       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4986       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4987     Instruction *NewOp =
4988       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4989                                                     Op1I->getOperand(0),
4990                                                     Op0I->getName()), I);
4991     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4992                                   Op1I->getOperand(1));
4993   }
4994     
4995   if (Op0I && Op1I) {
4996     Value *A, *B, *C, *D;
4997     // (A & B)^(A | B) -> A ^ B
4998     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4999         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5000       if ((A == C && B == D) || (A == D && B == C)) 
5001         return BinaryOperator::CreateXor(A, B);
5002     }
5003     // (A | B)^(A & B) -> A ^ B
5004     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5005         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5006       if ((A == C && B == D) || (A == D && B == C)) 
5007         return BinaryOperator::CreateXor(A, B);
5008     }
5009     
5010     // (A & B)^(C & D)
5011     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5012         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5013         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5014       // (X & Y)^(X & Y) -> (Y^Z) & X
5015       Value *X = 0, *Y = 0, *Z = 0;
5016       if (A == C)
5017         X = A, Y = B, Z = D;
5018       else if (A == D)
5019         X = A, Y = B, Z = C;
5020       else if (B == C)
5021         X = B, Y = A, Z = D;
5022       else if (B == D)
5023         X = B, Y = A, Z = C;
5024       
5025       if (X) {
5026         Instruction *NewOp =
5027         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5028         return BinaryOperator::CreateAnd(NewOp, X);
5029       }
5030     }
5031   }
5032     
5033   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5034   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5035     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5036       return R;
5037
5038   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5039   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5040     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5041       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5042         const Type *SrcTy = Op0C->getOperand(0)->getType();
5043         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5044             // Only do this if the casts both really cause code to be generated.
5045             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5046                               I.getType(), TD) &&
5047             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5048                               I.getType(), TD)) {
5049           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5050                                                          Op1C->getOperand(0),
5051                                                          I.getName());
5052           InsertNewInstBefore(NewOp, I);
5053           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5054         }
5055       }
5056   }
5057
5058   return Changed ? &I : 0;
5059 }
5060
5061 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5062 /// overflowed for this type.
5063 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5064                             ConstantInt *In2, bool IsSigned = false) {
5065   Result = cast<ConstantInt>(Add(In1, In2));
5066
5067   if (IsSigned)
5068     if (In2->getValue().isNegative())
5069       return Result->getValue().sgt(In1->getValue());
5070     else
5071       return Result->getValue().slt(In1->getValue());
5072   else
5073     return Result->getValue().ult(In1->getValue());
5074 }
5075
5076 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5077 /// overflowed for this type.
5078 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5079                             ConstantInt *In2, bool IsSigned = false) {
5080   Result = cast<ConstantInt>(Subtract(In1, In2));
5081
5082   if (IsSigned)
5083     if (In2->getValue().isNegative())
5084       return Result->getValue().slt(In1->getValue());
5085     else
5086       return Result->getValue().sgt(In1->getValue());
5087   else
5088     return Result->getValue().ugt(In1->getValue());
5089 }
5090
5091 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5092 /// code necessary to compute the offset from the base pointer (without adding
5093 /// in the base pointer).  Return the result as a signed integer of intptr size.
5094 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5095   TargetData &TD = IC.getTargetData();
5096   gep_type_iterator GTI = gep_type_begin(GEP);
5097   const Type *IntPtrTy = TD.getIntPtrType();
5098   Value *Result = Constant::getNullValue(IntPtrTy);
5099
5100   // Build a mask for high order bits.
5101   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5102   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5103
5104   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5105        ++i, ++GTI) {
5106     Value *Op = *i;
5107     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5108     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5109       if (OpC->isZero()) continue;
5110       
5111       // Handle a struct index, which adds its field offset to the pointer.
5112       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5113         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5114         
5115         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5116           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5117         else
5118           Result = IC.InsertNewInstBefore(
5119                    BinaryOperator::CreateAdd(Result,
5120                                              ConstantInt::get(IntPtrTy, Size),
5121                                              GEP->getName()+".offs"), I);
5122         continue;
5123       }
5124       
5125       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5126       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5127       Scale = ConstantExpr::getMul(OC, Scale);
5128       if (Constant *RC = dyn_cast<Constant>(Result))
5129         Result = ConstantExpr::getAdd(RC, Scale);
5130       else {
5131         // Emit an add instruction.
5132         Result = IC.InsertNewInstBefore(
5133            BinaryOperator::CreateAdd(Result, Scale,
5134                                      GEP->getName()+".offs"), I);
5135       }
5136       continue;
5137     }
5138     // Convert to correct type.
5139     if (Op->getType() != IntPtrTy) {
5140       if (Constant *OpC = dyn_cast<Constant>(Op))
5141         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5142       else
5143         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5144                                                  Op->getName()+".c"), I);
5145     }
5146     if (Size != 1) {
5147       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5148       if (Constant *OpC = dyn_cast<Constant>(Op))
5149         Op = ConstantExpr::getMul(OpC, Scale);
5150       else    // We'll let instcombine(mul) convert this to a shl if possible.
5151         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5152                                                   GEP->getName()+".idx"), I);
5153     }
5154
5155     // Emit an add instruction.
5156     if (isa<Constant>(Op) && isa<Constant>(Result))
5157       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5158                                     cast<Constant>(Result));
5159     else
5160       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5161                                                   GEP->getName()+".offs"), I);
5162   }
5163   return Result;
5164 }
5165
5166
5167 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5168 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5169 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5170 /// complex, and scales are involved.  The above expression would also be legal
5171 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5172 /// later form is less amenable to optimization though, and we are allowed to
5173 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5174 ///
5175 /// If we can't emit an optimized form for this expression, this returns null.
5176 /// 
5177 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5178                                           InstCombiner &IC) {
5179   TargetData &TD = IC.getTargetData();
5180   gep_type_iterator GTI = gep_type_begin(GEP);
5181
5182   // Check to see if this gep only has a single variable index.  If so, and if
5183   // any constant indices are a multiple of its scale, then we can compute this
5184   // in terms of the scale of the variable index.  For example, if the GEP
5185   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5186   // because the expression will cross zero at the same point.
5187   unsigned i, e = GEP->getNumOperands();
5188   int64_t Offset = 0;
5189   for (i = 1; i != e; ++i, ++GTI) {
5190     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5191       // Compute the aggregate offset of constant indices.
5192       if (CI->isZero()) continue;
5193
5194       // Handle a struct index, which adds its field offset to the pointer.
5195       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5196         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5197       } else {
5198         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5199         Offset += Size*CI->getSExtValue();
5200       }
5201     } else {
5202       // Found our variable index.
5203       break;
5204     }
5205   }
5206   
5207   // If there are no variable indices, we must have a constant offset, just
5208   // evaluate it the general way.
5209   if (i == e) return 0;
5210   
5211   Value *VariableIdx = GEP->getOperand(i);
5212   // Determine the scale factor of the variable element.  For example, this is
5213   // 4 if the variable index is into an array of i32.
5214   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5215   
5216   // Verify that there are no other variable indices.  If so, emit the hard way.
5217   for (++i, ++GTI; i != e; ++i, ++GTI) {
5218     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5219     if (!CI) return 0;
5220    
5221     // Compute the aggregate offset of constant indices.
5222     if (CI->isZero()) continue;
5223     
5224     // Handle a struct index, which adds its field offset to the pointer.
5225     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5226       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5227     } else {
5228       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5229       Offset += Size*CI->getSExtValue();
5230     }
5231   }
5232   
5233   // Okay, we know we have a single variable index, which must be a
5234   // pointer/array/vector index.  If there is no offset, life is simple, return
5235   // the index.
5236   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5237   if (Offset == 0) {
5238     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5239     // we don't need to bother extending: the extension won't affect where the
5240     // computation crosses zero.
5241     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5242       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5243                                   VariableIdx->getNameStart(), &I);
5244     return VariableIdx;
5245   }
5246   
5247   // Otherwise, there is an index.  The computation we will do will be modulo
5248   // the pointer size, so get it.
5249   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5250   
5251   Offset &= PtrSizeMask;
5252   VariableScale &= PtrSizeMask;
5253
5254   // To do this transformation, any constant index must be a multiple of the
5255   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5256   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5257   // multiple of the variable scale.
5258   int64_t NewOffs = Offset / (int64_t)VariableScale;
5259   if (Offset != NewOffs*(int64_t)VariableScale)
5260     return 0;
5261
5262   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5263   const Type *IntPtrTy = TD.getIntPtrType();
5264   if (VariableIdx->getType() != IntPtrTy)
5265     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5266                                               true /*SExt*/, 
5267                                               VariableIdx->getNameStart(), &I);
5268   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5269   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5270 }
5271
5272
5273 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5274 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5275 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5276                                        ICmpInst::Predicate Cond,
5277                                        Instruction &I) {
5278   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5279
5280   // Look through bitcasts.
5281   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5282     RHS = BCI->getOperand(0);
5283
5284   Value *PtrBase = GEPLHS->getOperand(0);
5285   if (PtrBase == RHS) {
5286     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5287     // This transformation (ignoring the base and scales) is valid because we
5288     // know pointers can't overflow.  See if we can output an optimized form.
5289     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5290     
5291     // If not, synthesize the offset the hard way.
5292     if (Offset == 0)
5293       Offset = EmitGEPOffset(GEPLHS, I, *this);
5294     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5295                         Constant::getNullValue(Offset->getType()));
5296   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5297     // If the base pointers are different, but the indices are the same, just
5298     // compare the base pointer.
5299     if (PtrBase != GEPRHS->getOperand(0)) {
5300       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5301       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5302                         GEPRHS->getOperand(0)->getType();
5303       if (IndicesTheSame)
5304         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5305           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5306             IndicesTheSame = false;
5307             break;
5308           }
5309
5310       // If all indices are the same, just compare the base pointers.
5311       if (IndicesTheSame)
5312         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5313                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5314
5315       // Otherwise, the base pointers are different and the indices are
5316       // different, bail out.
5317       return 0;
5318     }
5319
5320     // If one of the GEPs has all zero indices, recurse.
5321     bool AllZeros = true;
5322     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5323       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5324           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5325         AllZeros = false;
5326         break;
5327       }
5328     if (AllZeros)
5329       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5330                           ICmpInst::getSwappedPredicate(Cond), I);
5331
5332     // If the other GEP has all zero indices, recurse.
5333     AllZeros = true;
5334     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5335       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5336           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5337         AllZeros = false;
5338         break;
5339       }
5340     if (AllZeros)
5341       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5342
5343     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5344       // If the GEPs only differ by one index, compare it.
5345       unsigned NumDifferences = 0;  // Keep track of # differences.
5346       unsigned DiffOperand = 0;     // The operand that differs.
5347       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5348         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5349           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5350                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5351             // Irreconcilable differences.
5352             NumDifferences = 2;
5353             break;
5354           } else {
5355             if (NumDifferences++) break;
5356             DiffOperand = i;
5357           }
5358         }
5359
5360       if (NumDifferences == 0)   // SAME GEP?
5361         return ReplaceInstUsesWith(I, // No comparison is needed here.
5362                                    ConstantInt::get(Type::Int1Ty,
5363                                              ICmpInst::isTrueWhenEqual(Cond)));
5364
5365       else if (NumDifferences == 1) {
5366         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5367         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5368         // Make sure we do a signed comparison here.
5369         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5370       }
5371     }
5372
5373     // Only lower this if the icmp is the only user of the GEP or if we expect
5374     // the result to fold to a constant!
5375     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5376         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5377       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5378       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5379       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5380       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5381     }
5382   }
5383   return 0;
5384 }
5385
5386 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5387 ///
5388 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5389                                                 Instruction *LHSI,
5390                                                 Constant *RHSC) {
5391   if (!isa<ConstantFP>(RHSC)) return 0;
5392   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5393   
5394   // Get the width of the mantissa.  We don't want to hack on conversions that
5395   // might lose information from the integer, e.g. "i64 -> float"
5396   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5397   if (MantissaWidth == -1) return 0;  // Unknown.
5398   
5399   // Check to see that the input is converted from an integer type that is small
5400   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5401   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5402   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5403   
5404   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5405   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5406   if (LHSUnsigned)
5407     ++InputSize;
5408   
5409   // If the conversion would lose info, don't hack on this.
5410   if ((int)InputSize > MantissaWidth)
5411     return 0;
5412   
5413   // Otherwise, we can potentially simplify the comparison.  We know that it
5414   // will always come through as an integer value and we know the constant is
5415   // not a NAN (it would have been previously simplified).
5416   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5417   
5418   ICmpInst::Predicate Pred;
5419   switch (I.getPredicate()) {
5420   default: assert(0 && "Unexpected predicate!");
5421   case FCmpInst::FCMP_UEQ:
5422   case FCmpInst::FCMP_OEQ:
5423     Pred = ICmpInst::ICMP_EQ;
5424     break;
5425   case FCmpInst::FCMP_UGT:
5426   case FCmpInst::FCMP_OGT:
5427     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5428     break;
5429   case FCmpInst::FCMP_UGE:
5430   case FCmpInst::FCMP_OGE:
5431     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5432     break;
5433   case FCmpInst::FCMP_ULT:
5434   case FCmpInst::FCMP_OLT:
5435     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5436     break;
5437   case FCmpInst::FCMP_ULE:
5438   case FCmpInst::FCMP_OLE:
5439     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5440     break;
5441   case FCmpInst::FCMP_UNE:
5442   case FCmpInst::FCMP_ONE:
5443     Pred = ICmpInst::ICMP_NE;
5444     break;
5445   case FCmpInst::FCMP_ORD:
5446     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5447   case FCmpInst::FCMP_UNO:
5448     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5449   }
5450   
5451   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5452   
5453   // Now we know that the APFloat is a normal number, zero or inf.
5454   
5455   // See if the FP constant is too large for the integer.  For example,
5456   // comparing an i8 to 300.0.
5457   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5458   
5459   if (!LHSUnsigned) {
5460     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5461     // and large values.
5462     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5463     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5464                           APFloat::rmNearestTiesToEven);
5465     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5466       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5467           Pred == ICmpInst::ICMP_SLE)
5468         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5469       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5470     }
5471   } else {
5472     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5473     // +INF and large values.
5474     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5475     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5476                           APFloat::rmNearestTiesToEven);
5477     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5478       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5479           Pred == ICmpInst::ICMP_ULE)
5480         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5481       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5482     }
5483   }
5484   
5485   if (!LHSUnsigned) {
5486     // See if the RHS value is < SignedMin.
5487     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5488     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5489                           APFloat::rmNearestTiesToEven);
5490     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5491       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5492           Pred == ICmpInst::ICMP_SGE)
5493         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5494       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5495     }
5496   }
5497
5498   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5499   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5500   // casting the FP value to the integer value and back, checking for equality.
5501   // Don't do this for zero, because -0.0 is not fractional.
5502   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5503   if (!RHS.isZero() &&
5504       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5505     // If we had a comparison against a fractional value, we have to adjust the
5506     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5507     // at this point.
5508     switch (Pred) {
5509     default: assert(0 && "Unexpected integer comparison!");
5510     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5511       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5512     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5513       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5514     case ICmpInst::ICMP_ULE:
5515       // (float)int <= 4.4   --> int <= 4
5516       // (float)int <= -4.4  --> false
5517       if (RHS.isNegative())
5518         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5519       break;
5520     case ICmpInst::ICMP_SLE:
5521       // (float)int <= 4.4   --> int <= 4
5522       // (float)int <= -4.4  --> int < -4
5523       if (RHS.isNegative())
5524         Pred = ICmpInst::ICMP_SLT;
5525       break;
5526     case ICmpInst::ICMP_ULT:
5527       // (float)int < -4.4   --> false
5528       // (float)int < 4.4    --> int <= 4
5529       if (RHS.isNegative())
5530         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5531       Pred = ICmpInst::ICMP_ULE;
5532       break;
5533     case ICmpInst::ICMP_SLT:
5534       // (float)int < -4.4   --> int < -4
5535       // (float)int < 4.4    --> int <= 4
5536       if (!RHS.isNegative())
5537         Pred = ICmpInst::ICMP_SLE;
5538       break;
5539     case ICmpInst::ICMP_UGT:
5540       // (float)int > 4.4    --> int > 4
5541       // (float)int > -4.4   --> true
5542       if (RHS.isNegative())
5543         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5544       break;
5545     case ICmpInst::ICMP_SGT:
5546       // (float)int > 4.4    --> int > 4
5547       // (float)int > -4.4   --> int >= -4
5548       if (RHS.isNegative())
5549         Pred = ICmpInst::ICMP_SGE;
5550       break;
5551     case ICmpInst::ICMP_UGE:
5552       // (float)int >= -4.4   --> true
5553       // (float)int >= 4.4    --> int > 4
5554       if (!RHS.isNegative())
5555         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5556       Pred = ICmpInst::ICMP_UGT;
5557       break;
5558     case ICmpInst::ICMP_SGE:
5559       // (float)int >= -4.4   --> int >= -4
5560       // (float)int >= 4.4    --> int > 4
5561       if (!RHS.isNegative())
5562         Pred = ICmpInst::ICMP_SGT;
5563       break;
5564     }
5565   }
5566
5567   // Lower this FP comparison into an appropriate integer version of the
5568   // comparison.
5569   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5570 }
5571
5572 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5573   bool Changed = SimplifyCompare(I);
5574   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5575
5576   // Fold trivial predicates.
5577   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5578     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5579   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5580     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5581   
5582   // Simplify 'fcmp pred X, X'
5583   if (Op0 == Op1) {
5584     switch (I.getPredicate()) {
5585     default: assert(0 && "Unknown predicate!");
5586     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5587     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5588     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5589       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5590     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5591     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5592     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5593       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5594       
5595     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5596     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5597     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5598     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5599       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5600       I.setPredicate(FCmpInst::FCMP_UNO);
5601       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5602       return &I;
5603       
5604     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5605     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5606     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5607     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5608       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5609       I.setPredicate(FCmpInst::FCMP_ORD);
5610       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5611       return &I;
5612     }
5613   }
5614     
5615   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5616     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5617
5618   // Handle fcmp with constant RHS
5619   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5620     // If the constant is a nan, see if we can fold the comparison based on it.
5621     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5622       if (CFP->getValueAPF().isNaN()) {
5623         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5624           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5625         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5626                "Comparison must be either ordered or unordered!");
5627         // True if unordered.
5628         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5629       }
5630     }
5631     
5632     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5633       switch (LHSI->getOpcode()) {
5634       case Instruction::PHI:
5635         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5636         // block.  If in the same block, we're encouraging jump threading.  If
5637         // not, we are just pessimizing the code by making an i1 phi.
5638         if (LHSI->getParent() == I.getParent())
5639           if (Instruction *NV = FoldOpIntoPhi(I))
5640             return NV;
5641         break;
5642       case Instruction::SIToFP:
5643       case Instruction::UIToFP:
5644         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5645           return NV;
5646         break;
5647       case Instruction::Select:
5648         // If either operand of the select is a constant, we can fold the
5649         // comparison into the select arms, which will cause one to be
5650         // constant folded and the select turned into a bitwise or.
5651         Value *Op1 = 0, *Op2 = 0;
5652         if (LHSI->hasOneUse()) {
5653           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5654             // Fold the known value into the constant operand.
5655             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5656             // Insert a new FCmp of the other select operand.
5657             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5658                                                       LHSI->getOperand(2), RHSC,
5659                                                       I.getName()), I);
5660           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5661             // Fold the known value into the constant operand.
5662             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5663             // Insert a new FCmp of the other select operand.
5664             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5665                                                       LHSI->getOperand(1), RHSC,
5666                                                       I.getName()), I);
5667           }
5668         }
5669
5670         if (Op1)
5671           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5672         break;
5673       }
5674   }
5675
5676   return Changed ? &I : 0;
5677 }
5678
5679 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5680   bool Changed = SimplifyCompare(I);
5681   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5682   const Type *Ty = Op0->getType();
5683
5684   // icmp X, X
5685   if (Op0 == Op1)
5686     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5687                                                    I.isTrueWhenEqual()));
5688
5689   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5690     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5691   
5692   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5693   // addresses never equal each other!  We already know that Op0 != Op1.
5694   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5695        isa<ConstantPointerNull>(Op0)) &&
5696       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5697        isa<ConstantPointerNull>(Op1)))
5698     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5699                                                    !I.isTrueWhenEqual()));
5700
5701   // icmp's with boolean values can always be turned into bitwise operations
5702   if (Ty == Type::Int1Ty) {
5703     switch (I.getPredicate()) {
5704     default: assert(0 && "Invalid icmp instruction!");
5705     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5706       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5707       InsertNewInstBefore(Xor, I);
5708       return BinaryOperator::CreateNot(Xor);
5709     }
5710     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5711       return BinaryOperator::CreateXor(Op0, Op1);
5712
5713     case ICmpInst::ICMP_UGT:
5714       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5715       // FALL THROUGH
5716     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5717       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5718       InsertNewInstBefore(Not, I);
5719       return BinaryOperator::CreateAnd(Not, Op1);
5720     }
5721     case ICmpInst::ICMP_SGT:
5722       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5723       // FALL THROUGH
5724     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5725       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5726       InsertNewInstBefore(Not, I);
5727       return BinaryOperator::CreateAnd(Not, Op0);
5728     }
5729     case ICmpInst::ICMP_UGE:
5730       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5731       // FALL THROUGH
5732     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5733       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5734       InsertNewInstBefore(Not, I);
5735       return BinaryOperator::CreateOr(Not, Op1);
5736     }
5737     case ICmpInst::ICMP_SGE:
5738       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5739       // FALL THROUGH
5740     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5741       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5742       InsertNewInstBefore(Not, I);
5743       return BinaryOperator::CreateOr(Not, Op0);
5744     }
5745     }
5746   }
5747
5748   // See if we are doing a comparison with a constant.
5749   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5750     Value *A, *B;
5751     
5752     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5753     if (I.isEquality() && CI->isNullValue() &&
5754         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5755       // (icmp cond A B) if cond is equality
5756       return new ICmpInst(I.getPredicate(), A, B);
5757     }
5758     
5759     // If we have an icmp le or icmp ge instruction, turn it into the
5760     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5761     // them being folded in the code below.
5762     switch (I.getPredicate()) {
5763     default: break;
5764     case ICmpInst::ICMP_ULE:
5765       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5766         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5767       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5768     case ICmpInst::ICMP_SLE:
5769       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5770         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5771       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5772     case ICmpInst::ICMP_UGE:
5773       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5774         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5775       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5776     case ICmpInst::ICMP_SGE:
5777       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5778         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5779       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5780     }
5781     
5782     // See if we can fold the comparison based on range information we can get
5783     // by checking whether bits are known to be zero or one in the input.
5784     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5785     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5786     
5787     // If this comparison is a normal comparison, it demands all
5788     // bits, if it is a sign bit comparison, it only demands the sign bit.
5789     bool UnusedBit;
5790     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5791     
5792     if (SimplifyDemandedBits(Op0, 
5793                              isSignBit ? APInt::getSignBit(BitWidth)
5794                                        : APInt::getAllOnesValue(BitWidth),
5795                              KnownZero, KnownOne, 0))
5796       return &I;
5797         
5798     // Given the known and unknown bits, compute a range that the LHS could be
5799     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5800     // EQ and NE we use unsigned values.
5801     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5802     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5803       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5804     else
5805       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5806     
5807     // If Min and Max are known to be the same, then SimplifyDemandedBits
5808     // figured out that the LHS is a constant.  Just constant fold this now so
5809     // that code below can assume that Min != Max.
5810     if (Min == Max)
5811       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5812                                                           ConstantInt::get(Min),
5813                                                           CI));
5814     
5815     // Based on the range information we know about the LHS, see if we can
5816     // simplify this comparison.  For example, (x&4) < 8  is always true.
5817     const APInt &RHSVal = CI->getValue();
5818     switch (I.getPredicate()) {  // LE/GE have been folded already.
5819     default: assert(0 && "Unknown icmp opcode!");
5820     case ICmpInst::ICMP_EQ:
5821       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5822         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5823       break;
5824     case ICmpInst::ICMP_NE:
5825       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5826         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5827       break;
5828     case ICmpInst::ICMP_ULT:
5829       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5830         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5831       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5832         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5833       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5834         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5835       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5836         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5837         
5838       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5839       if (CI->isMinValue(true))
5840         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5841                             ConstantInt::getAllOnesValue(Op0->getType()));
5842       break;
5843     case ICmpInst::ICMP_UGT:
5844       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5845         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5847         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5848         
5849       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5850         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5851       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5852         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5853       
5854       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5855       if (CI->isMaxValue(true))
5856         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5857                             ConstantInt::getNullValue(Op0->getType()));
5858       break;
5859     case ICmpInst::ICMP_SLT:
5860       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5861         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5862       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5863         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5864       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5865         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5866       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5867         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5868       break;
5869     case ICmpInst::ICMP_SGT: 
5870       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5871         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5872       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5873         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5874         
5875       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5876         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5877       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5878         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5879       break;
5880     }
5881   }
5882
5883   // Test if the ICmpInst instruction is used exclusively by a select as
5884   // part of a minimum or maximum operation. If so, refrain from doing
5885   // any other folding. This helps out other analyses which understand
5886   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5887   // and CodeGen. And in this case, at least one of the comparison
5888   // operands has at least one user besides the compare (the select),
5889   // which would often largely negate the benefit of folding anyway.
5890   if (I.hasOneUse())
5891     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5892       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5893           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5894         return 0;
5895
5896   // See if we are doing a comparison between a constant and an instruction that
5897   // can be folded into the comparison.
5898   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5899     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5900     // instruction, see if that instruction also has constants so that the 
5901     // instruction can be folded into the icmp 
5902     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5903       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5904         return Res;
5905   }
5906
5907   // Handle icmp with constant (but not simple integer constant) RHS
5908   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5909     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5910       switch (LHSI->getOpcode()) {
5911       case Instruction::GetElementPtr:
5912         if (RHSC->isNullValue()) {
5913           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5914           bool isAllZeros = true;
5915           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5916             if (!isa<Constant>(LHSI->getOperand(i)) ||
5917                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5918               isAllZeros = false;
5919               break;
5920             }
5921           if (isAllZeros)
5922             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5923                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5924         }
5925         break;
5926
5927       case Instruction::PHI:
5928         // Only fold icmp into the PHI if the phi and fcmp are in the same
5929         // block.  If in the same block, we're encouraging jump threading.  If
5930         // not, we are just pessimizing the code by making an i1 phi.
5931         if (LHSI->getParent() == I.getParent())
5932           if (Instruction *NV = FoldOpIntoPhi(I))
5933             return NV;
5934         break;
5935       case Instruction::Select: {
5936         // If either operand of the select is a constant, we can fold the
5937         // comparison into the select arms, which will cause one to be
5938         // constant folded and the select turned into a bitwise or.
5939         Value *Op1 = 0, *Op2 = 0;
5940         if (LHSI->hasOneUse()) {
5941           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5942             // Fold the known value into the constant operand.
5943             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5944             // Insert a new ICmp of the other select operand.
5945             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5946                                                    LHSI->getOperand(2), RHSC,
5947                                                    I.getName()), I);
5948           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5949             // Fold the known value into the constant operand.
5950             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5951             // Insert a new ICmp of the other select operand.
5952             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5953                                                    LHSI->getOperand(1), RHSC,
5954                                                    I.getName()), I);
5955           }
5956         }
5957
5958         if (Op1)
5959           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5960         break;
5961       }
5962       case Instruction::Malloc:
5963         // If we have (malloc != null), and if the malloc has a single use, we
5964         // can assume it is successful and remove the malloc.
5965         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5966           AddToWorkList(LHSI);
5967           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5968                                                          !I.isTrueWhenEqual()));
5969         }
5970         break;
5971       }
5972   }
5973
5974   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5975   if (User *GEP = dyn_castGetElementPtr(Op0))
5976     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5977       return NI;
5978   if (User *GEP = dyn_castGetElementPtr(Op1))
5979     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5980                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5981       return NI;
5982
5983   // Test to see if the operands of the icmp are casted versions of other
5984   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5985   // now.
5986   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5987     if (isa<PointerType>(Op0->getType()) && 
5988         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5989       // We keep moving the cast from the left operand over to the right
5990       // operand, where it can often be eliminated completely.
5991       Op0 = CI->getOperand(0);
5992
5993       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5994       // so eliminate it as well.
5995       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5996         Op1 = CI2->getOperand(0);
5997
5998       // If Op1 is a constant, we can fold the cast into the constant.
5999       if (Op0->getType() != Op1->getType()) {
6000         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6001           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6002         } else {
6003           // Otherwise, cast the RHS right before the icmp
6004           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6005         }
6006       }
6007       return new ICmpInst(I.getPredicate(), Op0, Op1);
6008     }
6009   }
6010   
6011   if (isa<CastInst>(Op0)) {
6012     // Handle the special case of: icmp (cast bool to X), <cst>
6013     // This comes up when you have code like
6014     //   int X = A < B;
6015     //   if (X) ...
6016     // For generality, we handle any zero-extension of any operand comparison
6017     // with a constant or another cast from the same type.
6018     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6019       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6020         return R;
6021   }
6022   
6023   // See if it's the same type of instruction on the left and right.
6024   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6025     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6026       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6027           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6028           I.isEquality()) {
6029         switch (Op0I->getOpcode()) {
6030         default: break;
6031         case Instruction::Add:
6032         case Instruction::Sub:
6033         case Instruction::Xor:
6034           // a+x icmp eq/ne b+x --> a icmp b
6035           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6036                               Op1I->getOperand(0));
6037           break;
6038         case Instruction::Mul:
6039           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6040             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6041             // Mask = -1 >> count-trailing-zeros(Cst).
6042             if (!CI->isZero() && !CI->isOne()) {
6043               const APInt &AP = CI->getValue();
6044               ConstantInt *Mask = ConstantInt::get(
6045                                       APInt::getLowBitsSet(AP.getBitWidth(),
6046                                                            AP.getBitWidth() -
6047                                                       AP.countTrailingZeros()));
6048               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6049                                                             Mask);
6050               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6051                                                             Mask);
6052               InsertNewInstBefore(And1, I);
6053               InsertNewInstBefore(And2, I);
6054               return new ICmpInst(I.getPredicate(), And1, And2);
6055             }
6056           }
6057           break;
6058         }
6059       }
6060     }
6061   }
6062   
6063   // ~x < ~y --> y < x
6064   { Value *A, *B;
6065     if (match(Op0, m_Not(m_Value(A))) &&
6066         match(Op1, m_Not(m_Value(B))))
6067       return new ICmpInst(I.getPredicate(), B, A);
6068   }
6069   
6070   if (I.isEquality()) {
6071     Value *A, *B, *C, *D;
6072     
6073     // -x == -y --> x == y
6074     if (match(Op0, m_Neg(m_Value(A))) &&
6075         match(Op1, m_Neg(m_Value(B))))
6076       return new ICmpInst(I.getPredicate(), A, B);
6077     
6078     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6079       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6080         Value *OtherVal = A == Op1 ? B : A;
6081         return new ICmpInst(I.getPredicate(), OtherVal,
6082                             Constant::getNullValue(A->getType()));
6083       }
6084
6085       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6086         // A^c1 == C^c2 --> A == C^(c1^c2)
6087         ConstantInt *C1, *C2;
6088         if (match(B, m_ConstantInt(C1)) &&
6089             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6090           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6091           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6092           return new ICmpInst(I.getPredicate(), A,
6093                               InsertNewInstBefore(Xor, I));
6094         }
6095         
6096         // A^B == A^D -> B == D
6097         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6098         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6099         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6100         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6101       }
6102     }
6103     
6104     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6105         (A == Op0 || B == Op0)) {
6106       // A == (A^B)  ->  B == 0
6107       Value *OtherVal = A == Op0 ? B : A;
6108       return new ICmpInst(I.getPredicate(), OtherVal,
6109                           Constant::getNullValue(A->getType()));
6110     }
6111
6112     // (A-B) == A  ->  B == 0
6113     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6114       return new ICmpInst(I.getPredicate(), B, 
6115                           Constant::getNullValue(B->getType()));
6116
6117     // A == (A-B)  ->  B == 0
6118     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6119       return new ICmpInst(I.getPredicate(), B,
6120                           Constant::getNullValue(B->getType()));
6121     
6122     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6123     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6124         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6125         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6126       Value *X = 0, *Y = 0, *Z = 0;
6127       
6128       if (A == C) {
6129         X = B; Y = D; Z = A;
6130       } else if (A == D) {
6131         X = B; Y = C; Z = A;
6132       } else if (B == C) {
6133         X = A; Y = D; Z = B;
6134       } else if (B == D) {
6135         X = A; Y = C; Z = B;
6136       }
6137       
6138       if (X) {   // Build (X^Y) & Z
6139         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6140         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6141         I.setOperand(0, Op1);
6142         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6143         return &I;
6144       }
6145     }
6146   }
6147   return Changed ? &I : 0;
6148 }
6149
6150
6151 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6152 /// and CmpRHS are both known to be integer constants.
6153 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6154                                           ConstantInt *DivRHS) {
6155   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6156   const APInt &CmpRHSV = CmpRHS->getValue();
6157   
6158   // FIXME: If the operand types don't match the type of the divide 
6159   // then don't attempt this transform. The code below doesn't have the
6160   // logic to deal with a signed divide and an unsigned compare (and
6161   // vice versa). This is because (x /s C1) <s C2  produces different 
6162   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6163   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6164   // work. :(  The if statement below tests that condition and bails 
6165   // if it finds it. 
6166   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6167   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6168     return 0;
6169   if (DivRHS->isZero())
6170     return 0; // The ProdOV computation fails on divide by zero.
6171   if (DivIsSigned && DivRHS->isAllOnesValue())
6172     return 0; // The overflow computation also screws up here
6173   if (DivRHS->isOne())
6174     return 0; // Not worth bothering, and eliminates some funny cases
6175               // with INT_MIN.
6176
6177   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6178   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6179   // C2 (CI). By solving for X we can turn this into a range check 
6180   // instead of computing a divide. 
6181   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6182
6183   // Determine if the product overflows by seeing if the product is
6184   // not equal to the divide. Make sure we do the same kind of divide
6185   // as in the LHS instruction that we're folding. 
6186   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6187                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6188
6189   // Get the ICmp opcode
6190   ICmpInst::Predicate Pred = ICI.getPredicate();
6191
6192   // Figure out the interval that is being checked.  For example, a comparison
6193   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6194   // Compute this interval based on the constants involved and the signedness of
6195   // the compare/divide.  This computes a half-open interval, keeping track of
6196   // whether either value in the interval overflows.  After analysis each
6197   // overflow variable is set to 0 if it's corresponding bound variable is valid
6198   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6199   int LoOverflow = 0, HiOverflow = 0;
6200   ConstantInt *LoBound = 0, *HiBound = 0;
6201   
6202   if (!DivIsSigned) {  // udiv
6203     // e.g. X/5 op 3  --> [15, 20)
6204     LoBound = Prod;
6205     HiOverflow = LoOverflow = ProdOV;
6206     if (!HiOverflow)
6207       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6208   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6209     if (CmpRHSV == 0) {       // (X / pos) op 0
6210       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6211       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6212       HiBound = DivRHS;
6213     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6214       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6215       HiOverflow = LoOverflow = ProdOV;
6216       if (!HiOverflow)
6217         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6218     } else {                       // (X / pos) op neg
6219       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6220       HiBound = AddOne(Prod);
6221       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6222       if (!LoOverflow) {
6223         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6224         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6225                                      true) ? -1 : 0;
6226        }
6227     }
6228   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6229     if (CmpRHSV == 0) {       // (X / neg) op 0
6230       // e.g. X/-5 op 0  --> [-4, 5)
6231       LoBound = AddOne(DivRHS);
6232       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6233       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6234         HiOverflow = 1;            // [INTMIN+1, overflow)
6235         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6236       }
6237     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6238       // e.g. X/-5 op 3  --> [-19, -14)
6239       HiBound = AddOne(Prod);
6240       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6241       if (!LoOverflow)
6242         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6243     } else {                       // (X / neg) op neg
6244       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6245       LoOverflow = HiOverflow = ProdOV;
6246       if (!HiOverflow)
6247         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6248     }
6249     
6250     // Dividing by a negative swaps the condition.  LT <-> GT
6251     Pred = ICmpInst::getSwappedPredicate(Pred);
6252   }
6253
6254   Value *X = DivI->getOperand(0);
6255   switch (Pred) {
6256   default: assert(0 && "Unhandled icmp opcode!");
6257   case ICmpInst::ICMP_EQ:
6258     if (LoOverflow && HiOverflow)
6259       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6260     else if (HiOverflow)
6261       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6262                           ICmpInst::ICMP_UGE, X, LoBound);
6263     else if (LoOverflow)
6264       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6265                           ICmpInst::ICMP_ULT, X, HiBound);
6266     else
6267       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6268   case ICmpInst::ICMP_NE:
6269     if (LoOverflow && HiOverflow)
6270       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6271     else if (HiOverflow)
6272       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6273                           ICmpInst::ICMP_ULT, X, LoBound);
6274     else if (LoOverflow)
6275       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6276                           ICmpInst::ICMP_UGE, X, HiBound);
6277     else
6278       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6279   case ICmpInst::ICMP_ULT:
6280   case ICmpInst::ICMP_SLT:
6281     if (LoOverflow == +1)   // Low bound is greater than input range.
6282       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6283     if (LoOverflow == -1)   // Low bound is less than input range.
6284       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6285     return new ICmpInst(Pred, X, LoBound);
6286   case ICmpInst::ICMP_UGT:
6287   case ICmpInst::ICMP_SGT:
6288     if (HiOverflow == +1)       // High bound greater than input range.
6289       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6290     else if (HiOverflow == -1)  // High bound less than input range.
6291       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6292     if (Pred == ICmpInst::ICMP_UGT)
6293       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6294     else
6295       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6296   }
6297 }
6298
6299
6300 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6301 ///
6302 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6303                                                           Instruction *LHSI,
6304                                                           ConstantInt *RHS) {
6305   const APInt &RHSV = RHS->getValue();
6306   
6307   switch (LHSI->getOpcode()) {
6308   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6309     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6310       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6311       // fold the xor.
6312       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6313           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6314         Value *CompareVal = LHSI->getOperand(0);
6315         
6316         // If the sign bit of the XorCST is not set, there is no change to
6317         // the operation, just stop using the Xor.
6318         if (!XorCST->getValue().isNegative()) {
6319           ICI.setOperand(0, CompareVal);
6320           AddToWorkList(LHSI);
6321           return &ICI;
6322         }
6323         
6324         // Was the old condition true if the operand is positive?
6325         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6326         
6327         // If so, the new one isn't.
6328         isTrueIfPositive ^= true;
6329         
6330         if (isTrueIfPositive)
6331           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6332         else
6333           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6334       }
6335     }
6336     break;
6337   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6338     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6339         LHSI->getOperand(0)->hasOneUse()) {
6340       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6341       
6342       // If the LHS is an AND of a truncating cast, we can widen the
6343       // and/compare to be the input width without changing the value
6344       // produced, eliminating a cast.
6345       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6346         // We can do this transformation if either the AND constant does not
6347         // have its sign bit set or if it is an equality comparison. 
6348         // Extending a relational comparison when we're checking the sign
6349         // bit would not work.
6350         if (Cast->hasOneUse() &&
6351             (ICI.isEquality() ||
6352              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6353           uint32_t BitWidth = 
6354             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6355           APInt NewCST = AndCST->getValue();
6356           NewCST.zext(BitWidth);
6357           APInt NewCI = RHSV;
6358           NewCI.zext(BitWidth);
6359           Instruction *NewAnd = 
6360             BinaryOperator::CreateAnd(Cast->getOperand(0),
6361                                       ConstantInt::get(NewCST),LHSI->getName());
6362           InsertNewInstBefore(NewAnd, ICI);
6363           return new ICmpInst(ICI.getPredicate(), NewAnd,
6364                               ConstantInt::get(NewCI));
6365         }
6366       }
6367       
6368       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6369       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6370       // happens a LOT in code produced by the C front-end, for bitfield
6371       // access.
6372       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6373       if (Shift && !Shift->isShift())
6374         Shift = 0;
6375       
6376       ConstantInt *ShAmt;
6377       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6378       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6379       const Type *AndTy = AndCST->getType();          // Type of the and.
6380       
6381       // We can fold this as long as we can't shift unknown bits
6382       // into the mask.  This can only happen with signed shift
6383       // rights, as they sign-extend.
6384       if (ShAmt) {
6385         bool CanFold = Shift->isLogicalShift();
6386         if (!CanFold) {
6387           // To test for the bad case of the signed shr, see if any
6388           // of the bits shifted in could be tested after the mask.
6389           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6390           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6391           
6392           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6393           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6394                AndCST->getValue()) == 0)
6395             CanFold = true;
6396         }
6397         
6398         if (CanFold) {
6399           Constant *NewCst;
6400           if (Shift->getOpcode() == Instruction::Shl)
6401             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6402           else
6403             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6404           
6405           // Check to see if we are shifting out any of the bits being
6406           // compared.
6407           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6408             // If we shifted bits out, the fold is not going to work out.
6409             // As a special case, check to see if this means that the
6410             // result is always true or false now.
6411             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6412               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6413             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6414               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6415           } else {
6416             ICI.setOperand(1, NewCst);
6417             Constant *NewAndCST;
6418             if (Shift->getOpcode() == Instruction::Shl)
6419               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6420             else
6421               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6422             LHSI->setOperand(1, NewAndCST);
6423             LHSI->setOperand(0, Shift->getOperand(0));
6424             AddToWorkList(Shift); // Shift is dead.
6425             AddUsesToWorkList(ICI);
6426             return &ICI;
6427           }
6428         }
6429       }
6430       
6431       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6432       // preferable because it allows the C<<Y expression to be hoisted out
6433       // of a loop if Y is invariant and X is not.
6434       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6435           ICI.isEquality() && !Shift->isArithmeticShift() &&
6436           isa<Instruction>(Shift->getOperand(0))) {
6437         // Compute C << Y.
6438         Value *NS;
6439         if (Shift->getOpcode() == Instruction::LShr) {
6440           NS = BinaryOperator::CreateShl(AndCST, 
6441                                          Shift->getOperand(1), "tmp");
6442         } else {
6443           // Insert a logical shift.
6444           NS = BinaryOperator::CreateLShr(AndCST,
6445                                           Shift->getOperand(1), "tmp");
6446         }
6447         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6448         
6449         // Compute X & (C << Y).
6450         Instruction *NewAnd = 
6451           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6452         InsertNewInstBefore(NewAnd, ICI);
6453         
6454         ICI.setOperand(0, NewAnd);
6455         return &ICI;
6456       }
6457     }
6458     break;
6459     
6460   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6461     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6462     if (!ShAmt) break;
6463     
6464     uint32_t TypeBits = RHSV.getBitWidth();
6465     
6466     // Check that the shift amount is in range.  If not, don't perform
6467     // undefined shifts.  When the shift is visited it will be
6468     // simplified.
6469     if (ShAmt->uge(TypeBits))
6470       break;
6471     
6472     if (ICI.isEquality()) {
6473       // If we are comparing against bits always shifted out, the
6474       // comparison cannot succeed.
6475       Constant *Comp =
6476         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6477       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6478         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6479         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6480         return ReplaceInstUsesWith(ICI, Cst);
6481       }
6482       
6483       if (LHSI->hasOneUse()) {
6484         // Otherwise strength reduce the shift into an and.
6485         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6486         Constant *Mask =
6487           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6488         
6489         Instruction *AndI =
6490           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6491                                     Mask, LHSI->getName()+".mask");
6492         Value *And = InsertNewInstBefore(AndI, ICI);
6493         return new ICmpInst(ICI.getPredicate(), And,
6494                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6495       }
6496     }
6497     
6498     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6499     bool TrueIfSigned = false;
6500     if (LHSI->hasOneUse() &&
6501         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6502       // (X << 31) <s 0  --> (X&1) != 0
6503       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6504                                            (TypeBits-ShAmt->getZExtValue()-1));
6505       Instruction *AndI =
6506         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6507                                   Mask, LHSI->getName()+".mask");
6508       Value *And = InsertNewInstBefore(AndI, ICI);
6509       
6510       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6511                           And, Constant::getNullValue(And->getType()));
6512     }
6513     break;
6514   }
6515     
6516   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6517   case Instruction::AShr: {
6518     // Only handle equality comparisons of shift-by-constant.
6519     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6520     if (!ShAmt || !ICI.isEquality()) break;
6521
6522     // Check that the shift amount is in range.  If not, don't perform
6523     // undefined shifts.  When the shift is visited it will be
6524     // simplified.
6525     uint32_t TypeBits = RHSV.getBitWidth();
6526     if (ShAmt->uge(TypeBits))
6527       break;
6528     
6529     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6530       
6531     // If we are comparing against bits always shifted out, the
6532     // comparison cannot succeed.
6533     APInt Comp = RHSV << ShAmtVal;
6534     if (LHSI->getOpcode() == Instruction::LShr)
6535       Comp = Comp.lshr(ShAmtVal);
6536     else
6537       Comp = Comp.ashr(ShAmtVal);
6538     
6539     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6540       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6541       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6542       return ReplaceInstUsesWith(ICI, Cst);
6543     }
6544     
6545     // Otherwise, check to see if the bits shifted out are known to be zero.
6546     // If so, we can compare against the unshifted value:
6547     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6548     if (LHSI->hasOneUse() &&
6549         MaskedValueIsZero(LHSI->getOperand(0), 
6550                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6551       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6552                           ConstantExpr::getShl(RHS, ShAmt));
6553     }
6554       
6555     if (LHSI->hasOneUse()) {
6556       // Otherwise strength reduce the shift into an and.
6557       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6558       Constant *Mask = ConstantInt::get(Val);
6559       
6560       Instruction *AndI =
6561         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6562                                   Mask, LHSI->getName()+".mask");
6563       Value *And = InsertNewInstBefore(AndI, ICI);
6564       return new ICmpInst(ICI.getPredicate(), And,
6565                           ConstantExpr::getShl(RHS, ShAmt));
6566     }
6567     break;
6568   }
6569     
6570   case Instruction::SDiv:
6571   case Instruction::UDiv:
6572     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6573     // Fold this div into the comparison, producing a range check. 
6574     // Determine, based on the divide type, what the range is being 
6575     // checked.  If there is an overflow on the low or high side, remember 
6576     // it, otherwise compute the range [low, hi) bounding the new value.
6577     // See: InsertRangeTest above for the kinds of replacements possible.
6578     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6579       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6580                                           DivRHS))
6581         return R;
6582     break;
6583
6584   case Instruction::Add:
6585     // Fold: icmp pred (add, X, C1), C2
6586
6587     if (!ICI.isEquality()) {
6588       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6589       if (!LHSC) break;
6590       const APInt &LHSV = LHSC->getValue();
6591
6592       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6593                             .subtract(LHSV);
6594
6595       if (ICI.isSignedPredicate()) {
6596         if (CR.getLower().isSignBit()) {
6597           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6598                               ConstantInt::get(CR.getUpper()));
6599         } else if (CR.getUpper().isSignBit()) {
6600           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6601                               ConstantInt::get(CR.getLower()));
6602         }
6603       } else {
6604         if (CR.getLower().isMinValue()) {
6605           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6606                               ConstantInt::get(CR.getUpper()));
6607         } else if (CR.getUpper().isMinValue()) {
6608           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6609                               ConstantInt::get(CR.getLower()));
6610         }
6611       }
6612     }
6613     break;
6614   }
6615   
6616   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6617   if (ICI.isEquality()) {
6618     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6619     
6620     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6621     // the second operand is a constant, simplify a bit.
6622     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6623       switch (BO->getOpcode()) {
6624       case Instruction::SRem:
6625         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6626         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6627           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6628           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6629             Instruction *NewRem =
6630               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6631                                          BO->getName());
6632             InsertNewInstBefore(NewRem, ICI);
6633             return new ICmpInst(ICI.getPredicate(), NewRem, 
6634                                 Constant::getNullValue(BO->getType()));
6635           }
6636         }
6637         break;
6638       case Instruction::Add:
6639         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6640         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6641           if (BO->hasOneUse())
6642             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6643                                 Subtract(RHS, BOp1C));
6644         } else if (RHSV == 0) {
6645           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6646           // efficiently invertible, or if the add has just this one use.
6647           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6648           
6649           if (Value *NegVal = dyn_castNegVal(BOp1))
6650             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6651           else if (Value *NegVal = dyn_castNegVal(BOp0))
6652             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6653           else if (BO->hasOneUse()) {
6654             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6655             InsertNewInstBefore(Neg, ICI);
6656             Neg->takeName(BO);
6657             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6658           }
6659         }
6660         break;
6661       case Instruction::Xor:
6662         // For the xor case, we can xor two constants together, eliminating
6663         // the explicit xor.
6664         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6665           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6666                               ConstantExpr::getXor(RHS, BOC));
6667         
6668         // FALLTHROUGH
6669       case Instruction::Sub:
6670         // Replace (([sub|xor] A, B) != 0) with (A != B)
6671         if (RHSV == 0)
6672           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6673                               BO->getOperand(1));
6674         break;
6675         
6676       case Instruction::Or:
6677         // If bits are being or'd in that are not present in the constant we
6678         // are comparing against, then the comparison could never succeed!
6679         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6680           Constant *NotCI = ConstantExpr::getNot(RHS);
6681           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6682             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6683                                                              isICMP_NE));
6684         }
6685         break;
6686         
6687       case Instruction::And:
6688         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6689           // If bits are being compared against that are and'd out, then the
6690           // comparison can never succeed!
6691           if ((RHSV & ~BOC->getValue()) != 0)
6692             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6693                                                              isICMP_NE));
6694           
6695           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6696           if (RHS == BOC && RHSV.isPowerOf2())
6697             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6698                                 ICmpInst::ICMP_NE, LHSI,
6699                                 Constant::getNullValue(RHS->getType()));
6700           
6701           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6702           if (BOC->getValue().isSignBit()) {
6703             Value *X = BO->getOperand(0);
6704             Constant *Zero = Constant::getNullValue(X->getType());
6705             ICmpInst::Predicate pred = isICMP_NE ? 
6706               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6707             return new ICmpInst(pred, X, Zero);
6708           }
6709           
6710           // ((X & ~7) == 0) --> X < 8
6711           if (RHSV == 0 && isHighOnes(BOC)) {
6712             Value *X = BO->getOperand(0);
6713             Constant *NegX = ConstantExpr::getNeg(BOC);
6714             ICmpInst::Predicate pred = isICMP_NE ? 
6715               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6716             return new ICmpInst(pred, X, NegX);
6717           }
6718         }
6719       default: break;
6720       }
6721     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6722       // Handle icmp {eq|ne} <intrinsic>, intcst.
6723       if (II->getIntrinsicID() == Intrinsic::bswap) {
6724         AddToWorkList(II);
6725         ICI.setOperand(0, II->getOperand(1));
6726         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6727         return &ICI;
6728       }
6729     }
6730   } else {  // Not a ICMP_EQ/ICMP_NE
6731             // If the LHS is a cast from an integral value of the same size, 
6732             // then since we know the RHS is a constant, try to simlify.
6733     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6734       Value *CastOp = Cast->getOperand(0);
6735       const Type *SrcTy = CastOp->getType();
6736       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6737       if (SrcTy->isInteger() && 
6738           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6739         // If this is an unsigned comparison, try to make the comparison use
6740         // smaller constant values.
6741         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6742           // X u< 128 => X s> -1
6743           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6744                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6745         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6746                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6747           // X u> 127 => X s< 0
6748           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6749                               Constant::getNullValue(SrcTy));
6750         }
6751       }
6752     }
6753   }
6754   return 0;
6755 }
6756
6757 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6758 /// We only handle extending casts so far.
6759 ///
6760 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6761   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6762   Value *LHSCIOp        = LHSCI->getOperand(0);
6763   const Type *SrcTy     = LHSCIOp->getType();
6764   const Type *DestTy    = LHSCI->getType();
6765   Value *RHSCIOp;
6766
6767   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6768   // integer type is the same size as the pointer type.
6769   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6770       getTargetData().getPointerSizeInBits() == 
6771          cast<IntegerType>(DestTy)->getBitWidth()) {
6772     Value *RHSOp = 0;
6773     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6774       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6775     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6776       RHSOp = RHSC->getOperand(0);
6777       // If the pointer types don't match, insert a bitcast.
6778       if (LHSCIOp->getType() != RHSOp->getType())
6779         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6780     }
6781
6782     if (RHSOp)
6783       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6784   }
6785   
6786   // The code below only handles extension cast instructions, so far.
6787   // Enforce this.
6788   if (LHSCI->getOpcode() != Instruction::ZExt &&
6789       LHSCI->getOpcode() != Instruction::SExt)
6790     return 0;
6791
6792   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6793   bool isSignedCmp = ICI.isSignedPredicate();
6794
6795   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6796     // Not an extension from the same type?
6797     RHSCIOp = CI->getOperand(0);
6798     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6799       return 0;
6800     
6801     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6802     // and the other is a zext), then we can't handle this.
6803     if (CI->getOpcode() != LHSCI->getOpcode())
6804       return 0;
6805
6806     // Deal with equality cases early.
6807     if (ICI.isEquality())
6808       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6809
6810     // A signed comparison of sign extended values simplifies into a
6811     // signed comparison.
6812     if (isSignedCmp && isSignedExt)
6813       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6814
6815     // The other three cases all fold into an unsigned comparison.
6816     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6817   }
6818
6819   // If we aren't dealing with a constant on the RHS, exit early
6820   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6821   if (!CI)
6822     return 0;
6823
6824   // Compute the constant that would happen if we truncated to SrcTy then
6825   // reextended to DestTy.
6826   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6827   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6828
6829   // If the re-extended constant didn't change...
6830   if (Res2 == CI) {
6831     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6832     // For example, we might have:
6833     //    %A = sext short %X to uint
6834     //    %B = icmp ugt uint %A, 1330
6835     // It is incorrect to transform this into 
6836     //    %B = icmp ugt short %X, 1330 
6837     // because %A may have negative value. 
6838     //
6839     // However, we allow this when the compare is EQ/NE, because they are
6840     // signless.
6841     if (isSignedExt == isSignedCmp || ICI.isEquality())
6842       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6843     return 0;
6844   }
6845
6846   // The re-extended constant changed so the constant cannot be represented 
6847   // in the shorter type. Consequently, we cannot emit a simple comparison.
6848
6849   // First, handle some easy cases. We know the result cannot be equal at this
6850   // point so handle the ICI.isEquality() cases
6851   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6852     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6853   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6854     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6855
6856   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6857   // should have been folded away previously and not enter in here.
6858   Value *Result;
6859   if (isSignedCmp) {
6860     // We're performing a signed comparison.
6861     if (cast<ConstantInt>(CI)->getValue().isNegative())
6862       Result = ConstantInt::getFalse();          // X < (small) --> false
6863     else
6864       Result = ConstantInt::getTrue();           // X < (large) --> true
6865   } else {
6866     // We're performing an unsigned comparison.
6867     if (isSignedExt) {
6868       // We're performing an unsigned comp with a sign extended value.
6869       // This is true if the input is >= 0. [aka >s -1]
6870       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6871       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6872                                    NegOne, ICI.getName()), ICI);
6873     } else {
6874       // Unsigned extend & unsigned compare -> always true.
6875       Result = ConstantInt::getTrue();
6876     }
6877   }
6878
6879   // Finally, return the value computed.
6880   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6881       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6882     return ReplaceInstUsesWith(ICI, Result);
6883
6884   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6885           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6886          "ICmp should be folded!");
6887   if (Constant *CI = dyn_cast<Constant>(Result))
6888     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6889   return BinaryOperator::CreateNot(Result);
6890 }
6891
6892 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6893   return commonShiftTransforms(I);
6894 }
6895
6896 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6897   return commonShiftTransforms(I);
6898 }
6899
6900 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6901   if (Instruction *R = commonShiftTransforms(I))
6902     return R;
6903   
6904   Value *Op0 = I.getOperand(0);
6905   
6906   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6907   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6908     if (CSI->isAllOnesValue())
6909       return ReplaceInstUsesWith(I, CSI);
6910   
6911   // See if we can turn a signed shr into an unsigned shr.
6912   if (!isa<VectorType>(I.getType()) &&
6913       MaskedValueIsZero(Op0,
6914                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6915     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6916   
6917   return 0;
6918 }
6919
6920 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6921   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6922   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6923
6924   // shl X, 0 == X and shr X, 0 == X
6925   // shl 0, X == 0 and shr 0, X == 0
6926   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6927       Op0 == Constant::getNullValue(Op0->getType()))
6928     return ReplaceInstUsesWith(I, Op0);
6929   
6930   if (isa<UndefValue>(Op0)) {            
6931     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6932       return ReplaceInstUsesWith(I, Op0);
6933     else                                    // undef << X -> 0, undef >>u X -> 0
6934       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6935   }
6936   if (isa<UndefValue>(Op1)) {
6937     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6938       return ReplaceInstUsesWith(I, Op0);          
6939     else                                     // X << undef, X >>u undef -> 0
6940       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6941   }
6942
6943   // Try to fold constant and into select arguments.
6944   if (isa<Constant>(Op0))
6945     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6946       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6947         return R;
6948
6949   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6950     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6951       return Res;
6952   return 0;
6953 }
6954
6955 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6956                                                BinaryOperator &I) {
6957   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6958
6959   // See if we can simplify any instructions used by the instruction whose sole 
6960   // purpose is to compute bits we don't care about.
6961   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6962   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6963   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6964                            KnownZero, KnownOne))
6965     return &I;
6966   
6967   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6968   // of a signed value.
6969   //
6970   if (Op1->uge(TypeBits)) {
6971     if (I.getOpcode() != Instruction::AShr)
6972       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6973     else {
6974       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6975       return &I;
6976     }
6977   }
6978   
6979   // ((X*C1) << C2) == (X * (C1 << C2))
6980   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6981     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6982       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6983         return BinaryOperator::CreateMul(BO->getOperand(0),
6984                                          ConstantExpr::getShl(BOOp, Op1));
6985   
6986   // Try to fold constant and into select arguments.
6987   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6988     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6989       return R;
6990   if (isa<PHINode>(Op0))
6991     if (Instruction *NV = FoldOpIntoPhi(I))
6992       return NV;
6993   
6994   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6995   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6996     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6997     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6998     // place.  Don't try to do this transformation in this case.  Also, we
6999     // require that the input operand is a shift-by-constant so that we have
7000     // confidence that the shifts will get folded together.  We could do this
7001     // xform in more cases, but it is unlikely to be profitable.
7002     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7003         isa<ConstantInt>(TrOp->getOperand(1))) {
7004       // Okay, we'll do this xform.  Make the shift of shift.
7005       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7006       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7007                                                 I.getName());
7008       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7009
7010       // For logical shifts, the truncation has the effect of making the high
7011       // part of the register be zeros.  Emulate this by inserting an AND to
7012       // clear the top bits as needed.  This 'and' will usually be zapped by
7013       // other xforms later if dead.
7014       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7015       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7016       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7017       
7018       // The mask we constructed says what the trunc would do if occurring
7019       // between the shifts.  We want to know the effect *after* the second
7020       // shift.  We know that it is a logical shift by a constant, so adjust the
7021       // mask as appropriate.
7022       if (I.getOpcode() == Instruction::Shl)
7023         MaskV <<= Op1->getZExtValue();
7024       else {
7025         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7026         MaskV = MaskV.lshr(Op1->getZExtValue());
7027       }
7028
7029       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7030                                                    TI->getName());
7031       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7032
7033       // Return the value truncated to the interesting size.
7034       return new TruncInst(And, I.getType());
7035     }
7036   }
7037   
7038   if (Op0->hasOneUse()) {
7039     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7040       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7041       Value *V1, *V2;
7042       ConstantInt *CC;
7043       switch (Op0BO->getOpcode()) {
7044         default: break;
7045         case Instruction::Add:
7046         case Instruction::And:
7047         case Instruction::Or:
7048         case Instruction::Xor: {
7049           // These operators commute.
7050           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7051           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7052               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7053             Instruction *YS = BinaryOperator::CreateShl(
7054                                             Op0BO->getOperand(0), Op1,
7055                                             Op0BO->getName());
7056             InsertNewInstBefore(YS, I); // (Y << C)
7057             Instruction *X = 
7058               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7059                                      Op0BO->getOperand(1)->getName());
7060             InsertNewInstBefore(X, I);  // (X + (Y << C))
7061             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7062             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7063                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7064           }
7065           
7066           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7067           Value *Op0BOOp1 = Op0BO->getOperand(1);
7068           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7069               match(Op0BOOp1, 
7070                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7071                           m_ConstantInt(CC))) &&
7072               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7073             Instruction *YS = BinaryOperator::CreateShl(
7074                                                      Op0BO->getOperand(0), Op1,
7075                                                      Op0BO->getName());
7076             InsertNewInstBefore(YS, I); // (Y << C)
7077             Instruction *XM =
7078               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7079                                         V1->getName()+".mask");
7080             InsertNewInstBefore(XM, I); // X & (CC << C)
7081             
7082             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7083           }
7084         }
7085           
7086         // FALL THROUGH.
7087         case Instruction::Sub: {
7088           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7089           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7090               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7091             Instruction *YS = BinaryOperator::CreateShl(
7092                                                      Op0BO->getOperand(1), Op1,
7093                                                      Op0BO->getName());
7094             InsertNewInstBefore(YS, I); // (Y << C)
7095             Instruction *X =
7096               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7097                                      Op0BO->getOperand(0)->getName());
7098             InsertNewInstBefore(X, I);  // (X + (Y << C))
7099             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7100             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7101                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7102           }
7103           
7104           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7105           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7106               match(Op0BO->getOperand(0),
7107                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7108                           m_ConstantInt(CC))) && V2 == Op1 &&
7109               cast<BinaryOperator>(Op0BO->getOperand(0))
7110                   ->getOperand(0)->hasOneUse()) {
7111             Instruction *YS = BinaryOperator::CreateShl(
7112                                                      Op0BO->getOperand(1), Op1,
7113                                                      Op0BO->getName());
7114             InsertNewInstBefore(YS, I); // (Y << C)
7115             Instruction *XM =
7116               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7117                                         V1->getName()+".mask");
7118             InsertNewInstBefore(XM, I); // X & (CC << C)
7119             
7120             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7121           }
7122           
7123           break;
7124         }
7125       }
7126       
7127       
7128       // If the operand is an bitwise operator with a constant RHS, and the
7129       // shift is the only use, we can pull it out of the shift.
7130       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7131         bool isValid = true;     // Valid only for And, Or, Xor
7132         bool highBitSet = false; // Transform if high bit of constant set?
7133         
7134         switch (Op0BO->getOpcode()) {
7135           default: isValid = false; break;   // Do not perform transform!
7136           case Instruction::Add:
7137             isValid = isLeftShift;
7138             break;
7139           case Instruction::Or:
7140           case Instruction::Xor:
7141             highBitSet = false;
7142             break;
7143           case Instruction::And:
7144             highBitSet = true;
7145             break;
7146         }
7147         
7148         // If this is a signed shift right, and the high bit is modified
7149         // by the logical operation, do not perform the transformation.
7150         // The highBitSet boolean indicates the value of the high bit of
7151         // the constant which would cause it to be modified for this
7152         // operation.
7153         //
7154         if (isValid && I.getOpcode() == Instruction::AShr)
7155           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7156         
7157         if (isValid) {
7158           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7159           
7160           Instruction *NewShift =
7161             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7162           InsertNewInstBefore(NewShift, I);
7163           NewShift->takeName(Op0BO);
7164           
7165           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7166                                         NewRHS);
7167         }
7168       }
7169     }
7170   }
7171   
7172   // Find out if this is a shift of a shift by a constant.
7173   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7174   if (ShiftOp && !ShiftOp->isShift())
7175     ShiftOp = 0;
7176   
7177   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7178     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7179     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7180     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7181     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7182     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7183     Value *X = ShiftOp->getOperand(0);
7184     
7185     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7186     if (AmtSum > TypeBits)
7187       AmtSum = TypeBits;
7188     
7189     const IntegerType *Ty = cast<IntegerType>(I.getType());
7190     
7191     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7192     if (I.getOpcode() == ShiftOp->getOpcode()) {
7193       return BinaryOperator::Create(I.getOpcode(), X,
7194                                     ConstantInt::get(Ty, AmtSum));
7195     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7196                I.getOpcode() == Instruction::AShr) {
7197       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7198       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7199     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7200                I.getOpcode() == Instruction::LShr) {
7201       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7202       Instruction *Shift =
7203         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7204       InsertNewInstBefore(Shift, I);
7205
7206       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7207       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7208     }
7209     
7210     // Okay, if we get here, one shift must be left, and the other shift must be
7211     // right.  See if the amounts are equal.
7212     if (ShiftAmt1 == ShiftAmt2) {
7213       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7214       if (I.getOpcode() == Instruction::Shl) {
7215         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7216         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7217       }
7218       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7219       if (I.getOpcode() == Instruction::LShr) {
7220         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7221         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7222       }
7223       // We can simplify ((X << C) >>s C) into a trunc + sext.
7224       // NOTE: we could do this for any C, but that would make 'unusual' integer
7225       // types.  For now, just stick to ones well-supported by the code
7226       // generators.
7227       const Type *SExtType = 0;
7228       switch (Ty->getBitWidth() - ShiftAmt1) {
7229       case 1  :
7230       case 8  :
7231       case 16 :
7232       case 32 :
7233       case 64 :
7234       case 128:
7235         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7236         break;
7237       default: break;
7238       }
7239       if (SExtType) {
7240         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7241         InsertNewInstBefore(NewTrunc, I);
7242         return new SExtInst(NewTrunc, Ty);
7243       }
7244       // Otherwise, we can't handle it yet.
7245     } else if (ShiftAmt1 < ShiftAmt2) {
7246       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7247       
7248       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7249       if (I.getOpcode() == Instruction::Shl) {
7250         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7251                ShiftOp->getOpcode() == Instruction::AShr);
7252         Instruction *Shift =
7253           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7254         InsertNewInstBefore(Shift, I);
7255         
7256         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7257         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7258       }
7259       
7260       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7261       if (I.getOpcode() == Instruction::LShr) {
7262         assert(ShiftOp->getOpcode() == Instruction::Shl);
7263         Instruction *Shift =
7264           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7265         InsertNewInstBefore(Shift, I);
7266         
7267         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7268         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7269       }
7270       
7271       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7272     } else {
7273       assert(ShiftAmt2 < ShiftAmt1);
7274       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7275
7276       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7277       if (I.getOpcode() == Instruction::Shl) {
7278         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7279                ShiftOp->getOpcode() == Instruction::AShr);
7280         Instruction *Shift =
7281           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7282                                  ConstantInt::get(Ty, ShiftDiff));
7283         InsertNewInstBefore(Shift, I);
7284         
7285         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7286         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7287       }
7288       
7289       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7290       if (I.getOpcode() == Instruction::LShr) {
7291         assert(ShiftOp->getOpcode() == Instruction::Shl);
7292         Instruction *Shift =
7293           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7294         InsertNewInstBefore(Shift, I);
7295         
7296         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7297         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7298       }
7299       
7300       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7301     }
7302   }
7303   return 0;
7304 }
7305
7306
7307 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7308 /// expression.  If so, decompose it, returning some value X, such that Val is
7309 /// X*Scale+Offset.
7310 ///
7311 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7312                                         int &Offset) {
7313   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7314   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7315     Offset = CI->getZExtValue();
7316     Scale  = 0;
7317     return ConstantInt::get(Type::Int32Ty, 0);
7318   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7319     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7320       if (I->getOpcode() == Instruction::Shl) {
7321         // This is a value scaled by '1 << the shift amt'.
7322         Scale = 1U << RHS->getZExtValue();
7323         Offset = 0;
7324         return I->getOperand(0);
7325       } else if (I->getOpcode() == Instruction::Mul) {
7326         // This value is scaled by 'RHS'.
7327         Scale = RHS->getZExtValue();
7328         Offset = 0;
7329         return I->getOperand(0);
7330       } else if (I->getOpcode() == Instruction::Add) {
7331         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7332         // where C1 is divisible by C2.
7333         unsigned SubScale;
7334         Value *SubVal = 
7335           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7336         Offset += RHS->getZExtValue();
7337         Scale = SubScale;
7338         return SubVal;
7339       }
7340     }
7341   }
7342
7343   // Otherwise, we can't look past this.
7344   Scale = 1;
7345   Offset = 0;
7346   return Val;
7347 }
7348
7349
7350 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7351 /// try to eliminate the cast by moving the type information into the alloc.
7352 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7353                                                    AllocationInst &AI) {
7354   const PointerType *PTy = cast<PointerType>(CI.getType());
7355   
7356   // Remove any uses of AI that are dead.
7357   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7358   
7359   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7360     Instruction *User = cast<Instruction>(*UI++);
7361     if (isInstructionTriviallyDead(User)) {
7362       while (UI != E && *UI == User)
7363         ++UI; // If this instruction uses AI more than once, don't break UI.
7364       
7365       ++NumDeadInst;
7366       DOUT << "IC: DCE: " << *User;
7367       EraseInstFromFunction(*User);
7368     }
7369   }
7370   
7371   // Get the type really allocated and the type casted to.
7372   const Type *AllocElTy = AI.getAllocatedType();
7373   const Type *CastElTy = PTy->getElementType();
7374   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7375
7376   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7377   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7378   if (CastElTyAlign < AllocElTyAlign) return 0;
7379
7380   // If the allocation has multiple uses, only promote it if we are strictly
7381   // increasing the alignment of the resultant allocation.  If we keep it the
7382   // same, we open the door to infinite loops of various kinds.
7383   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7384
7385   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7386   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7387   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7388
7389   // See if we can satisfy the modulus by pulling a scale out of the array
7390   // size argument.
7391   unsigned ArraySizeScale;
7392   int ArrayOffset;
7393   Value *NumElements = // See if the array size is a decomposable linear expr.
7394     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7395  
7396   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7397   // do the xform.
7398   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7399       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7400
7401   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7402   Value *Amt = 0;
7403   if (Scale == 1) {
7404     Amt = NumElements;
7405   } else {
7406     // If the allocation size is constant, form a constant mul expression
7407     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7408     if (isa<ConstantInt>(NumElements))
7409       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7410     // otherwise multiply the amount and the number of elements
7411     else if (Scale != 1) {
7412       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7413       Amt = InsertNewInstBefore(Tmp, AI);
7414     }
7415   }
7416   
7417   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7418     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7419     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7420     Amt = InsertNewInstBefore(Tmp, AI);
7421   }
7422   
7423   AllocationInst *New;
7424   if (isa<MallocInst>(AI))
7425     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7426   else
7427     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7428   InsertNewInstBefore(New, AI);
7429   New->takeName(&AI);
7430   
7431   // If the allocation has multiple uses, insert a cast and change all things
7432   // that used it to use the new cast.  This will also hack on CI, but it will
7433   // die soon.
7434   if (!AI.hasOneUse()) {
7435     AddUsesToWorkList(AI);
7436     // New is the allocation instruction, pointer typed. AI is the original
7437     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7438     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7439     InsertNewInstBefore(NewCast, AI);
7440     AI.replaceAllUsesWith(NewCast);
7441   }
7442   return ReplaceInstUsesWith(CI, New);
7443 }
7444
7445 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7446 /// and return it as type Ty without inserting any new casts and without
7447 /// changing the computed value.  This is used by code that tries to decide
7448 /// whether promoting or shrinking integer operations to wider or smaller types
7449 /// will allow us to eliminate a truncate or extend.
7450 ///
7451 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7452 /// extension operation if Ty is larger.
7453 ///
7454 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7455 /// should return true if trunc(V) can be computed by computing V in the smaller
7456 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7457 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7458 /// efficiently truncated.
7459 ///
7460 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7461 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7462 /// the final result.
7463 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7464                                               unsigned CastOpc,
7465                                               int &NumCastsRemoved) {
7466   // We can always evaluate constants in another type.
7467   if (isa<ConstantInt>(V))
7468     return true;
7469   
7470   Instruction *I = dyn_cast<Instruction>(V);
7471   if (!I) return false;
7472   
7473   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7474   
7475   // If this is an extension or truncate, we can often eliminate it.
7476   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7477     // If this is a cast from the destination type, we can trivially eliminate
7478     // it, and this will remove a cast overall.
7479     if (I->getOperand(0)->getType() == Ty) {
7480       // If the first operand is itself a cast, and is eliminable, do not count
7481       // this as an eliminable cast.  We would prefer to eliminate those two
7482       // casts first.
7483       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7484         ++NumCastsRemoved;
7485       return true;
7486     }
7487   }
7488
7489   // We can't extend or shrink something that has multiple uses: doing so would
7490   // require duplicating the instruction in general, which isn't profitable.
7491   if (!I->hasOneUse()) return false;
7492
7493   switch (I->getOpcode()) {
7494   case Instruction::Add:
7495   case Instruction::Sub:
7496   case Instruction::Mul:
7497   case Instruction::And:
7498   case Instruction::Or:
7499   case Instruction::Xor:
7500     // These operators can all arbitrarily be extended or truncated.
7501     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7502                                       NumCastsRemoved) &&
7503            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7504                                       NumCastsRemoved);
7505
7506   case Instruction::Shl:
7507     // If we are truncating the result of this SHL, and if it's a shift of a
7508     // constant amount, we can always perform a SHL in a smaller type.
7509     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7510       uint32_t BitWidth = Ty->getBitWidth();
7511       if (BitWidth < OrigTy->getBitWidth() && 
7512           CI->getLimitedValue(BitWidth) < BitWidth)
7513         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7514                                           NumCastsRemoved);
7515     }
7516     break;
7517   case Instruction::LShr:
7518     // If this is a truncate of a logical shr, we can truncate it to a smaller
7519     // lshr iff we know that the bits we would otherwise be shifting in are
7520     // already zeros.
7521     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7522       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7523       uint32_t BitWidth = Ty->getBitWidth();
7524       if (BitWidth < OrigBitWidth &&
7525           MaskedValueIsZero(I->getOperand(0),
7526             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7527           CI->getLimitedValue(BitWidth) < BitWidth) {
7528         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7529                                           NumCastsRemoved);
7530       }
7531     }
7532     break;
7533   case Instruction::ZExt:
7534   case Instruction::SExt:
7535   case Instruction::Trunc:
7536     // If this is the same kind of case as our original (e.g. zext+zext), we
7537     // can safely replace it.  Note that replacing it does not reduce the number
7538     // of casts in the input.
7539     if (I->getOpcode() == CastOpc)
7540       return true;
7541     break;
7542   case Instruction::Select: {
7543     SelectInst *SI = cast<SelectInst>(I);
7544     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7545                                       NumCastsRemoved) &&
7546            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7547                                       NumCastsRemoved);
7548   }
7549   case Instruction::PHI: {
7550     // We can change a phi if we can change all operands.
7551     PHINode *PN = cast<PHINode>(I);
7552     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7553       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7554                                       NumCastsRemoved))
7555         return false;
7556     return true;
7557   }
7558   default:
7559     // TODO: Can handle more cases here.
7560     break;
7561   }
7562   
7563   return false;
7564 }
7565
7566 /// EvaluateInDifferentType - Given an expression that 
7567 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7568 /// evaluate the expression.
7569 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7570                                              bool isSigned) {
7571   if (Constant *C = dyn_cast<Constant>(V))
7572     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7573
7574   // Otherwise, it must be an instruction.
7575   Instruction *I = cast<Instruction>(V);
7576   Instruction *Res = 0;
7577   switch (I->getOpcode()) {
7578   case Instruction::Add:
7579   case Instruction::Sub:
7580   case Instruction::Mul:
7581   case Instruction::And:
7582   case Instruction::Or:
7583   case Instruction::Xor:
7584   case Instruction::AShr:
7585   case Instruction::LShr:
7586   case Instruction::Shl: {
7587     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7588     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7589     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7590                                  LHS, RHS);
7591     break;
7592   }    
7593   case Instruction::Trunc:
7594   case Instruction::ZExt:
7595   case Instruction::SExt:
7596     // If the source type of the cast is the type we're trying for then we can
7597     // just return the source.  There's no need to insert it because it is not
7598     // new.
7599     if (I->getOperand(0)->getType() == Ty)
7600       return I->getOperand(0);
7601     
7602     // Otherwise, must be the same type of cast, so just reinsert a new one.
7603     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7604                            Ty);
7605     break;
7606   case Instruction::Select: {
7607     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7608     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7609     Res = SelectInst::Create(I->getOperand(0), True, False);
7610     break;
7611   }
7612   case Instruction::PHI: {
7613     PHINode *OPN = cast<PHINode>(I);
7614     PHINode *NPN = PHINode::Create(Ty);
7615     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7616       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7617       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7618     }
7619     Res = NPN;
7620     break;
7621   }
7622   default: 
7623     // TODO: Can handle more cases here.
7624     assert(0 && "Unreachable!");
7625     break;
7626   }
7627   
7628   Res->takeName(I);
7629   return InsertNewInstBefore(Res, *I);
7630 }
7631
7632 /// @brief Implement the transforms common to all CastInst visitors.
7633 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7634   Value *Src = CI.getOperand(0);
7635
7636   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7637   // eliminate it now.
7638   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7639     if (Instruction::CastOps opc = 
7640         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7641       // The first cast (CSrc) is eliminable so we need to fix up or replace
7642       // the second cast (CI). CSrc will then have a good chance of being dead.
7643       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7644     }
7645   }
7646
7647   // If we are casting a select then fold the cast into the select
7648   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7649     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7650       return NV;
7651
7652   // If we are casting a PHI then fold the cast into the PHI
7653   if (isa<PHINode>(Src))
7654     if (Instruction *NV = FoldOpIntoPhi(CI))
7655       return NV;
7656   
7657   return 0;
7658 }
7659
7660 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7661 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7662   Value *Src = CI.getOperand(0);
7663   
7664   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7665     // If casting the result of a getelementptr instruction with no offset, turn
7666     // this into a cast of the original pointer!
7667     if (GEP->hasAllZeroIndices()) {
7668       // Changing the cast operand is usually not a good idea but it is safe
7669       // here because the pointer operand is being replaced with another 
7670       // pointer operand so the opcode doesn't need to change.
7671       AddToWorkList(GEP);
7672       CI.setOperand(0, GEP->getOperand(0));
7673       return &CI;
7674     }
7675     
7676     // If the GEP has a single use, and the base pointer is a bitcast, and the
7677     // GEP computes a constant offset, see if we can convert these three
7678     // instructions into fewer.  This typically happens with unions and other
7679     // non-type-safe code.
7680     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7681       if (GEP->hasAllConstantIndices()) {
7682         // We are guaranteed to get a constant from EmitGEPOffset.
7683         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7684         int64_t Offset = OffsetV->getSExtValue();
7685         
7686         // Get the base pointer input of the bitcast, and the type it points to.
7687         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7688         const Type *GEPIdxTy =
7689           cast<PointerType>(OrigBase->getType())->getElementType();
7690         if (GEPIdxTy->isSized()) {
7691           SmallVector<Value*, 8> NewIndices;
7692           
7693           // Start with the index over the outer type.  Note that the type size
7694           // might be zero (even if the offset isn't zero) if the indexed type
7695           // is something like [0 x {int, int}]
7696           const Type *IntPtrTy = TD->getIntPtrType();
7697           int64_t FirstIdx = 0;
7698           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7699             FirstIdx = Offset/TySize;
7700             Offset %= TySize;
7701           
7702             // Handle silly modulus not returning values values [0..TySize).
7703             if (Offset < 0) {
7704               --FirstIdx;
7705               Offset += TySize;
7706               assert(Offset >= 0);
7707             }
7708             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7709           }
7710           
7711           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7712
7713           // Index into the types.  If we fail, set OrigBase to null.
7714           while (Offset) {
7715             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7716               const StructLayout *SL = TD->getStructLayout(STy);
7717               if (Offset < (int64_t)SL->getSizeInBytes()) {
7718                 unsigned Elt = SL->getElementContainingOffset(Offset);
7719                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7720               
7721                 Offset -= SL->getElementOffset(Elt);
7722                 GEPIdxTy = STy->getElementType(Elt);
7723               } else {
7724                 // Otherwise, we can't index into this, bail out.
7725                 Offset = 0;
7726                 OrigBase = 0;
7727               }
7728             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7729               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7730               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7731                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7732                 Offset %= EltSize;
7733               } else {
7734                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7735               }
7736               GEPIdxTy = STy->getElementType();
7737             } else {
7738               // Otherwise, we can't index into this, bail out.
7739               Offset = 0;
7740               OrigBase = 0;
7741             }
7742           }
7743           if (OrigBase) {
7744             // If we were able to index down into an element, create the GEP
7745             // and bitcast the result.  This eliminates one bitcast, potentially
7746             // two.
7747             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7748                                                           NewIndices.begin(),
7749                                                           NewIndices.end(), "");
7750             InsertNewInstBefore(NGEP, CI);
7751             NGEP->takeName(GEP);
7752             
7753             if (isa<BitCastInst>(CI))
7754               return new BitCastInst(NGEP, CI.getType());
7755             assert(isa<PtrToIntInst>(CI));
7756             return new PtrToIntInst(NGEP, CI.getType());
7757           }
7758         }
7759       }      
7760     }
7761   }
7762     
7763   return commonCastTransforms(CI);
7764 }
7765
7766
7767
7768 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7769 /// integer types. This function implements the common transforms for all those
7770 /// cases.
7771 /// @brief Implement the transforms common to CastInst with integer operands
7772 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7773   if (Instruction *Result = commonCastTransforms(CI))
7774     return Result;
7775
7776   Value *Src = CI.getOperand(0);
7777   const Type *SrcTy = Src->getType();
7778   const Type *DestTy = CI.getType();
7779   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7780   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7781
7782   // See if we can simplify any instructions used by the LHS whose sole 
7783   // purpose is to compute bits we don't care about.
7784   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7785   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7786                            KnownZero, KnownOne))
7787     return &CI;
7788
7789   // If the source isn't an instruction or has more than one use then we
7790   // can't do anything more. 
7791   Instruction *SrcI = dyn_cast<Instruction>(Src);
7792   if (!SrcI || !Src->hasOneUse())
7793     return 0;
7794
7795   // Attempt to propagate the cast into the instruction for int->int casts.
7796   int NumCastsRemoved = 0;
7797   if (!isa<BitCastInst>(CI) &&
7798       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7799                                  CI.getOpcode(), NumCastsRemoved)) {
7800     // If this cast is a truncate, evaluting in a different type always
7801     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7802     // we need to do an AND to maintain the clear top-part of the computation,
7803     // so we require that the input have eliminated at least one cast.  If this
7804     // is a sign extension, we insert two new casts (to do the extension) so we
7805     // require that two casts have been eliminated.
7806     bool DoXForm;
7807     switch (CI.getOpcode()) {
7808     default:
7809       // All the others use floating point so we shouldn't actually 
7810       // get here because of the check above.
7811       assert(0 && "Unknown cast type");
7812     case Instruction::Trunc:
7813       DoXForm = true;
7814       break;
7815     case Instruction::ZExt:
7816       DoXForm = NumCastsRemoved >= 1;
7817       break;
7818     case Instruction::SExt:
7819       DoXForm = NumCastsRemoved >= 2;
7820       break;
7821     }
7822     
7823     if (DoXForm) {
7824       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7825                                            CI.getOpcode() == Instruction::SExt);
7826       assert(Res->getType() == DestTy);
7827       switch (CI.getOpcode()) {
7828       default: assert(0 && "Unknown cast type!");
7829       case Instruction::Trunc:
7830       case Instruction::BitCast:
7831         // Just replace this cast with the result.
7832         return ReplaceInstUsesWith(CI, Res);
7833       case Instruction::ZExt: {
7834         // We need to emit an AND to clear the high bits.
7835         assert(SrcBitSize < DestBitSize && "Not a zext?");
7836         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7837                                                             SrcBitSize));
7838         return BinaryOperator::CreateAnd(Res, C);
7839       }
7840       case Instruction::SExt:
7841         // We need to emit a cast to truncate, then a cast to sext.
7842         return CastInst::Create(Instruction::SExt,
7843             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7844                              CI), DestTy);
7845       }
7846     }
7847   }
7848   
7849   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7850   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7851
7852   switch (SrcI->getOpcode()) {
7853   case Instruction::Add:
7854   case Instruction::Mul:
7855   case Instruction::And:
7856   case Instruction::Or:
7857   case Instruction::Xor:
7858     // If we are discarding information, rewrite.
7859     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7860       // Don't insert two casts if they cannot be eliminated.  We allow 
7861       // two casts to be inserted if the sizes are the same.  This could 
7862       // only be converting signedness, which is a noop.
7863       if (DestBitSize == SrcBitSize || 
7864           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7865           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7866         Instruction::CastOps opcode = CI.getOpcode();
7867         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7868         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7869         return BinaryOperator::Create(
7870             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7871       }
7872     }
7873
7874     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7875     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7876         SrcI->getOpcode() == Instruction::Xor &&
7877         Op1 == ConstantInt::getTrue() &&
7878         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7879       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7880       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7881     }
7882     break;
7883   case Instruction::SDiv:
7884   case Instruction::UDiv:
7885   case Instruction::SRem:
7886   case Instruction::URem:
7887     // If we are just changing the sign, rewrite.
7888     if (DestBitSize == SrcBitSize) {
7889       // Don't insert two casts if they cannot be eliminated.  We allow 
7890       // two casts to be inserted if the sizes are the same.  This could 
7891       // only be converting signedness, which is a noop.
7892       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7893           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7894         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
7895                                        Op0, DestTy, *SrcI);
7896         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
7897                                        Op1, DestTy, *SrcI);
7898         return BinaryOperator::Create(
7899           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7900       }
7901     }
7902     break;
7903
7904   case Instruction::Shl:
7905     // Allow changing the sign of the source operand.  Do not allow 
7906     // changing the size of the shift, UNLESS the shift amount is a 
7907     // constant.  We must not change variable sized shifts to a smaller 
7908     // size, because it is undefined to shift more bits out than exist 
7909     // in the value.
7910     if (DestBitSize == SrcBitSize ||
7911         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7912       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7913           Instruction::BitCast : Instruction::Trunc);
7914       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7915       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7916       return BinaryOperator::CreateShl(Op0c, Op1c);
7917     }
7918     break;
7919   case Instruction::AShr:
7920     // If this is a signed shr, and if all bits shifted in are about to be
7921     // truncated off, turn it into an unsigned shr to allow greater
7922     // simplifications.
7923     if (DestBitSize < SrcBitSize &&
7924         isa<ConstantInt>(Op1)) {
7925       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7926       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7927         // Insert the new logical shift right.
7928         return BinaryOperator::CreateLShr(Op0, Op1);
7929       }
7930     }
7931     break;
7932   }
7933   return 0;
7934 }
7935
7936 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7937   if (Instruction *Result = commonIntCastTransforms(CI))
7938     return Result;
7939   
7940   Value *Src = CI.getOperand(0);
7941   const Type *Ty = CI.getType();
7942   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7943   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7944   
7945   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7946     switch (SrcI->getOpcode()) {
7947     default: break;
7948     case Instruction::LShr:
7949       // We can shrink lshr to something smaller if we know the bits shifted in
7950       // are already zeros.
7951       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7952         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7953         
7954         // Get a mask for the bits shifting in.
7955         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7956         Value* SrcIOp0 = SrcI->getOperand(0);
7957         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7958           if (ShAmt >= DestBitWidth)        // All zeros.
7959             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7960
7961           // Okay, we can shrink this.  Truncate the input, then return a new
7962           // shift.
7963           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7964           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7965                                        Ty, CI);
7966           return BinaryOperator::CreateLShr(V1, V2);
7967         }
7968       } else {     // This is a variable shr.
7969         
7970         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7971         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7972         // loop-invariant and CSE'd.
7973         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7974           Value *One = ConstantInt::get(SrcI->getType(), 1);
7975
7976           Value *V = InsertNewInstBefore(
7977               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7978                                      "tmp"), CI);
7979           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7980                                                             SrcI->getOperand(0),
7981                                                             "tmp"), CI);
7982           Value *Zero = Constant::getNullValue(V->getType());
7983           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7984         }
7985       }
7986       break;
7987     }
7988   }
7989   
7990   return 0;
7991 }
7992
7993 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7994 /// in order to eliminate the icmp.
7995 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7996                                              bool DoXform) {
7997   // If we are just checking for a icmp eq of a single bit and zext'ing it
7998   // to an integer, then shift the bit to the appropriate place and then
7999   // cast to integer to avoid the comparison.
8000   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8001     const APInt &Op1CV = Op1C->getValue();
8002       
8003     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8004     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8005     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8006         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8007       if (!DoXform) return ICI;
8008
8009       Value *In = ICI->getOperand(0);
8010       Value *Sh = ConstantInt::get(In->getType(),
8011                                    In->getType()->getPrimitiveSizeInBits()-1);
8012       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8013                                                         In->getName()+".lobit"),
8014                                CI);
8015       if (In->getType() != CI.getType())
8016         In = CastInst::CreateIntegerCast(In, CI.getType(),
8017                                          false/*ZExt*/, "tmp", &CI);
8018
8019       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8020         Constant *One = ConstantInt::get(In->getType(), 1);
8021         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8022                                                          In->getName()+".not"),
8023                                  CI);
8024       }
8025
8026       return ReplaceInstUsesWith(CI, In);
8027     }
8028       
8029       
8030       
8031     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8032     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8033     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8034     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8035     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8036     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8037     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8038     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8039     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8040         // This only works for EQ and NE
8041         ICI->isEquality()) {
8042       // If Op1C some other power of two, convert:
8043       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8044       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8045       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8046       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8047         
8048       APInt KnownZeroMask(~KnownZero);
8049       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8050         if (!DoXform) return ICI;
8051
8052         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8053         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8054           // (X&4) == 2 --> false
8055           // (X&4) != 2 --> true
8056           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8057           Res = ConstantExpr::getZExt(Res, CI.getType());
8058           return ReplaceInstUsesWith(CI, Res);
8059         }
8060           
8061         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8062         Value *In = ICI->getOperand(0);
8063         if (ShiftAmt) {
8064           // Perform a logical shr by shiftamt.
8065           // Insert the shift to put the result in the low bit.
8066           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8067                                   ConstantInt::get(In->getType(), ShiftAmt),
8068                                                    In->getName()+".lobit"), CI);
8069         }
8070           
8071         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8072           Constant *One = ConstantInt::get(In->getType(), 1);
8073           In = BinaryOperator::CreateXor(In, One, "tmp");
8074           InsertNewInstBefore(cast<Instruction>(In), CI);
8075         }
8076           
8077         if (CI.getType() == In->getType())
8078           return ReplaceInstUsesWith(CI, In);
8079         else
8080           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8081       }
8082     }
8083   }
8084
8085   return 0;
8086 }
8087
8088 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8089   // If one of the common conversion will work ..
8090   if (Instruction *Result = commonIntCastTransforms(CI))
8091     return Result;
8092
8093   Value *Src = CI.getOperand(0);
8094
8095   // If this is a cast of a cast
8096   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8097     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8098     // types and if the sizes are just right we can convert this into a logical
8099     // 'and' which will be much cheaper than the pair of casts.
8100     if (isa<TruncInst>(CSrc)) {
8101       // Get the sizes of the types involved
8102       Value *A = CSrc->getOperand(0);
8103       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8104       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8105       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8106       // If we're actually extending zero bits and the trunc is a no-op
8107       if (MidSize < DstSize && SrcSize == DstSize) {
8108         // Replace both of the casts with an And of the type mask.
8109         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8110         Constant *AndConst = ConstantInt::get(AndValue);
8111         Instruction *And = 
8112           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8113         // Unfortunately, if the type changed, we need to cast it back.
8114         if (And->getType() != CI.getType()) {
8115           And->setName(CSrc->getName()+".mask");
8116           InsertNewInstBefore(And, CI);
8117           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8118         }
8119         return And;
8120       }
8121     }
8122   }
8123
8124   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8125     return transformZExtICmp(ICI, CI);
8126
8127   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8128   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8129     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8130     // of the (zext icmp) will be transformed.
8131     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8132     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8133     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8134         (transformZExtICmp(LHS, CI, false) ||
8135          transformZExtICmp(RHS, CI, false))) {
8136       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8137       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8138       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8139     }
8140   }
8141
8142   return 0;
8143 }
8144
8145 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8146   if (Instruction *I = commonIntCastTransforms(CI))
8147     return I;
8148   
8149   Value *Src = CI.getOperand(0);
8150   
8151   // Canonicalize sign-extend from i1 to a select.
8152   if (Src->getType() == Type::Int1Ty)
8153     return SelectInst::Create(Src,
8154                               ConstantInt::getAllOnesValue(CI.getType()),
8155                               Constant::getNullValue(CI.getType()));
8156
8157   // See if the value being truncated is already sign extended.  If so, just
8158   // eliminate the trunc/sext pair.
8159   if (getOpcode(Src) == Instruction::Trunc) {
8160     Value *Op = cast<User>(Src)->getOperand(0);
8161     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8162     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8163     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8164     unsigned NumSignBits = ComputeNumSignBits(Op);
8165
8166     if (OpBits == DestBits) {
8167       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8168       // bits, it is already ready.
8169       if (NumSignBits > DestBits-MidBits)
8170         return ReplaceInstUsesWith(CI, Op);
8171     } else if (OpBits < DestBits) {
8172       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8173       // bits, just sext from i32.
8174       if (NumSignBits > OpBits-MidBits)
8175         return new SExtInst(Op, CI.getType(), "tmp");
8176     } else {
8177       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8178       // bits, just truncate to i32.
8179       if (NumSignBits > OpBits-MidBits)
8180         return new TruncInst(Op, CI.getType(), "tmp");
8181     }
8182   }
8183
8184   // If the input is a shl/ashr pair of a same constant, then this is a sign
8185   // extension from a smaller value.  If we could trust arbitrary bitwidth
8186   // integers, we could turn this into a truncate to the smaller bit and then
8187   // use a sext for the whole extension.  Since we don't, look deeper and check
8188   // for a truncate.  If the source and dest are the same type, eliminate the
8189   // trunc and extend and just do shifts.  For example, turn:
8190   //   %a = trunc i32 %i to i8
8191   //   %b = shl i8 %a, 6
8192   //   %c = ashr i8 %b, 6
8193   //   %d = sext i8 %c to i32
8194   // into:
8195   //   %a = shl i32 %i, 30
8196   //   %d = ashr i32 %a, 30
8197   Value *A = 0;
8198   ConstantInt *BA = 0, *CA = 0;
8199   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8200                         m_ConstantInt(CA))) &&
8201       BA == CA && isa<TruncInst>(A)) {
8202     Value *I = cast<TruncInst>(A)->getOperand(0);
8203     if (I->getType() == CI.getType()) {
8204       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8205       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8206       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8207       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8208       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8209                                                         CI.getName()), CI);
8210       return BinaryOperator::CreateAShr(I, ShAmtV);
8211     }
8212   }
8213   
8214   return 0;
8215 }
8216
8217 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8218 /// in the specified FP type without changing its value.
8219 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8220   bool losesInfo;
8221   APFloat F = CFP->getValueAPF();
8222   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8223   if (!losesInfo)
8224     return ConstantFP::get(F);
8225   return 0;
8226 }
8227
8228 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8229 /// through it until we get the source value.
8230 static Value *LookThroughFPExtensions(Value *V) {
8231   if (Instruction *I = dyn_cast<Instruction>(V))
8232     if (I->getOpcode() == Instruction::FPExt)
8233       return LookThroughFPExtensions(I->getOperand(0));
8234   
8235   // If this value is a constant, return the constant in the smallest FP type
8236   // that can accurately represent it.  This allows us to turn
8237   // (float)((double)X+2.0) into x+2.0f.
8238   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8239     if (CFP->getType() == Type::PPC_FP128Ty)
8240       return V;  // No constant folding of this.
8241     // See if the value can be truncated to float and then reextended.
8242     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8243       return V;
8244     if (CFP->getType() == Type::DoubleTy)
8245       return V;  // Won't shrink.
8246     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8247       return V;
8248     // Don't try to shrink to various long double types.
8249   }
8250   
8251   return V;
8252 }
8253
8254 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8255   if (Instruction *I = commonCastTransforms(CI))
8256     return I;
8257   
8258   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8259   // smaller than the destination type, we can eliminate the truncate by doing
8260   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8261   // many builtins (sqrt, etc).
8262   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8263   if (OpI && OpI->hasOneUse()) {
8264     switch (OpI->getOpcode()) {
8265     default: break;
8266     case Instruction::Add:
8267     case Instruction::Sub:
8268     case Instruction::Mul:
8269     case Instruction::FDiv:
8270     case Instruction::FRem:
8271       const Type *SrcTy = OpI->getType();
8272       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8273       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8274       if (LHSTrunc->getType() != SrcTy && 
8275           RHSTrunc->getType() != SrcTy) {
8276         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8277         // If the source types were both smaller than the destination type of
8278         // the cast, do this xform.
8279         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8280             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8281           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8282                                       CI.getType(), CI);
8283           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8284                                       CI.getType(), CI);
8285           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8286         }
8287       }
8288       break;  
8289     }
8290   }
8291   return 0;
8292 }
8293
8294 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8295   return commonCastTransforms(CI);
8296 }
8297
8298 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8299   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8300   if (OpI == 0)
8301     return commonCastTransforms(FI);
8302
8303   // fptoui(uitofp(X)) --> X
8304   // fptoui(sitofp(X)) --> X
8305   // This is safe if the intermediate type has enough bits in its mantissa to
8306   // accurately represent all values of X.  For example, do not do this with
8307   // i64->float->i64.  This is also safe for sitofp case, because any negative
8308   // 'X' value would cause an undefined result for the fptoui. 
8309   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8310       OpI->getOperand(0)->getType() == FI.getType() &&
8311       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8312                     OpI->getType()->getFPMantissaWidth())
8313     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8314
8315   return commonCastTransforms(FI);
8316 }
8317
8318 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8319   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8320   if (OpI == 0)
8321     return commonCastTransforms(FI);
8322   
8323   // fptosi(sitofp(X)) --> X
8324   // fptosi(uitofp(X)) --> X
8325   // This is safe if the intermediate type has enough bits in its mantissa to
8326   // accurately represent all values of X.  For example, do not do this with
8327   // i64->float->i64.  This is also safe for sitofp case, because any negative
8328   // 'X' value would cause an undefined result for the fptoui. 
8329   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8330       OpI->getOperand(0)->getType() == FI.getType() &&
8331       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8332                     OpI->getType()->getFPMantissaWidth())
8333     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8334   
8335   return commonCastTransforms(FI);
8336 }
8337
8338 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8339   return commonCastTransforms(CI);
8340 }
8341
8342 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8343   return commonCastTransforms(CI);
8344 }
8345
8346 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8347   return commonPointerCastTransforms(CI);
8348 }
8349
8350 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8351   if (Instruction *I = commonCastTransforms(CI))
8352     return I;
8353   
8354   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8355   if (!DestPointee->isSized()) return 0;
8356
8357   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8358   ConstantInt *Cst;
8359   Value *X;
8360   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8361                                     m_ConstantInt(Cst)))) {
8362     // If the source and destination operands have the same type, see if this
8363     // is a single-index GEP.
8364     if (X->getType() == CI.getType()) {
8365       // Get the size of the pointee type.
8366       uint64_t Size = TD->getABITypeSize(DestPointee);
8367
8368       // Convert the constant to intptr type.
8369       APInt Offset = Cst->getValue();
8370       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8371
8372       // If Offset is evenly divisible by Size, we can do this xform.
8373       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8374         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8375         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8376       }
8377     }
8378     // TODO: Could handle other cases, e.g. where add is indexing into field of
8379     // struct etc.
8380   } else if (CI.getOperand(0)->hasOneUse() &&
8381              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8382     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8383     // "inttoptr+GEP" instead of "add+intptr".
8384     
8385     // Get the size of the pointee type.
8386     uint64_t Size = TD->getABITypeSize(DestPointee);
8387     
8388     // Convert the constant to intptr type.
8389     APInt Offset = Cst->getValue();
8390     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8391     
8392     // If Offset is evenly divisible by Size, we can do this xform.
8393     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8394       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8395       
8396       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8397                                                             "tmp"), CI);
8398       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8399     }
8400   }
8401   return 0;
8402 }
8403
8404 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8405   // If the operands are integer typed then apply the integer transforms,
8406   // otherwise just apply the common ones.
8407   Value *Src = CI.getOperand(0);
8408   const Type *SrcTy = Src->getType();
8409   const Type *DestTy = CI.getType();
8410
8411   if (SrcTy->isInteger() && DestTy->isInteger()) {
8412     if (Instruction *Result = commonIntCastTransforms(CI))
8413       return Result;
8414   } else if (isa<PointerType>(SrcTy)) {
8415     if (Instruction *I = commonPointerCastTransforms(CI))
8416       return I;
8417   } else {
8418     if (Instruction *Result = commonCastTransforms(CI))
8419       return Result;
8420   }
8421
8422
8423   // Get rid of casts from one type to the same type. These are useless and can
8424   // be replaced by the operand.
8425   if (DestTy == Src->getType())
8426     return ReplaceInstUsesWith(CI, Src);
8427
8428   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8429     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8430     const Type *DstElTy = DstPTy->getElementType();
8431     const Type *SrcElTy = SrcPTy->getElementType();
8432     
8433     // If the address spaces don't match, don't eliminate the bitcast, which is
8434     // required for changing types.
8435     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8436       return 0;
8437     
8438     // If we are casting a malloc or alloca to a pointer to a type of the same
8439     // size, rewrite the allocation instruction to allocate the "right" type.
8440     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8441       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8442         return V;
8443     
8444     // If the source and destination are pointers, and this cast is equivalent
8445     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8446     // This can enhance SROA and other transforms that want type-safe pointers.
8447     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8448     unsigned NumZeros = 0;
8449     while (SrcElTy != DstElTy && 
8450            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8451            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8452       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8453       ++NumZeros;
8454     }
8455
8456     // If we found a path from the src to dest, create the getelementptr now.
8457     if (SrcElTy == DstElTy) {
8458       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8459       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8460                                        ((Instruction*) NULL));
8461     }
8462   }
8463
8464   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8465     if (SVI->hasOneUse()) {
8466       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8467       // a bitconvert to a vector with the same # elts.
8468       if (isa<VectorType>(DestTy) && 
8469           cast<VectorType>(DestTy)->getNumElements() ==
8470                 SVI->getType()->getNumElements() &&
8471           SVI->getType()->getNumElements() ==
8472             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8473         CastInst *Tmp;
8474         // If either of the operands is a cast from CI.getType(), then
8475         // evaluating the shuffle in the casted destination's type will allow
8476         // us to eliminate at least one cast.
8477         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8478              Tmp->getOperand(0)->getType() == DestTy) ||
8479             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8480              Tmp->getOperand(0)->getType() == DestTy)) {
8481           Value *LHS = InsertCastBefore(Instruction::BitCast,
8482                                         SVI->getOperand(0), DestTy, CI);
8483           Value *RHS = InsertCastBefore(Instruction::BitCast,
8484                                         SVI->getOperand(1), DestTy, CI);
8485           // Return a new shuffle vector.  Use the same element ID's, as we
8486           // know the vector types match #elts.
8487           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8488         }
8489       }
8490     }
8491   }
8492   return 0;
8493 }
8494
8495 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8496 ///   %C = or %A, %B
8497 ///   %D = select %cond, %C, %A
8498 /// into:
8499 ///   %C = select %cond, %B, 0
8500 ///   %D = or %A, %C
8501 ///
8502 /// Assuming that the specified instruction is an operand to the select, return
8503 /// a bitmask indicating which operands of this instruction are foldable if they
8504 /// equal the other incoming value of the select.
8505 ///
8506 static unsigned GetSelectFoldableOperands(Instruction *I) {
8507   switch (I->getOpcode()) {
8508   case Instruction::Add:
8509   case Instruction::Mul:
8510   case Instruction::And:
8511   case Instruction::Or:
8512   case Instruction::Xor:
8513     return 3;              // Can fold through either operand.
8514   case Instruction::Sub:   // Can only fold on the amount subtracted.
8515   case Instruction::Shl:   // Can only fold on the shift amount.
8516   case Instruction::LShr:
8517   case Instruction::AShr:
8518     return 1;
8519   default:
8520     return 0;              // Cannot fold
8521   }
8522 }
8523
8524 /// GetSelectFoldableConstant - For the same transformation as the previous
8525 /// function, return the identity constant that goes into the select.
8526 static Constant *GetSelectFoldableConstant(Instruction *I) {
8527   switch (I->getOpcode()) {
8528   default: assert(0 && "This cannot happen!"); abort();
8529   case Instruction::Add:
8530   case Instruction::Sub:
8531   case Instruction::Or:
8532   case Instruction::Xor:
8533   case Instruction::Shl:
8534   case Instruction::LShr:
8535   case Instruction::AShr:
8536     return Constant::getNullValue(I->getType());
8537   case Instruction::And:
8538     return Constant::getAllOnesValue(I->getType());
8539   case Instruction::Mul:
8540     return ConstantInt::get(I->getType(), 1);
8541   }
8542 }
8543
8544 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8545 /// have the same opcode and only one use each.  Try to simplify this.
8546 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8547                                           Instruction *FI) {
8548   if (TI->getNumOperands() == 1) {
8549     // If this is a non-volatile load or a cast from the same type,
8550     // merge.
8551     if (TI->isCast()) {
8552       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8553         return 0;
8554     } else {
8555       return 0;  // unknown unary op.
8556     }
8557
8558     // Fold this by inserting a select from the input values.
8559     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8560                                            FI->getOperand(0), SI.getName()+".v");
8561     InsertNewInstBefore(NewSI, SI);
8562     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8563                             TI->getType());
8564   }
8565
8566   // Only handle binary operators here.
8567   if (!isa<BinaryOperator>(TI))
8568     return 0;
8569
8570   // Figure out if the operations have any operands in common.
8571   Value *MatchOp, *OtherOpT, *OtherOpF;
8572   bool MatchIsOpZero;
8573   if (TI->getOperand(0) == FI->getOperand(0)) {
8574     MatchOp  = TI->getOperand(0);
8575     OtherOpT = TI->getOperand(1);
8576     OtherOpF = FI->getOperand(1);
8577     MatchIsOpZero = true;
8578   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8579     MatchOp  = TI->getOperand(1);
8580     OtherOpT = TI->getOperand(0);
8581     OtherOpF = FI->getOperand(0);
8582     MatchIsOpZero = false;
8583   } else if (!TI->isCommutative()) {
8584     return 0;
8585   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8586     MatchOp  = TI->getOperand(0);
8587     OtherOpT = TI->getOperand(1);
8588     OtherOpF = FI->getOperand(0);
8589     MatchIsOpZero = true;
8590   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8591     MatchOp  = TI->getOperand(1);
8592     OtherOpT = TI->getOperand(0);
8593     OtherOpF = FI->getOperand(1);
8594     MatchIsOpZero = true;
8595   } else {
8596     return 0;
8597   }
8598
8599   // If we reach here, they do have operations in common.
8600   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8601                                          OtherOpF, SI.getName()+".v");
8602   InsertNewInstBefore(NewSI, SI);
8603
8604   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8605     if (MatchIsOpZero)
8606       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8607     else
8608       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8609   }
8610   assert(0 && "Shouldn't get here");
8611   return 0;
8612 }
8613
8614 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8615 /// ICmpInst as its first operand.
8616 ///
8617 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8618                                                    ICmpInst *ICI) {
8619   bool Changed = false;
8620   ICmpInst::Predicate Pred = ICI->getPredicate();
8621   Value *CmpLHS = ICI->getOperand(0);
8622   Value *CmpRHS = ICI->getOperand(1);
8623   Value *TrueVal = SI.getTrueValue();
8624   Value *FalseVal = SI.getFalseValue();
8625
8626   // Check cases where the comparison is with a constant that
8627   // can be adjusted to fit the min/max idiom. We may edit ICI in
8628   // place here, so make sure the select is the only user.
8629   if (ICI->hasOneUse())
8630     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8631       switch (Pred) {
8632       default: break;
8633       case ICmpInst::ICMP_ULT:
8634       case ICmpInst::ICMP_SLT: {
8635         // X < MIN ? T : F  -->  F
8636         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8637           return ReplaceInstUsesWith(SI, FalseVal);
8638         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8639         Constant *AdjustedRHS = SubOne(CI);
8640         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8641             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8642           Pred = ICmpInst::getSwappedPredicate(Pred);
8643           CmpRHS = AdjustedRHS;
8644           std::swap(FalseVal, TrueVal);
8645           ICI->setPredicate(Pred);
8646           ICI->setOperand(1, CmpRHS);
8647           SI.setOperand(1, TrueVal);
8648           SI.setOperand(2, FalseVal);
8649           Changed = true;
8650         }
8651         break;
8652       }
8653       case ICmpInst::ICMP_UGT:
8654       case ICmpInst::ICMP_SGT: {
8655         // X > MAX ? T : F  -->  F
8656         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8657           return ReplaceInstUsesWith(SI, FalseVal);
8658         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8659         Constant *AdjustedRHS = AddOne(CI);
8660         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8661             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8662           Pred = ICmpInst::getSwappedPredicate(Pred);
8663           CmpRHS = AdjustedRHS;
8664           std::swap(FalseVal, TrueVal);
8665           ICI->setPredicate(Pred);
8666           ICI->setOperand(1, CmpRHS);
8667           SI.setOperand(1, TrueVal);
8668           SI.setOperand(2, FalseVal);
8669           Changed = true;
8670         }
8671         break;
8672       }
8673       }
8674
8675       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8676       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8677       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8678       if (match(TrueVal, m_ConstantInt(-1)) &&
8679           match(FalseVal, m_ConstantInt(0)))
8680         Pred = ICI->getPredicate();
8681       else if (match(TrueVal, m_ConstantInt(0)) &&
8682                match(FalseVal, m_ConstantInt(-1)))
8683         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8684       
8685       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8686         // If we are just checking for a icmp eq of a single bit and zext'ing it
8687         // to an integer, then shift the bit to the appropriate place and then
8688         // cast to integer to avoid the comparison.
8689         const APInt &Op1CV = CI->getValue();
8690     
8691         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8692         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8693         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8694             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8695           Value *In = ICI->getOperand(0);
8696           Value *Sh = ConstantInt::get(In->getType(),
8697                                        In->getType()->getPrimitiveSizeInBits()-1);
8698           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8699                                                           In->getName()+".lobit"),
8700                                    *ICI);
8701           if (In->getType() != SI.getType())
8702             In = CastInst::CreateIntegerCast(In, SI.getType(),
8703                                              true/*SExt*/, "tmp", ICI);
8704     
8705           if (Pred == ICmpInst::ICMP_SGT)
8706             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8707                                        In->getName()+".not"), *ICI);
8708     
8709           return ReplaceInstUsesWith(SI, In);
8710         }
8711       }
8712     }
8713
8714   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8715     // Transform (X == Y) ? X : Y  -> Y
8716     if (Pred == ICmpInst::ICMP_EQ)
8717       return ReplaceInstUsesWith(SI, FalseVal);
8718     // Transform (X != Y) ? X : Y  -> X
8719     if (Pred == ICmpInst::ICMP_NE)
8720       return ReplaceInstUsesWith(SI, TrueVal);
8721     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8722
8723   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8724     // Transform (X == Y) ? Y : X  -> X
8725     if (Pred == ICmpInst::ICMP_EQ)
8726       return ReplaceInstUsesWith(SI, FalseVal);
8727     // Transform (X != Y) ? Y : X  -> Y
8728     if (Pred == ICmpInst::ICMP_NE)
8729       return ReplaceInstUsesWith(SI, TrueVal);
8730     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8731   }
8732
8733   /// NOTE: if we wanted to, this is where to detect integer ABS
8734
8735   return Changed ? &SI : 0;
8736 }
8737
8738 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8739   Value *CondVal = SI.getCondition();
8740   Value *TrueVal = SI.getTrueValue();
8741   Value *FalseVal = SI.getFalseValue();
8742
8743   // select true, X, Y  -> X
8744   // select false, X, Y -> Y
8745   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8746     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8747
8748   // select C, X, X -> X
8749   if (TrueVal == FalseVal)
8750     return ReplaceInstUsesWith(SI, TrueVal);
8751
8752   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8753     return ReplaceInstUsesWith(SI, FalseVal);
8754   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8755     return ReplaceInstUsesWith(SI, TrueVal);
8756   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8757     if (isa<Constant>(TrueVal))
8758       return ReplaceInstUsesWith(SI, TrueVal);
8759     else
8760       return ReplaceInstUsesWith(SI, FalseVal);
8761   }
8762
8763   if (SI.getType() == Type::Int1Ty) {
8764     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8765       if (C->getZExtValue()) {
8766         // Change: A = select B, true, C --> A = or B, C
8767         return BinaryOperator::CreateOr(CondVal, FalseVal);
8768       } else {
8769         // Change: A = select B, false, C --> A = and !B, C
8770         Value *NotCond =
8771           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8772                                              "not."+CondVal->getName()), SI);
8773         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8774       }
8775     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8776       if (C->getZExtValue() == false) {
8777         // Change: A = select B, C, false --> A = and B, C
8778         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8779       } else {
8780         // Change: A = select B, C, true --> A = or !B, C
8781         Value *NotCond =
8782           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8783                                              "not."+CondVal->getName()), SI);
8784         return BinaryOperator::CreateOr(NotCond, TrueVal);
8785       }
8786     }
8787     
8788     // select a, b, a  -> a&b
8789     // select a, a, b  -> a|b
8790     if (CondVal == TrueVal)
8791       return BinaryOperator::CreateOr(CondVal, FalseVal);
8792     else if (CondVal == FalseVal)
8793       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8794   }
8795
8796   // Selecting between two integer constants?
8797   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8798     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8799       // select C, 1, 0 -> zext C to int
8800       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8801         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8802       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8803         // select C, 0, 1 -> zext !C to int
8804         Value *NotCond =
8805           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8806                                                "not."+CondVal->getName()), SI);
8807         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8808       }
8809
8810       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8811
8812         // (x <s 0) ? -1 : 0 -> ashr x, 31
8813         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8814           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8815             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8816               // The comparison constant and the result are not neccessarily the
8817               // same width. Make an all-ones value by inserting a AShr.
8818               Value *X = IC->getOperand(0);
8819               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8820               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8821               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8822                                                         ShAmt, "ones");
8823               InsertNewInstBefore(SRA, SI);
8824
8825               // Then cast to the appropriate width.
8826               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8827             }
8828           }
8829
8830
8831         // If one of the constants is zero (we know they can't both be) and we
8832         // have an icmp instruction with zero, and we have an 'and' with the
8833         // non-constant value, eliminate this whole mess.  This corresponds to
8834         // cases like this: ((X & 27) ? 27 : 0)
8835         if (TrueValC->isZero() || FalseValC->isZero())
8836           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8837               cast<Constant>(IC->getOperand(1))->isNullValue())
8838             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8839               if (ICA->getOpcode() == Instruction::And &&
8840                   isa<ConstantInt>(ICA->getOperand(1)) &&
8841                   (ICA->getOperand(1) == TrueValC ||
8842                    ICA->getOperand(1) == FalseValC) &&
8843                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8844                 // Okay, now we know that everything is set up, we just don't
8845                 // know whether we have a icmp_ne or icmp_eq and whether the 
8846                 // true or false val is the zero.
8847                 bool ShouldNotVal = !TrueValC->isZero();
8848                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8849                 Value *V = ICA;
8850                 if (ShouldNotVal)
8851                   V = InsertNewInstBefore(BinaryOperator::Create(
8852                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8853                 return ReplaceInstUsesWith(SI, V);
8854               }
8855       }
8856     }
8857
8858   // See if we are selecting two values based on a comparison of the two values.
8859   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8860     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8861       // Transform (X == Y) ? X : Y  -> Y
8862       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8863         // This is not safe in general for floating point:  
8864         // consider X== -0, Y== +0.
8865         // It becomes safe if either operand is a nonzero constant.
8866         ConstantFP *CFPt, *CFPf;
8867         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8868               !CFPt->getValueAPF().isZero()) ||
8869             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8870              !CFPf->getValueAPF().isZero()))
8871         return ReplaceInstUsesWith(SI, FalseVal);
8872       }
8873       // Transform (X != Y) ? X : Y  -> X
8874       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8875         return ReplaceInstUsesWith(SI, TrueVal);
8876       // NOTE: if we wanted to, this is where to detect MIN/MAX
8877
8878     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8879       // Transform (X == Y) ? Y : X  -> X
8880       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8881         // This is not safe in general for floating point:  
8882         // consider X== -0, Y== +0.
8883         // It becomes safe if either operand is a nonzero constant.
8884         ConstantFP *CFPt, *CFPf;
8885         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8886               !CFPt->getValueAPF().isZero()) ||
8887             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8888              !CFPf->getValueAPF().isZero()))
8889           return ReplaceInstUsesWith(SI, FalseVal);
8890       }
8891       // Transform (X != Y) ? Y : X  -> Y
8892       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8893         return ReplaceInstUsesWith(SI, TrueVal);
8894       // NOTE: if we wanted to, this is where to detect MIN/MAX
8895     }
8896     // NOTE: if we wanted to, this is where to detect ABS
8897   }
8898
8899   // See if we are selecting two values based on a comparison of the two values.
8900   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8901     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8902       return Result;
8903
8904   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8905     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8906       if (TI->hasOneUse() && FI->hasOneUse()) {
8907         Instruction *AddOp = 0, *SubOp = 0;
8908
8909         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8910         if (TI->getOpcode() == FI->getOpcode())
8911           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8912             return IV;
8913
8914         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8915         // even legal for FP.
8916         if (TI->getOpcode() == Instruction::Sub &&
8917             FI->getOpcode() == Instruction::Add) {
8918           AddOp = FI; SubOp = TI;
8919         } else if (FI->getOpcode() == Instruction::Sub &&
8920                    TI->getOpcode() == Instruction::Add) {
8921           AddOp = TI; SubOp = FI;
8922         }
8923
8924         if (AddOp) {
8925           Value *OtherAddOp = 0;
8926           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8927             OtherAddOp = AddOp->getOperand(1);
8928           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8929             OtherAddOp = AddOp->getOperand(0);
8930           }
8931
8932           if (OtherAddOp) {
8933             // So at this point we know we have (Y -> OtherAddOp):
8934             //        select C, (add X, Y), (sub X, Z)
8935             Value *NegVal;  // Compute -Z
8936             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8937               NegVal = ConstantExpr::getNeg(C);
8938             } else {
8939               NegVal = InsertNewInstBefore(
8940                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8941             }
8942
8943             Value *NewTrueOp = OtherAddOp;
8944             Value *NewFalseOp = NegVal;
8945             if (AddOp != TI)
8946               std::swap(NewTrueOp, NewFalseOp);
8947             Instruction *NewSel =
8948               SelectInst::Create(CondVal, NewTrueOp,
8949                                  NewFalseOp, SI.getName() + ".p");
8950
8951             NewSel = InsertNewInstBefore(NewSel, SI);
8952             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8953           }
8954         }
8955       }
8956
8957   // See if we can fold the select into one of our operands.
8958   if (SI.getType()->isInteger()) {
8959     // See the comment above GetSelectFoldableOperands for a description of the
8960     // transformation we are doing here.
8961     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8962       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8963           !isa<Constant>(FalseVal))
8964         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8965           unsigned OpToFold = 0;
8966           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8967             OpToFold = 1;
8968           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8969             OpToFold = 2;
8970           }
8971
8972           if (OpToFold) {
8973             Constant *C = GetSelectFoldableConstant(TVI);
8974             Instruction *NewSel =
8975               SelectInst::Create(SI.getCondition(),
8976                                  TVI->getOperand(2-OpToFold), C);
8977             InsertNewInstBefore(NewSel, SI);
8978             NewSel->takeName(TVI);
8979             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8980               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8981             else {
8982               assert(0 && "Unknown instruction!!");
8983             }
8984           }
8985         }
8986
8987     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8988       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8989           !isa<Constant>(TrueVal))
8990         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8991           unsigned OpToFold = 0;
8992           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8993             OpToFold = 1;
8994           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8995             OpToFold = 2;
8996           }
8997
8998           if (OpToFold) {
8999             Constant *C = GetSelectFoldableConstant(FVI);
9000             Instruction *NewSel =
9001               SelectInst::Create(SI.getCondition(), C,
9002                                  FVI->getOperand(2-OpToFold));
9003             InsertNewInstBefore(NewSel, SI);
9004             NewSel->takeName(FVI);
9005             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9006               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9007             else
9008               assert(0 && "Unknown instruction!!");
9009           }
9010         }
9011   }
9012
9013   if (BinaryOperator::isNot(CondVal)) {
9014     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9015     SI.setOperand(1, FalseVal);
9016     SI.setOperand(2, TrueVal);
9017     return &SI;
9018   }
9019
9020   return 0;
9021 }
9022
9023 /// EnforceKnownAlignment - If the specified pointer points to an object that
9024 /// we control, modify the object's alignment to PrefAlign. This isn't
9025 /// often possible though. If alignment is important, a more reliable approach
9026 /// is to simply align all global variables and allocation instructions to
9027 /// their preferred alignment from the beginning.
9028 ///
9029 static unsigned EnforceKnownAlignment(Value *V,
9030                                       unsigned Align, unsigned PrefAlign) {
9031
9032   User *U = dyn_cast<User>(V);
9033   if (!U) return Align;
9034
9035   switch (getOpcode(U)) {
9036   default: break;
9037   case Instruction::BitCast:
9038     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9039   case Instruction::GetElementPtr: {
9040     // If all indexes are zero, it is just the alignment of the base pointer.
9041     bool AllZeroOperands = true;
9042     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9043       if (!isa<Constant>(*i) ||
9044           !cast<Constant>(*i)->isNullValue()) {
9045         AllZeroOperands = false;
9046         break;
9047       }
9048
9049     if (AllZeroOperands) {
9050       // Treat this like a bitcast.
9051       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9052     }
9053     break;
9054   }
9055   }
9056
9057   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9058     // If there is a large requested alignment and we can, bump up the alignment
9059     // of the global.
9060     if (!GV->isDeclaration()) {
9061       GV->setAlignment(PrefAlign);
9062       Align = PrefAlign;
9063     }
9064   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9065     // If there is a requested alignment and if this is an alloca, round up.  We
9066     // don't do this for malloc, because some systems can't respect the request.
9067     if (isa<AllocaInst>(AI)) {
9068       AI->setAlignment(PrefAlign);
9069       Align = PrefAlign;
9070     }
9071   }
9072
9073   return Align;
9074 }
9075
9076 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9077 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9078 /// and it is more than the alignment of the ultimate object, see if we can
9079 /// increase the alignment of the ultimate object, making this check succeed.
9080 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9081                                                   unsigned PrefAlign) {
9082   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9083                       sizeof(PrefAlign) * CHAR_BIT;
9084   APInt Mask = APInt::getAllOnesValue(BitWidth);
9085   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9086   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9087   unsigned TrailZ = KnownZero.countTrailingOnes();
9088   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9089
9090   if (PrefAlign > Align)
9091     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9092   
9093     // We don't need to make any adjustment.
9094   return Align;
9095 }
9096
9097 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9098   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9099   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9100   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9101   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9102
9103   if (CopyAlign < MinAlign) {
9104     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9105     return MI;
9106   }
9107   
9108   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9109   // load/store.
9110   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9111   if (MemOpLength == 0) return 0;
9112   
9113   // Source and destination pointer types are always "i8*" for intrinsic.  See
9114   // if the size is something we can handle with a single primitive load/store.
9115   // A single load+store correctly handles overlapping memory in the memmove
9116   // case.
9117   unsigned Size = MemOpLength->getZExtValue();
9118   if (Size == 0) return MI;  // Delete this mem transfer.
9119   
9120   if (Size > 8 || (Size&(Size-1)))
9121     return 0;  // If not 1/2/4/8 bytes, exit.
9122   
9123   // Use an integer load+store unless we can find something better.
9124   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9125   
9126   // Memcpy forces the use of i8* for the source and destination.  That means
9127   // that if you're using memcpy to move one double around, you'll get a cast
9128   // from double* to i8*.  We'd much rather use a double load+store rather than
9129   // an i64 load+store, here because this improves the odds that the source or
9130   // dest address will be promotable.  See if we can find a better type than the
9131   // integer datatype.
9132   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9133     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9134     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9135       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9136       // down through these levels if so.
9137       while (!SrcETy->isSingleValueType()) {
9138         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9139           if (STy->getNumElements() == 1)
9140             SrcETy = STy->getElementType(0);
9141           else
9142             break;
9143         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9144           if (ATy->getNumElements() == 1)
9145             SrcETy = ATy->getElementType();
9146           else
9147             break;
9148         } else
9149           break;
9150       }
9151       
9152       if (SrcETy->isSingleValueType())
9153         NewPtrTy = PointerType::getUnqual(SrcETy);
9154     }
9155   }
9156   
9157   
9158   // If the memcpy/memmove provides better alignment info than we can
9159   // infer, use it.
9160   SrcAlign = std::max(SrcAlign, CopyAlign);
9161   DstAlign = std::max(DstAlign, CopyAlign);
9162   
9163   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9164   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9165   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9166   InsertNewInstBefore(L, *MI);
9167   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9168
9169   // Set the size of the copy to 0, it will be deleted on the next iteration.
9170   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9171   return MI;
9172 }
9173
9174 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9175   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9176   if (MI->getAlignment()->getZExtValue() < Alignment) {
9177     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9178     return MI;
9179   }
9180   
9181   // Extract the length and alignment and fill if they are constant.
9182   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9183   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9184   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9185     return 0;
9186   uint64_t Len = LenC->getZExtValue();
9187   Alignment = MI->getAlignment()->getZExtValue();
9188   
9189   // If the length is zero, this is a no-op
9190   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9191   
9192   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9193   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9194     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9195     
9196     Value *Dest = MI->getDest();
9197     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9198
9199     // Alignment 0 is identity for alignment 1 for memset, but not store.
9200     if (Alignment == 0) Alignment = 1;
9201     
9202     // Extract the fill value and store.
9203     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9204     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9205                                       Alignment), *MI);
9206     
9207     // Set the size of the copy to 0, it will be deleted on the next iteration.
9208     MI->setLength(Constant::getNullValue(LenC->getType()));
9209     return MI;
9210   }
9211
9212   return 0;
9213 }
9214
9215
9216 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9217 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9218 /// the heavy lifting.
9219 ///
9220 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9221   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9222   if (!II) return visitCallSite(&CI);
9223   
9224   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9225   // visitCallSite.
9226   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9227     bool Changed = false;
9228
9229     // memmove/cpy/set of zero bytes is a noop.
9230     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9231       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9232
9233       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9234         if (CI->getZExtValue() == 1) {
9235           // Replace the instruction with just byte operations.  We would
9236           // transform other cases to loads/stores, but we don't know if
9237           // alignment is sufficient.
9238         }
9239     }
9240
9241     // If we have a memmove and the source operation is a constant global,
9242     // then the source and dest pointers can't alias, so we can change this
9243     // into a call to memcpy.
9244     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9245       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9246         if (GVSrc->isConstant()) {
9247           Module *M = CI.getParent()->getParent()->getParent();
9248           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9249           const Type *Tys[1];
9250           Tys[0] = CI.getOperand(3)->getType();
9251           CI.setOperand(0, 
9252                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9253           Changed = true;
9254         }
9255
9256       // memmove(x,x,size) -> noop.
9257       if (MMI->getSource() == MMI->getDest())
9258         return EraseInstFromFunction(CI);
9259     }
9260
9261     // If we can determine a pointer alignment that is bigger than currently
9262     // set, update the alignment.
9263     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9264       if (Instruction *I = SimplifyMemTransfer(MI))
9265         return I;
9266     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9267       if (Instruction *I = SimplifyMemSet(MSI))
9268         return I;
9269     }
9270           
9271     if (Changed) return II;
9272   }
9273   
9274   switch (II->getIntrinsicID()) {
9275   default: break;
9276   case Intrinsic::bswap:
9277     // bswap(bswap(x)) -> x
9278     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9279       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9280         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9281     break;
9282   case Intrinsic::ppc_altivec_lvx:
9283   case Intrinsic::ppc_altivec_lvxl:
9284   case Intrinsic::x86_sse_loadu_ps:
9285   case Intrinsic::x86_sse2_loadu_pd:
9286   case Intrinsic::x86_sse2_loadu_dq:
9287     // Turn PPC lvx     -> load if the pointer is known aligned.
9288     // Turn X86 loadups -> load if the pointer is known aligned.
9289     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9290       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9291                                        PointerType::getUnqual(II->getType()),
9292                                        CI);
9293       return new LoadInst(Ptr);
9294     }
9295     break;
9296   case Intrinsic::ppc_altivec_stvx:
9297   case Intrinsic::ppc_altivec_stvxl:
9298     // Turn stvx -> store if the pointer is known aligned.
9299     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9300       const Type *OpPtrTy = 
9301         PointerType::getUnqual(II->getOperand(1)->getType());
9302       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9303       return new StoreInst(II->getOperand(1), Ptr);
9304     }
9305     break;
9306   case Intrinsic::x86_sse_storeu_ps:
9307   case Intrinsic::x86_sse2_storeu_pd:
9308   case Intrinsic::x86_sse2_storeu_dq:
9309     // Turn X86 storeu -> store if the pointer is known aligned.
9310     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9311       const Type *OpPtrTy = 
9312         PointerType::getUnqual(II->getOperand(2)->getType());
9313       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9314       return new StoreInst(II->getOperand(2), Ptr);
9315     }
9316     break;
9317     
9318   case Intrinsic::x86_sse_cvttss2si: {
9319     // These intrinsics only demands the 0th element of its input vector.  If
9320     // we can simplify the input based on that, do so now.
9321     uint64_t UndefElts;
9322     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9323                                               UndefElts)) {
9324       II->setOperand(1, V);
9325       return II;
9326     }
9327     break;
9328   }
9329     
9330   case Intrinsic::ppc_altivec_vperm:
9331     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9332     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9333       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9334       
9335       // Check that all of the elements are integer constants or undefs.
9336       bool AllEltsOk = true;
9337       for (unsigned i = 0; i != 16; ++i) {
9338         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9339             !isa<UndefValue>(Mask->getOperand(i))) {
9340           AllEltsOk = false;
9341           break;
9342         }
9343       }
9344       
9345       if (AllEltsOk) {
9346         // Cast the input vectors to byte vectors.
9347         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9348         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9349         Value *Result = UndefValue::get(Op0->getType());
9350         
9351         // Only extract each element once.
9352         Value *ExtractedElts[32];
9353         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9354         
9355         for (unsigned i = 0; i != 16; ++i) {
9356           if (isa<UndefValue>(Mask->getOperand(i)))
9357             continue;
9358           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9359           Idx &= 31;  // Match the hardware behavior.
9360           
9361           if (ExtractedElts[Idx] == 0) {
9362             Instruction *Elt = 
9363               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9364             InsertNewInstBefore(Elt, CI);
9365             ExtractedElts[Idx] = Elt;
9366           }
9367         
9368           // Insert this value into the result vector.
9369           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9370                                              i, "tmp");
9371           InsertNewInstBefore(cast<Instruction>(Result), CI);
9372         }
9373         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9374       }
9375     }
9376     break;
9377
9378   case Intrinsic::stackrestore: {
9379     // If the save is right next to the restore, remove the restore.  This can
9380     // happen when variable allocas are DCE'd.
9381     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9382       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9383         BasicBlock::iterator BI = SS;
9384         if (&*++BI == II)
9385           return EraseInstFromFunction(CI);
9386       }
9387     }
9388     
9389     // Scan down this block to see if there is another stack restore in the
9390     // same block without an intervening call/alloca.
9391     BasicBlock::iterator BI = II;
9392     TerminatorInst *TI = II->getParent()->getTerminator();
9393     bool CannotRemove = false;
9394     for (++BI; &*BI != TI; ++BI) {
9395       if (isa<AllocaInst>(BI)) {
9396         CannotRemove = true;
9397         break;
9398       }
9399       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9400         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9401           // If there is a stackrestore below this one, remove this one.
9402           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9403             return EraseInstFromFunction(CI);
9404           // Otherwise, ignore the intrinsic.
9405         } else {
9406           // If we found a non-intrinsic call, we can't remove the stack
9407           // restore.
9408           CannotRemove = true;
9409           break;
9410         }
9411       }
9412     }
9413     
9414     // If the stack restore is in a return/unwind block and if there are no
9415     // allocas or calls between the restore and the return, nuke the restore.
9416     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9417       return EraseInstFromFunction(CI);
9418     break;
9419   }
9420   }
9421
9422   return visitCallSite(II);
9423 }
9424
9425 // InvokeInst simplification
9426 //
9427 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9428   return visitCallSite(&II);
9429 }
9430
9431 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9432 /// passed through the varargs area, we can eliminate the use of the cast.
9433 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9434                                          const CastInst * const CI,
9435                                          const TargetData * const TD,
9436                                          const int ix) {
9437   if (!CI->isLosslessCast())
9438     return false;
9439
9440   // The size of ByVal arguments is derived from the type, so we
9441   // can't change to a type with a different size.  If the size were
9442   // passed explicitly we could avoid this check.
9443   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9444     return true;
9445
9446   const Type* SrcTy = 
9447             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9448   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9449   if (!SrcTy->isSized() || !DstTy->isSized())
9450     return false;
9451   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9452     return false;
9453   return true;
9454 }
9455
9456 // visitCallSite - Improvements for call and invoke instructions.
9457 //
9458 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9459   bool Changed = false;
9460
9461   // If the callee is a constexpr cast of a function, attempt to move the cast
9462   // to the arguments of the call/invoke.
9463   if (transformConstExprCastCall(CS)) return 0;
9464
9465   Value *Callee = CS.getCalledValue();
9466
9467   if (Function *CalleeF = dyn_cast<Function>(Callee))
9468     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9469       Instruction *OldCall = CS.getInstruction();
9470       // If the call and callee calling conventions don't match, this call must
9471       // be unreachable, as the call is undefined.
9472       new StoreInst(ConstantInt::getTrue(),
9473                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9474                                     OldCall);
9475       if (!OldCall->use_empty())
9476         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9477       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9478         return EraseInstFromFunction(*OldCall);
9479       return 0;
9480     }
9481
9482   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9483     // This instruction is not reachable, just remove it.  We insert a store to
9484     // undef so that we know that this code is not reachable, despite the fact
9485     // that we can't modify the CFG here.
9486     new StoreInst(ConstantInt::getTrue(),
9487                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9488                   CS.getInstruction());
9489
9490     if (!CS.getInstruction()->use_empty())
9491       CS.getInstruction()->
9492         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9493
9494     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9495       // Don't break the CFG, insert a dummy cond branch.
9496       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9497                          ConstantInt::getTrue(), II);
9498     }
9499     return EraseInstFromFunction(*CS.getInstruction());
9500   }
9501
9502   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9503     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9504       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9505         return transformCallThroughTrampoline(CS);
9506
9507   const PointerType *PTy = cast<PointerType>(Callee->getType());
9508   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9509   if (FTy->isVarArg()) {
9510     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9511     // See if we can optimize any arguments passed through the varargs area of
9512     // the call.
9513     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9514            E = CS.arg_end(); I != E; ++I, ++ix) {
9515       CastInst *CI = dyn_cast<CastInst>(*I);
9516       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9517         *I = CI->getOperand(0);
9518         Changed = true;
9519       }
9520     }
9521   }
9522
9523   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9524     // Inline asm calls cannot throw - mark them 'nounwind'.
9525     CS.setDoesNotThrow();
9526     Changed = true;
9527   }
9528
9529   return Changed ? CS.getInstruction() : 0;
9530 }
9531
9532 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9533 // attempt to move the cast to the arguments of the call/invoke.
9534 //
9535 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9536   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9537   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9538   if (CE->getOpcode() != Instruction::BitCast || 
9539       !isa<Function>(CE->getOperand(0)))
9540     return false;
9541   Function *Callee = cast<Function>(CE->getOperand(0));
9542   Instruction *Caller = CS.getInstruction();
9543   const AttrListPtr &CallerPAL = CS.getAttributes();
9544
9545   // Okay, this is a cast from a function to a different type.  Unless doing so
9546   // would cause a type conversion of one of our arguments, change this call to
9547   // be a direct call with arguments casted to the appropriate types.
9548   //
9549   const FunctionType *FT = Callee->getFunctionType();
9550   const Type *OldRetTy = Caller->getType();
9551   const Type *NewRetTy = FT->getReturnType();
9552
9553   if (isa<StructType>(NewRetTy))
9554     return false; // TODO: Handle multiple return values.
9555
9556   // Check to see if we are changing the return type...
9557   if (OldRetTy != NewRetTy) {
9558     if (Callee->isDeclaration() &&
9559         // Conversion is ok if changing from one pointer type to another or from
9560         // a pointer to an integer of the same size.
9561         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9562           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9563       return false;   // Cannot transform this return value.
9564
9565     if (!Caller->use_empty() &&
9566         // void -> non-void is handled specially
9567         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9568       return false;   // Cannot transform this return value.
9569
9570     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9571       Attributes RAttrs = CallerPAL.getRetAttributes();
9572       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9573         return false;   // Attribute not compatible with transformed value.
9574     }
9575
9576     // If the callsite is an invoke instruction, and the return value is used by
9577     // a PHI node in a successor, we cannot change the return type of the call
9578     // because there is no place to put the cast instruction (without breaking
9579     // the critical edge).  Bail out in this case.
9580     if (!Caller->use_empty())
9581       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9582         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9583              UI != E; ++UI)
9584           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9585             if (PN->getParent() == II->getNormalDest() ||
9586                 PN->getParent() == II->getUnwindDest())
9587               return false;
9588   }
9589
9590   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9591   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9592
9593   CallSite::arg_iterator AI = CS.arg_begin();
9594   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9595     const Type *ParamTy = FT->getParamType(i);
9596     const Type *ActTy = (*AI)->getType();
9597
9598     if (!CastInst::isCastable(ActTy, ParamTy))
9599       return false;   // Cannot transform this parameter value.
9600
9601     if (CallerPAL.getParamAttributes(i + 1) 
9602         & Attribute::typeIncompatible(ParamTy))
9603       return false;   // Attribute not compatible with transformed value.
9604
9605     // Converting from one pointer type to another or between a pointer and an
9606     // integer of the same size is safe even if we do not have a body.
9607     bool isConvertible = ActTy == ParamTy ||
9608       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9609        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9610     if (Callee->isDeclaration() && !isConvertible) return false;
9611   }
9612
9613   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9614       Callee->isDeclaration())
9615     return false;   // Do not delete arguments unless we have a function body.
9616
9617   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9618       !CallerPAL.isEmpty())
9619     // In this case we have more arguments than the new function type, but we
9620     // won't be dropping them.  Check that these extra arguments have attributes
9621     // that are compatible with being a vararg call argument.
9622     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9623       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9624         break;
9625       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9626       if (PAttrs & Attribute::VarArgsIncompatible)
9627         return false;
9628     }
9629
9630   // Okay, we decided that this is a safe thing to do: go ahead and start
9631   // inserting cast instructions as necessary...
9632   std::vector<Value*> Args;
9633   Args.reserve(NumActualArgs);
9634   SmallVector<AttributeWithIndex, 8> attrVec;
9635   attrVec.reserve(NumCommonArgs);
9636
9637   // Get any return attributes.
9638   Attributes RAttrs = CallerPAL.getRetAttributes();
9639
9640   // If the return value is not being used, the type may not be compatible
9641   // with the existing attributes.  Wipe out any problematic attributes.
9642   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9643
9644   // Add the new return attributes.
9645   if (RAttrs)
9646     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9647
9648   AI = CS.arg_begin();
9649   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9650     const Type *ParamTy = FT->getParamType(i);
9651     if ((*AI)->getType() == ParamTy) {
9652       Args.push_back(*AI);
9653     } else {
9654       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9655           false, ParamTy, false);
9656       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9657       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9658     }
9659
9660     // Add any parameter attributes.
9661     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9662       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9663   }
9664
9665   // If the function takes more arguments than the call was taking, add them
9666   // now...
9667   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9668     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9669
9670   // If we are removing arguments to the function, emit an obnoxious warning...
9671   if (FT->getNumParams() < NumActualArgs) {
9672     if (!FT->isVarArg()) {
9673       cerr << "WARNING: While resolving call to function '"
9674            << Callee->getName() << "' arguments were dropped!\n";
9675     } else {
9676       // Add all of the arguments in their promoted form to the arg list...
9677       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9678         const Type *PTy = getPromotedType((*AI)->getType());
9679         if (PTy != (*AI)->getType()) {
9680           // Must promote to pass through va_arg area!
9681           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9682                                                                 PTy, false);
9683           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9684           InsertNewInstBefore(Cast, *Caller);
9685           Args.push_back(Cast);
9686         } else {
9687           Args.push_back(*AI);
9688         }
9689
9690         // Add any parameter attributes.
9691         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9692           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9693       }
9694     }
9695   }
9696
9697   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9698     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9699
9700   if (NewRetTy == Type::VoidTy)
9701     Caller->setName("");   // Void type should not have a name.
9702
9703   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9704
9705   Instruction *NC;
9706   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9707     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9708                             Args.begin(), Args.end(),
9709                             Caller->getName(), Caller);
9710     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9711     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9712   } else {
9713     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9714                           Caller->getName(), Caller);
9715     CallInst *CI = cast<CallInst>(Caller);
9716     if (CI->isTailCall())
9717       cast<CallInst>(NC)->setTailCall();
9718     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9719     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9720   }
9721
9722   // Insert a cast of the return type as necessary.
9723   Value *NV = NC;
9724   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9725     if (NV->getType() != Type::VoidTy) {
9726       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9727                                                             OldRetTy, false);
9728       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9729
9730       // If this is an invoke instruction, we should insert it after the first
9731       // non-phi, instruction in the normal successor block.
9732       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9733         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9734         InsertNewInstBefore(NC, *I);
9735       } else {
9736         // Otherwise, it's a call, just insert cast right after the call instr
9737         InsertNewInstBefore(NC, *Caller);
9738       }
9739       AddUsersToWorkList(*Caller);
9740     } else {
9741       NV = UndefValue::get(Caller->getType());
9742     }
9743   }
9744
9745   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9746     Caller->replaceAllUsesWith(NV);
9747   Caller->eraseFromParent();
9748   RemoveFromWorkList(Caller);
9749   return true;
9750 }
9751
9752 // transformCallThroughTrampoline - Turn a call to a function created by the
9753 // init_trampoline intrinsic into a direct call to the underlying function.
9754 //
9755 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9756   Value *Callee = CS.getCalledValue();
9757   const PointerType *PTy = cast<PointerType>(Callee->getType());
9758   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9759   const AttrListPtr &Attrs = CS.getAttributes();
9760
9761   // If the call already has the 'nest' attribute somewhere then give up -
9762   // otherwise 'nest' would occur twice after splicing in the chain.
9763   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9764     return 0;
9765
9766   IntrinsicInst *Tramp =
9767     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9768
9769   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9770   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9771   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9772
9773   const AttrListPtr &NestAttrs = NestF->getAttributes();
9774   if (!NestAttrs.isEmpty()) {
9775     unsigned NestIdx = 1;
9776     const Type *NestTy = 0;
9777     Attributes NestAttr = Attribute::None;
9778
9779     // Look for a parameter marked with the 'nest' attribute.
9780     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9781          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9782       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9783         // Record the parameter type and any other attributes.
9784         NestTy = *I;
9785         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9786         break;
9787       }
9788
9789     if (NestTy) {
9790       Instruction *Caller = CS.getInstruction();
9791       std::vector<Value*> NewArgs;
9792       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9793
9794       SmallVector<AttributeWithIndex, 8> NewAttrs;
9795       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9796
9797       // Insert the nest argument into the call argument list, which may
9798       // mean appending it.  Likewise for attributes.
9799
9800       // Add any result attributes.
9801       if (Attributes Attr = Attrs.getRetAttributes())
9802         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9803
9804       {
9805         unsigned Idx = 1;
9806         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9807         do {
9808           if (Idx == NestIdx) {
9809             // Add the chain argument and attributes.
9810             Value *NestVal = Tramp->getOperand(3);
9811             if (NestVal->getType() != NestTy)
9812               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9813             NewArgs.push_back(NestVal);
9814             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9815           }
9816
9817           if (I == E)
9818             break;
9819
9820           // Add the original argument and attributes.
9821           NewArgs.push_back(*I);
9822           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9823             NewAttrs.push_back
9824               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9825
9826           ++Idx, ++I;
9827         } while (1);
9828       }
9829
9830       // Add any function attributes.
9831       if (Attributes Attr = Attrs.getFnAttributes())
9832         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9833
9834       // The trampoline may have been bitcast to a bogus type (FTy).
9835       // Handle this by synthesizing a new function type, equal to FTy
9836       // with the chain parameter inserted.
9837
9838       std::vector<const Type*> NewTypes;
9839       NewTypes.reserve(FTy->getNumParams()+1);
9840
9841       // Insert the chain's type into the list of parameter types, which may
9842       // mean appending it.
9843       {
9844         unsigned Idx = 1;
9845         FunctionType::param_iterator I = FTy->param_begin(),
9846           E = FTy->param_end();
9847
9848         do {
9849           if (Idx == NestIdx)
9850             // Add the chain's type.
9851             NewTypes.push_back(NestTy);
9852
9853           if (I == E)
9854             break;
9855
9856           // Add the original type.
9857           NewTypes.push_back(*I);
9858
9859           ++Idx, ++I;
9860         } while (1);
9861       }
9862
9863       // Replace the trampoline call with a direct call.  Let the generic
9864       // code sort out any function type mismatches.
9865       FunctionType *NewFTy =
9866         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9867       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9868         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9869       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9870
9871       Instruction *NewCaller;
9872       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9873         NewCaller = InvokeInst::Create(NewCallee,
9874                                        II->getNormalDest(), II->getUnwindDest(),
9875                                        NewArgs.begin(), NewArgs.end(),
9876                                        Caller->getName(), Caller);
9877         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9878         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9879       } else {
9880         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9881                                      Caller->getName(), Caller);
9882         if (cast<CallInst>(Caller)->isTailCall())
9883           cast<CallInst>(NewCaller)->setTailCall();
9884         cast<CallInst>(NewCaller)->
9885           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9886         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9887       }
9888       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9889         Caller->replaceAllUsesWith(NewCaller);
9890       Caller->eraseFromParent();
9891       RemoveFromWorkList(Caller);
9892       return 0;
9893     }
9894   }
9895
9896   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9897   // parameter, there is no need to adjust the argument list.  Let the generic
9898   // code sort out any function type mismatches.
9899   Constant *NewCallee =
9900     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9901   CS.setCalledFunction(NewCallee);
9902   return CS.getInstruction();
9903 }
9904
9905 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9906 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9907 /// and a single binop.
9908 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9909   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9910   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9911          isa<CmpInst>(FirstInst));
9912   unsigned Opc = FirstInst->getOpcode();
9913   Value *LHSVal = FirstInst->getOperand(0);
9914   Value *RHSVal = FirstInst->getOperand(1);
9915     
9916   const Type *LHSType = LHSVal->getType();
9917   const Type *RHSType = RHSVal->getType();
9918   
9919   // Scan to see if all operands are the same opcode, all have one use, and all
9920   // kill their operands (i.e. the operands have one use).
9921   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9922     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9923     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9924         // Verify type of the LHS matches so we don't fold cmp's of different
9925         // types or GEP's with different index types.
9926         I->getOperand(0)->getType() != LHSType ||
9927         I->getOperand(1)->getType() != RHSType)
9928       return 0;
9929
9930     // If they are CmpInst instructions, check their predicates
9931     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9932       if (cast<CmpInst>(I)->getPredicate() !=
9933           cast<CmpInst>(FirstInst)->getPredicate())
9934         return 0;
9935     
9936     // Keep track of which operand needs a phi node.
9937     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9938     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9939   }
9940   
9941   // Otherwise, this is safe to transform, determine if it is profitable.
9942
9943   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9944   // Indexes are often folded into load/store instructions, so we don't want to
9945   // hide them behind a phi.
9946   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9947     return 0;
9948   
9949   Value *InLHS = FirstInst->getOperand(0);
9950   Value *InRHS = FirstInst->getOperand(1);
9951   PHINode *NewLHS = 0, *NewRHS = 0;
9952   if (LHSVal == 0) {
9953     NewLHS = PHINode::Create(LHSType,
9954                              FirstInst->getOperand(0)->getName() + ".pn");
9955     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9956     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9957     InsertNewInstBefore(NewLHS, PN);
9958     LHSVal = NewLHS;
9959   }
9960   
9961   if (RHSVal == 0) {
9962     NewRHS = PHINode::Create(RHSType,
9963                              FirstInst->getOperand(1)->getName() + ".pn");
9964     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9965     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9966     InsertNewInstBefore(NewRHS, PN);
9967     RHSVal = NewRHS;
9968   }
9969   
9970   // Add all operands to the new PHIs.
9971   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9972     if (NewLHS) {
9973       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9974       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9975     }
9976     if (NewRHS) {
9977       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9978       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9979     }
9980   }
9981     
9982   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9983     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9984   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9985     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9986                            RHSVal);
9987   else {
9988     assert(isa<GetElementPtrInst>(FirstInst));
9989     return GetElementPtrInst::Create(LHSVal, RHSVal);
9990   }
9991 }
9992
9993 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9994 /// of the block that defines it.  This means that it must be obvious the value
9995 /// of the load is not changed from the point of the load to the end of the
9996 /// block it is in.
9997 ///
9998 /// Finally, it is safe, but not profitable, to sink a load targetting a
9999 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10000 /// to a register.
10001 static bool isSafeToSinkLoad(LoadInst *L) {
10002   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10003   
10004   for (++BBI; BBI != E; ++BBI)
10005     if (BBI->mayWriteToMemory())
10006       return false;
10007   
10008   // Check for non-address taken alloca.  If not address-taken already, it isn't
10009   // profitable to do this xform.
10010   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10011     bool isAddressTaken = false;
10012     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10013          UI != E; ++UI) {
10014       if (isa<LoadInst>(UI)) continue;
10015       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10016         // If storing TO the alloca, then the address isn't taken.
10017         if (SI->getOperand(1) == AI) continue;
10018       }
10019       isAddressTaken = true;
10020       break;
10021     }
10022     
10023     if (!isAddressTaken)
10024       return false;
10025   }
10026   
10027   return true;
10028 }
10029
10030
10031 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10032 // operator and they all are only used by the PHI, PHI together their
10033 // inputs, and do the operation once, to the result of the PHI.
10034 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10035   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10036
10037   // Scan the instruction, looking for input operations that can be folded away.
10038   // If all input operands to the phi are the same instruction (e.g. a cast from
10039   // the same type or "+42") we can pull the operation through the PHI, reducing
10040   // code size and simplifying code.
10041   Constant *ConstantOp = 0;
10042   const Type *CastSrcTy = 0;
10043   bool isVolatile = false;
10044   if (isa<CastInst>(FirstInst)) {
10045     CastSrcTy = FirstInst->getOperand(0)->getType();
10046   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10047     // Can fold binop, compare or shift here if the RHS is a constant, 
10048     // otherwise call FoldPHIArgBinOpIntoPHI.
10049     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10050     if (ConstantOp == 0)
10051       return FoldPHIArgBinOpIntoPHI(PN);
10052   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10053     isVolatile = LI->isVolatile();
10054     // We can't sink the load if the loaded value could be modified between the
10055     // load and the PHI.
10056     if (LI->getParent() != PN.getIncomingBlock(0) ||
10057         !isSafeToSinkLoad(LI))
10058       return 0;
10059     
10060     // If the PHI is of volatile loads and the load block has multiple
10061     // successors, sinking it would remove a load of the volatile value from
10062     // the path through the other successor.
10063     if (isVolatile &&
10064         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10065       return 0;
10066     
10067   } else if (isa<GetElementPtrInst>(FirstInst)) {
10068     if (FirstInst->getNumOperands() == 2)
10069       return FoldPHIArgBinOpIntoPHI(PN);
10070     // Can't handle general GEPs yet.
10071     return 0;
10072   } else {
10073     return 0;  // Cannot fold this operation.
10074   }
10075
10076   // Check to see if all arguments are the same operation.
10077   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10078     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10079     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10080     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10081       return 0;
10082     if (CastSrcTy) {
10083       if (I->getOperand(0)->getType() != CastSrcTy)
10084         return 0;  // Cast operation must match.
10085     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10086       // We can't sink the load if the loaded value could be modified between 
10087       // the load and the PHI.
10088       if (LI->isVolatile() != isVolatile ||
10089           LI->getParent() != PN.getIncomingBlock(i) ||
10090           !isSafeToSinkLoad(LI))
10091         return 0;
10092       
10093       // If the PHI is of volatile loads and the load block has multiple
10094       // successors, sinking it would remove a load of the volatile value from
10095       // the path through the other successor.
10096       if (isVolatile &&
10097           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10098         return 0;
10099
10100       
10101     } else if (I->getOperand(1) != ConstantOp) {
10102       return 0;
10103     }
10104   }
10105
10106   // Okay, they are all the same operation.  Create a new PHI node of the
10107   // correct type, and PHI together all of the LHS's of the instructions.
10108   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10109                                    PN.getName()+".in");
10110   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10111
10112   Value *InVal = FirstInst->getOperand(0);
10113   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10114
10115   // Add all operands to the new PHI.
10116   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10117     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10118     if (NewInVal != InVal)
10119       InVal = 0;
10120     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10121   }
10122
10123   Value *PhiVal;
10124   if (InVal) {
10125     // The new PHI unions all of the same values together.  This is really
10126     // common, so we handle it intelligently here for compile-time speed.
10127     PhiVal = InVal;
10128     delete NewPN;
10129   } else {
10130     InsertNewInstBefore(NewPN, PN);
10131     PhiVal = NewPN;
10132   }
10133
10134   // Insert and return the new operation.
10135   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10136     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10137   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10138     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10139   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10140     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10141                            PhiVal, ConstantOp);
10142   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10143   
10144   // If this was a volatile load that we are merging, make sure to loop through
10145   // and mark all the input loads as non-volatile.  If we don't do this, we will
10146   // insert a new volatile load and the old ones will not be deletable.
10147   if (isVolatile)
10148     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10149       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10150   
10151   return new LoadInst(PhiVal, "", isVolatile);
10152 }
10153
10154 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10155 /// that is dead.
10156 static bool DeadPHICycle(PHINode *PN,
10157                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10158   if (PN->use_empty()) return true;
10159   if (!PN->hasOneUse()) return false;
10160
10161   // Remember this node, and if we find the cycle, return.
10162   if (!PotentiallyDeadPHIs.insert(PN))
10163     return true;
10164   
10165   // Don't scan crazily complex things.
10166   if (PotentiallyDeadPHIs.size() == 16)
10167     return false;
10168
10169   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10170     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10171
10172   return false;
10173 }
10174
10175 /// PHIsEqualValue - Return true if this phi node is always equal to
10176 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10177 ///   z = some value; x = phi (y, z); y = phi (x, z)
10178 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10179                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10180   // See if we already saw this PHI node.
10181   if (!ValueEqualPHIs.insert(PN))
10182     return true;
10183   
10184   // Don't scan crazily complex things.
10185   if (ValueEqualPHIs.size() == 16)
10186     return false;
10187  
10188   // Scan the operands to see if they are either phi nodes or are equal to
10189   // the value.
10190   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10191     Value *Op = PN->getIncomingValue(i);
10192     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10193       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10194         return false;
10195     } else if (Op != NonPhiInVal)
10196       return false;
10197   }
10198   
10199   return true;
10200 }
10201
10202
10203 // PHINode simplification
10204 //
10205 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10206   // If LCSSA is around, don't mess with Phi nodes
10207   if (MustPreserveLCSSA) return 0;
10208   
10209   if (Value *V = PN.hasConstantValue())
10210     return ReplaceInstUsesWith(PN, V);
10211
10212   // If all PHI operands are the same operation, pull them through the PHI,
10213   // reducing code size.
10214   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10215       PN.getIncomingValue(0)->hasOneUse())
10216     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10217       return Result;
10218
10219   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10220   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10221   // PHI)... break the cycle.
10222   if (PN.hasOneUse()) {
10223     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10224     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10225       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10226       PotentiallyDeadPHIs.insert(&PN);
10227       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10228         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10229     }
10230    
10231     // If this phi has a single use, and if that use just computes a value for
10232     // the next iteration of a loop, delete the phi.  This occurs with unused
10233     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10234     // common case here is good because the only other things that catch this
10235     // are induction variable analysis (sometimes) and ADCE, which is only run
10236     // late.
10237     if (PHIUser->hasOneUse() &&
10238         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10239         PHIUser->use_back() == &PN) {
10240       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10241     }
10242   }
10243
10244   // We sometimes end up with phi cycles that non-obviously end up being the
10245   // same value, for example:
10246   //   z = some value; x = phi (y, z); y = phi (x, z)
10247   // where the phi nodes don't necessarily need to be in the same block.  Do a
10248   // quick check to see if the PHI node only contains a single non-phi value, if
10249   // so, scan to see if the phi cycle is actually equal to that value.
10250   {
10251     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10252     // Scan for the first non-phi operand.
10253     while (InValNo != NumOperandVals && 
10254            isa<PHINode>(PN.getIncomingValue(InValNo)))
10255       ++InValNo;
10256
10257     if (InValNo != NumOperandVals) {
10258       Value *NonPhiInVal = PN.getOperand(InValNo);
10259       
10260       // Scan the rest of the operands to see if there are any conflicts, if so
10261       // there is no need to recursively scan other phis.
10262       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10263         Value *OpVal = PN.getIncomingValue(InValNo);
10264         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10265           break;
10266       }
10267       
10268       // If we scanned over all operands, then we have one unique value plus
10269       // phi values.  Scan PHI nodes to see if they all merge in each other or
10270       // the value.
10271       if (InValNo == NumOperandVals) {
10272         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10273         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10274           return ReplaceInstUsesWith(PN, NonPhiInVal);
10275       }
10276     }
10277   }
10278   return 0;
10279 }
10280
10281 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10282                                    Instruction *InsertPoint,
10283                                    InstCombiner *IC) {
10284   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10285   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10286   // We must cast correctly to the pointer type. Ensure that we
10287   // sign extend the integer value if it is smaller as this is
10288   // used for address computation.
10289   Instruction::CastOps opcode = 
10290      (VTySize < PtrSize ? Instruction::SExt :
10291       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10292   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10293 }
10294
10295
10296 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10297   Value *PtrOp = GEP.getOperand(0);
10298   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10299   // If so, eliminate the noop.
10300   if (GEP.getNumOperands() == 1)
10301     return ReplaceInstUsesWith(GEP, PtrOp);
10302
10303   if (isa<UndefValue>(GEP.getOperand(0)))
10304     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10305
10306   bool HasZeroPointerIndex = false;
10307   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10308     HasZeroPointerIndex = C->isNullValue();
10309
10310   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10311     return ReplaceInstUsesWith(GEP, PtrOp);
10312
10313   // Eliminate unneeded casts for indices.
10314   bool MadeChange = false;
10315   
10316   gep_type_iterator GTI = gep_type_begin(GEP);
10317   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10318        i != e; ++i, ++GTI) {
10319     if (isa<SequentialType>(*GTI)) {
10320       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10321         if (CI->getOpcode() == Instruction::ZExt ||
10322             CI->getOpcode() == Instruction::SExt) {
10323           const Type *SrcTy = CI->getOperand(0)->getType();
10324           // We can eliminate a cast from i32 to i64 iff the target 
10325           // is a 32-bit pointer target.
10326           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10327             MadeChange = true;
10328             *i = CI->getOperand(0);
10329           }
10330         }
10331       }
10332       // If we are using a wider index than needed for this platform, shrink it
10333       // to what we need.  If narrower, sign-extend it to what we need.
10334       // If the incoming value needs a cast instruction,
10335       // insert it.  This explicit cast can make subsequent optimizations more
10336       // obvious.
10337       Value *Op = *i;
10338       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10339         if (Constant *C = dyn_cast<Constant>(Op)) {
10340           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10341           MadeChange = true;
10342         } else {
10343           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10344                                 GEP);
10345           *i = Op;
10346           MadeChange = true;
10347         }
10348       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10349         if (Constant *C = dyn_cast<Constant>(Op)) {
10350           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10351           MadeChange = true;
10352         } else {
10353           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10354                                 GEP);
10355           *i = Op;
10356           MadeChange = true;
10357         }
10358       }
10359     }
10360   }
10361   if (MadeChange) return &GEP;
10362
10363   // If this GEP instruction doesn't move the pointer, and if the input operand
10364   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10365   // real input to the dest type.
10366   if (GEP.hasAllZeroIndices()) {
10367     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10368       // If the bitcast is of an allocation, and the allocation will be
10369       // converted to match the type of the cast, don't touch this.
10370       if (isa<AllocationInst>(BCI->getOperand(0))) {
10371         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10372         if (Instruction *I = visitBitCast(*BCI)) {
10373           if (I != BCI) {
10374             I->takeName(BCI);
10375             BCI->getParent()->getInstList().insert(BCI, I);
10376             ReplaceInstUsesWith(*BCI, I);
10377           }
10378           return &GEP;
10379         }
10380       }
10381       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10382     }
10383   }
10384   
10385   // Combine Indices - If the source pointer to this getelementptr instruction
10386   // is a getelementptr instruction, combine the indices of the two
10387   // getelementptr instructions into a single instruction.
10388   //
10389   SmallVector<Value*, 8> SrcGEPOperands;
10390   if (User *Src = dyn_castGetElementPtr(PtrOp))
10391     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10392
10393   if (!SrcGEPOperands.empty()) {
10394     // Note that if our source is a gep chain itself that we wait for that
10395     // chain to be resolved before we perform this transformation.  This
10396     // avoids us creating a TON of code in some cases.
10397     //
10398     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10399         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10400       return 0;   // Wait until our source is folded to completion.
10401
10402     SmallVector<Value*, 8> Indices;
10403
10404     // Find out whether the last index in the source GEP is a sequential idx.
10405     bool EndsWithSequential = false;
10406     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10407            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10408       EndsWithSequential = !isa<StructType>(*I);
10409
10410     // Can we combine the two pointer arithmetics offsets?
10411     if (EndsWithSequential) {
10412       // Replace: gep (gep %P, long B), long A, ...
10413       // With:    T = long A+B; gep %P, T, ...
10414       //
10415       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10416       if (SO1 == Constant::getNullValue(SO1->getType())) {
10417         Sum = GO1;
10418       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10419         Sum = SO1;
10420       } else {
10421         // If they aren't the same type, convert both to an integer of the
10422         // target's pointer size.
10423         if (SO1->getType() != GO1->getType()) {
10424           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10425             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10426           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10427             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10428           } else {
10429             unsigned PS = TD->getPointerSizeInBits();
10430             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10431               // Convert GO1 to SO1's type.
10432               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10433
10434             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10435               // Convert SO1 to GO1's type.
10436               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10437             } else {
10438               const Type *PT = TD->getIntPtrType();
10439               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10440               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10441             }
10442           }
10443         }
10444         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10445           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10446         else {
10447           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10448           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10449         }
10450       }
10451
10452       // Recycle the GEP we already have if possible.
10453       if (SrcGEPOperands.size() == 2) {
10454         GEP.setOperand(0, SrcGEPOperands[0]);
10455         GEP.setOperand(1, Sum);
10456         return &GEP;
10457       } else {
10458         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10459                        SrcGEPOperands.end()-1);
10460         Indices.push_back(Sum);
10461         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10462       }
10463     } else if (isa<Constant>(*GEP.idx_begin()) &&
10464                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10465                SrcGEPOperands.size() != 1) {
10466       // Otherwise we can do the fold if the first index of the GEP is a zero
10467       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10468                      SrcGEPOperands.end());
10469       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10470     }
10471
10472     if (!Indices.empty())
10473       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10474                                        Indices.end(), GEP.getName());
10475
10476   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10477     // GEP of global variable.  If all of the indices for this GEP are
10478     // constants, we can promote this to a constexpr instead of an instruction.
10479
10480     // Scan for nonconstants...
10481     SmallVector<Constant*, 8> Indices;
10482     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10483     for (; I != E && isa<Constant>(*I); ++I)
10484       Indices.push_back(cast<Constant>(*I));
10485
10486     if (I == E) {  // If they are all constants...
10487       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10488                                                     &Indices[0],Indices.size());
10489
10490       // Replace all uses of the GEP with the new constexpr...
10491       return ReplaceInstUsesWith(GEP, CE);
10492     }
10493   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10494     if (!isa<PointerType>(X->getType())) {
10495       // Not interesting.  Source pointer must be a cast from pointer.
10496     } else if (HasZeroPointerIndex) {
10497       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10498       // into     : GEP [10 x i8]* X, i32 0, ...
10499       //
10500       // This occurs when the program declares an array extern like "int X[];"
10501       //
10502       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10503       const PointerType *XTy = cast<PointerType>(X->getType());
10504       if (const ArrayType *XATy =
10505           dyn_cast<ArrayType>(XTy->getElementType()))
10506         if (const ArrayType *CATy =
10507             dyn_cast<ArrayType>(CPTy->getElementType()))
10508           if (CATy->getElementType() == XATy->getElementType()) {
10509             // At this point, we know that the cast source type is a pointer
10510             // to an array of the same type as the destination pointer
10511             // array.  Because the array type is never stepped over (there
10512             // is a leading zero) we can fold the cast into this GEP.
10513             GEP.setOperand(0, X);
10514             return &GEP;
10515           }
10516     } else if (GEP.getNumOperands() == 2) {
10517       // Transform things like:
10518       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10519       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10520       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10521       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10522       if (isa<ArrayType>(SrcElTy) &&
10523           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10524           TD->getABITypeSize(ResElTy)) {
10525         Value *Idx[2];
10526         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10527         Idx[1] = GEP.getOperand(1);
10528         Value *V = InsertNewInstBefore(
10529                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10530         // V and GEP are both pointer types --> BitCast
10531         return new BitCastInst(V, GEP.getType());
10532       }
10533       
10534       // Transform things like:
10535       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10536       //   (where tmp = 8*tmp2) into:
10537       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10538       
10539       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10540         uint64_t ArrayEltSize =
10541             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10542         
10543         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10544         // allow either a mul, shift, or constant here.
10545         Value *NewIdx = 0;
10546         ConstantInt *Scale = 0;
10547         if (ArrayEltSize == 1) {
10548           NewIdx = GEP.getOperand(1);
10549           Scale = ConstantInt::get(NewIdx->getType(), 1);
10550         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10551           NewIdx = ConstantInt::get(CI->getType(), 1);
10552           Scale = CI;
10553         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10554           if (Inst->getOpcode() == Instruction::Shl &&
10555               isa<ConstantInt>(Inst->getOperand(1))) {
10556             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10557             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10558             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10559             NewIdx = Inst->getOperand(0);
10560           } else if (Inst->getOpcode() == Instruction::Mul &&
10561                      isa<ConstantInt>(Inst->getOperand(1))) {
10562             Scale = cast<ConstantInt>(Inst->getOperand(1));
10563             NewIdx = Inst->getOperand(0);
10564           }
10565         }
10566         
10567         // If the index will be to exactly the right offset with the scale taken
10568         // out, perform the transformation. Note, we don't know whether Scale is
10569         // signed or not. We'll use unsigned version of division/modulo
10570         // operation after making sure Scale doesn't have the sign bit set.
10571         if (Scale && Scale->getSExtValue() >= 0LL &&
10572             Scale->getZExtValue() % ArrayEltSize == 0) {
10573           Scale = ConstantInt::get(Scale->getType(),
10574                                    Scale->getZExtValue() / ArrayEltSize);
10575           if (Scale->getZExtValue() != 1) {
10576             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10577                                                        false /*ZExt*/);
10578             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10579             NewIdx = InsertNewInstBefore(Sc, GEP);
10580           }
10581
10582           // Insert the new GEP instruction.
10583           Value *Idx[2];
10584           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10585           Idx[1] = NewIdx;
10586           Instruction *NewGEP =
10587             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10588           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10589           // The NewGEP must be pointer typed, so must the old one -> BitCast
10590           return new BitCastInst(NewGEP, GEP.getType());
10591         }
10592       }
10593     }
10594   }
10595
10596   return 0;
10597 }
10598
10599 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10600   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10601   if (AI.isArrayAllocation()) {  // Check C != 1
10602     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10603       const Type *NewTy = 
10604         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10605       AllocationInst *New = 0;
10606
10607       // Create and insert the replacement instruction...
10608       if (isa<MallocInst>(AI))
10609         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10610       else {
10611         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10612         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10613       }
10614
10615       InsertNewInstBefore(New, AI);
10616
10617       // Scan to the end of the allocation instructions, to skip over a block of
10618       // allocas if possible...
10619       //
10620       BasicBlock::iterator It = New;
10621       while (isa<AllocationInst>(*It)) ++It;
10622
10623       // Now that I is pointing to the first non-allocation-inst in the block,
10624       // insert our getelementptr instruction...
10625       //
10626       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10627       Value *Idx[2];
10628       Idx[0] = NullIdx;
10629       Idx[1] = NullIdx;
10630       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10631                                            New->getName()+".sub", It);
10632
10633       // Now make everything use the getelementptr instead of the original
10634       // allocation.
10635       return ReplaceInstUsesWith(AI, V);
10636     } else if (isa<UndefValue>(AI.getArraySize())) {
10637       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10638     }
10639   }
10640
10641   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10642   // Note that we only do this for alloca's, because malloc should allocate and
10643   // return a unique pointer, even for a zero byte allocation.
10644   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10645       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10646     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10647
10648   return 0;
10649 }
10650
10651 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10652   Value *Op = FI.getOperand(0);
10653
10654   // free undef -> unreachable.
10655   if (isa<UndefValue>(Op)) {
10656     // Insert a new store to null because we cannot modify the CFG here.
10657     new StoreInst(ConstantInt::getTrue(),
10658                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10659     return EraseInstFromFunction(FI);
10660   }
10661   
10662   // If we have 'free null' delete the instruction.  This can happen in stl code
10663   // when lots of inlining happens.
10664   if (isa<ConstantPointerNull>(Op))
10665     return EraseInstFromFunction(FI);
10666   
10667   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10668   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10669     FI.setOperand(0, CI->getOperand(0));
10670     return &FI;
10671   }
10672   
10673   // Change free (gep X, 0,0,0,0) into free(X)
10674   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10675     if (GEPI->hasAllZeroIndices()) {
10676       AddToWorkList(GEPI);
10677       FI.setOperand(0, GEPI->getOperand(0));
10678       return &FI;
10679     }
10680   }
10681   
10682   // Change free(malloc) into nothing, if the malloc has a single use.
10683   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10684     if (MI->hasOneUse()) {
10685       EraseInstFromFunction(FI);
10686       return EraseInstFromFunction(*MI);
10687     }
10688
10689   return 0;
10690 }
10691
10692
10693 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10694 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10695                                         const TargetData *TD) {
10696   User *CI = cast<User>(LI.getOperand(0));
10697   Value *CastOp = CI->getOperand(0);
10698
10699   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10700     // Instead of loading constant c string, use corresponding integer value
10701     // directly if string length is small enough.
10702     std::string Str;
10703     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10704       unsigned len = Str.length();
10705       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10706       unsigned numBits = Ty->getPrimitiveSizeInBits();
10707       // Replace LI with immediate integer store.
10708       if ((numBits >> 3) == len + 1) {
10709         APInt StrVal(numBits, 0);
10710         APInt SingleChar(numBits, 0);
10711         if (TD->isLittleEndian()) {
10712           for (signed i = len-1; i >= 0; i--) {
10713             SingleChar = (uint64_t) Str[i];
10714             StrVal = (StrVal << 8) | SingleChar;
10715           }
10716         } else {
10717           for (unsigned i = 0; i < len; i++) {
10718             SingleChar = (uint64_t) Str[i];
10719             StrVal = (StrVal << 8) | SingleChar;
10720           }
10721           // Append NULL at the end.
10722           SingleChar = 0;
10723           StrVal = (StrVal << 8) | SingleChar;
10724         }
10725         Value *NL = ConstantInt::get(StrVal);
10726         return IC.ReplaceInstUsesWith(LI, NL);
10727       }
10728     }
10729   }
10730
10731   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10732   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10733     const Type *SrcPTy = SrcTy->getElementType();
10734
10735     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10736          isa<VectorType>(DestPTy)) {
10737       // If the source is an array, the code below will not succeed.  Check to
10738       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10739       // constants.
10740       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10741         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10742           if (ASrcTy->getNumElements() != 0) {
10743             Value *Idxs[2];
10744             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10745             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10746             SrcTy = cast<PointerType>(CastOp->getType());
10747             SrcPTy = SrcTy->getElementType();
10748           }
10749
10750       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10751             isa<VectorType>(SrcPTy)) &&
10752           // Do not allow turning this into a load of an integer, which is then
10753           // casted to a pointer, this pessimizes pointer analysis a lot.
10754           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10755           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10756                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10757
10758         // Okay, we are casting from one integer or pointer type to another of
10759         // the same size.  Instead of casting the pointer before the load, cast
10760         // the result of the loaded value.
10761         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10762                                                              CI->getName(),
10763                                                          LI.isVolatile()),LI);
10764         // Now cast the result of the load.
10765         return new BitCastInst(NewLoad, LI.getType());
10766       }
10767     }
10768   }
10769   return 0;
10770 }
10771
10772 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10773 /// from this value cannot trap.  If it is not obviously safe to load from the
10774 /// specified pointer, we do a quick local scan of the basic block containing
10775 /// ScanFrom, to determine if the address is already accessed.
10776 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10777   // If it is an alloca it is always safe to load from.
10778   if (isa<AllocaInst>(V)) return true;
10779
10780   // If it is a global variable it is mostly safe to load from.
10781   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10782     // Don't try to evaluate aliases.  External weak GV can be null.
10783     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10784
10785   // Otherwise, be a little bit agressive by scanning the local block where we
10786   // want to check to see if the pointer is already being loaded or stored
10787   // from/to.  If so, the previous load or store would have already trapped,
10788   // so there is no harm doing an extra load (also, CSE will later eliminate
10789   // the load entirely).
10790   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10791
10792   while (BBI != E) {
10793     --BBI;
10794
10795     // If we see a free or a call (which might do a free) the pointer could be
10796     // marked invalid.
10797     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10798       return false;
10799     
10800     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10801       if (LI->getOperand(0) == V) return true;
10802     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10803       if (SI->getOperand(1) == V) return true;
10804     }
10805
10806   }
10807   return false;
10808 }
10809
10810 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10811   Value *Op = LI.getOperand(0);
10812
10813   // Attempt to improve the alignment.
10814   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10815   if (KnownAlign >
10816       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10817                                 LI.getAlignment()))
10818     LI.setAlignment(KnownAlign);
10819
10820   // load (cast X) --> cast (load X) iff safe
10821   if (isa<CastInst>(Op))
10822     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10823       return Res;
10824
10825   // None of the following transforms are legal for volatile loads.
10826   if (LI.isVolatile()) return 0;
10827   
10828   // Do really simple store-to-load forwarding and load CSE, to catch cases
10829   // where there are several consequtive memory accesses to the same location,
10830   // separated by a few arithmetic operations.
10831   BasicBlock::iterator BBI = &LI;
10832   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10833     return ReplaceInstUsesWith(LI, AvailableVal);
10834
10835   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10836     const Value *GEPI0 = GEPI->getOperand(0);
10837     // TODO: Consider a target hook for valid address spaces for this xform.
10838     if (isa<ConstantPointerNull>(GEPI0) &&
10839         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10840       // Insert a new store to null instruction before the load to indicate
10841       // that this code is not reachable.  We do this instead of inserting
10842       // an unreachable instruction directly because we cannot modify the
10843       // CFG.
10844       new StoreInst(UndefValue::get(LI.getType()),
10845                     Constant::getNullValue(Op->getType()), &LI);
10846       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10847     }
10848   } 
10849
10850   if (Constant *C = dyn_cast<Constant>(Op)) {
10851     // load null/undef -> undef
10852     // TODO: Consider a target hook for valid address spaces for this xform.
10853     if (isa<UndefValue>(C) || (C->isNullValue() && 
10854         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10855       // Insert a new store to null instruction before the load to indicate that
10856       // this code is not reachable.  We do this instead of inserting an
10857       // unreachable instruction directly because we cannot modify the CFG.
10858       new StoreInst(UndefValue::get(LI.getType()),
10859                     Constant::getNullValue(Op->getType()), &LI);
10860       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10861     }
10862
10863     // Instcombine load (constant global) into the value loaded.
10864     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10865       if (GV->isConstant() && !GV->isDeclaration())
10866         return ReplaceInstUsesWith(LI, GV->getInitializer());
10867
10868     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10869     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10870       if (CE->getOpcode() == Instruction::GetElementPtr) {
10871         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10872           if (GV->isConstant() && !GV->isDeclaration())
10873             if (Constant *V = 
10874                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10875               return ReplaceInstUsesWith(LI, V);
10876         if (CE->getOperand(0)->isNullValue()) {
10877           // Insert a new store to null instruction before the load to indicate
10878           // that this code is not reachable.  We do this instead of inserting
10879           // an unreachable instruction directly because we cannot modify the
10880           // CFG.
10881           new StoreInst(UndefValue::get(LI.getType()),
10882                         Constant::getNullValue(Op->getType()), &LI);
10883           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10884         }
10885
10886       } else if (CE->isCast()) {
10887         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10888           return Res;
10889       }
10890     }
10891   }
10892     
10893   // If this load comes from anywhere in a constant global, and if the global
10894   // is all undef or zero, we know what it loads.
10895   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
10896     if (GV->isConstant() && GV->hasInitializer()) {
10897       if (GV->getInitializer()->isNullValue())
10898         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10899       else if (isa<UndefValue>(GV->getInitializer()))
10900         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10901     }
10902   }
10903
10904   if (Op->hasOneUse()) {
10905     // Change select and PHI nodes to select values instead of addresses: this
10906     // helps alias analysis out a lot, allows many others simplifications, and
10907     // exposes redundancy in the code.
10908     //
10909     // Note that we cannot do the transformation unless we know that the
10910     // introduced loads cannot trap!  Something like this is valid as long as
10911     // the condition is always false: load (select bool %C, int* null, int* %G),
10912     // but it would not be valid if we transformed it to load from null
10913     // unconditionally.
10914     //
10915     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10916       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10917       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10918           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10919         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10920                                      SI->getOperand(1)->getName()+".val"), LI);
10921         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10922                                      SI->getOperand(2)->getName()+".val"), LI);
10923         return SelectInst::Create(SI->getCondition(), V1, V2);
10924       }
10925
10926       // load (select (cond, null, P)) -> load P
10927       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10928         if (C->isNullValue()) {
10929           LI.setOperand(0, SI->getOperand(2));
10930           return &LI;
10931         }
10932
10933       // load (select (cond, P, null)) -> load P
10934       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10935         if (C->isNullValue()) {
10936           LI.setOperand(0, SI->getOperand(1));
10937           return &LI;
10938         }
10939     }
10940   }
10941   return 0;
10942 }
10943
10944 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10945 /// when possible.
10946 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10947   User *CI = cast<User>(SI.getOperand(1));
10948   Value *CastOp = CI->getOperand(0);
10949
10950   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10951   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10952     const Type *SrcPTy = SrcTy->getElementType();
10953
10954     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10955       // If the source is an array, the code below will not succeed.  Check to
10956       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10957       // constants.
10958       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10959         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10960           if (ASrcTy->getNumElements() != 0) {
10961             Value* Idxs[2];
10962             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10963             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10964             SrcTy = cast<PointerType>(CastOp->getType());
10965             SrcPTy = SrcTy->getElementType();
10966           }
10967
10968       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10969           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10970                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10971
10972         // Okay, we are casting from one integer or pointer type to another of
10973         // the same size.  Instead of casting the pointer before 
10974         // the store, cast the value to be stored.
10975         Value *NewCast;
10976         Value *SIOp0 = SI.getOperand(0);
10977         Instruction::CastOps opcode = Instruction::BitCast;
10978         const Type* CastSrcTy = SIOp0->getType();
10979         const Type* CastDstTy = SrcPTy;
10980         if (isa<PointerType>(CastDstTy)) {
10981           if (CastSrcTy->isInteger())
10982             opcode = Instruction::IntToPtr;
10983         } else if (isa<IntegerType>(CastDstTy)) {
10984           if (isa<PointerType>(SIOp0->getType()))
10985             opcode = Instruction::PtrToInt;
10986         }
10987         if (Constant *C = dyn_cast<Constant>(SIOp0))
10988           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10989         else
10990           NewCast = IC.InsertNewInstBefore(
10991             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10992             SI);
10993         return new StoreInst(NewCast, CastOp);
10994       }
10995     }
10996   }
10997   return 0;
10998 }
10999
11000 /// equivalentAddressValues - Test if A and B will obviously have the same
11001 /// value. This includes recognizing that %t0 and %t1 will have the same
11002 /// value in code like this:
11003 ///   %t0 = getelementptr @a, 0, 3
11004 ///   store i32 0, i32* %t0
11005 ///   %t1 = getelementptr @a, 0, 3
11006 ///   %t2 = load i32* %t1
11007 ///
11008 static bool equivalentAddressValues(Value *A, Value *B) {
11009   // Test if the values are trivially equivalent.
11010   if (A == B) return true;
11011   
11012   // Test if the values come form identical arithmetic instructions.
11013   if (isa<BinaryOperator>(A) ||
11014       isa<CastInst>(A) ||
11015       isa<PHINode>(A) ||
11016       isa<GetElementPtrInst>(A))
11017     if (Instruction *BI = dyn_cast<Instruction>(B))
11018       if (cast<Instruction>(A)->isIdenticalTo(BI))
11019         return true;
11020   
11021   // Otherwise they may not be equivalent.
11022   return false;
11023 }
11024
11025 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11026   Value *Val = SI.getOperand(0);
11027   Value *Ptr = SI.getOperand(1);
11028
11029   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11030     EraseInstFromFunction(SI);
11031     ++NumCombined;
11032     return 0;
11033   }
11034   
11035   // If the RHS is an alloca with a single use, zapify the store, making the
11036   // alloca dead.
11037   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11038     if (isa<AllocaInst>(Ptr)) {
11039       EraseInstFromFunction(SI);
11040       ++NumCombined;
11041       return 0;
11042     }
11043     
11044     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11045       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11046           GEP->getOperand(0)->hasOneUse()) {
11047         EraseInstFromFunction(SI);
11048         ++NumCombined;
11049         return 0;
11050       }
11051   }
11052
11053   // Attempt to improve the alignment.
11054   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11055   if (KnownAlign >
11056       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11057                                 SI.getAlignment()))
11058     SI.setAlignment(KnownAlign);
11059
11060   // Do really simple DSE, to catch cases where there are several consequtive
11061   // stores to the same location, separated by a few arithmetic operations. This
11062   // situation often occurs with bitfield accesses.
11063   BasicBlock::iterator BBI = &SI;
11064   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11065        --ScanInsts) {
11066     --BBI;
11067     
11068     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11069       // Prev store isn't volatile, and stores to the same location?
11070       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11071                                                           SI.getOperand(1))) {
11072         ++NumDeadStore;
11073         ++BBI;
11074         EraseInstFromFunction(*PrevSI);
11075         continue;
11076       }
11077       break;
11078     }
11079     
11080     // If this is a load, we have to stop.  However, if the loaded value is from
11081     // the pointer we're loading and is producing the pointer we're storing,
11082     // then *this* store is dead (X = load P; store X -> P).
11083     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11084       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11085           !SI.isVolatile()) {
11086         EraseInstFromFunction(SI);
11087         ++NumCombined;
11088         return 0;
11089       }
11090       // Otherwise, this is a load from some other location.  Stores before it
11091       // may not be dead.
11092       break;
11093     }
11094     
11095     // Don't skip over loads or things that can modify memory.
11096     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11097       break;
11098   }
11099   
11100   
11101   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11102
11103   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11104   if (isa<ConstantPointerNull>(Ptr)) {
11105     if (!isa<UndefValue>(Val)) {
11106       SI.setOperand(0, UndefValue::get(Val->getType()));
11107       if (Instruction *U = dyn_cast<Instruction>(Val))
11108         AddToWorkList(U);  // Dropped a use.
11109       ++NumCombined;
11110     }
11111     return 0;  // Do not modify these!
11112   }
11113
11114   // store undef, Ptr -> noop
11115   if (isa<UndefValue>(Val)) {
11116     EraseInstFromFunction(SI);
11117     ++NumCombined;
11118     return 0;
11119   }
11120
11121   // If the pointer destination is a cast, see if we can fold the cast into the
11122   // source instead.
11123   if (isa<CastInst>(Ptr))
11124     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11125       return Res;
11126   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11127     if (CE->isCast())
11128       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11129         return Res;
11130
11131   
11132   // If this store is the last instruction in the basic block, and if the block
11133   // ends with an unconditional branch, try to move it to the successor block.
11134   BBI = &SI; ++BBI;
11135   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11136     if (BI->isUnconditional())
11137       if (SimplifyStoreAtEndOfBlock(SI))
11138         return 0;  // xform done!
11139   
11140   return 0;
11141 }
11142
11143 /// SimplifyStoreAtEndOfBlock - Turn things like:
11144 ///   if () { *P = v1; } else { *P = v2 }
11145 /// into a phi node with a store in the successor.
11146 ///
11147 /// Simplify things like:
11148 ///   *P = v1; if () { *P = v2; }
11149 /// into a phi node with a store in the successor.
11150 ///
11151 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11152   BasicBlock *StoreBB = SI.getParent();
11153   
11154   // Check to see if the successor block has exactly two incoming edges.  If
11155   // so, see if the other predecessor contains a store to the same location.
11156   // if so, insert a PHI node (if needed) and move the stores down.
11157   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11158   
11159   // Determine whether Dest has exactly two predecessors and, if so, compute
11160   // the other predecessor.
11161   pred_iterator PI = pred_begin(DestBB);
11162   BasicBlock *OtherBB = 0;
11163   if (*PI != StoreBB)
11164     OtherBB = *PI;
11165   ++PI;
11166   if (PI == pred_end(DestBB))
11167     return false;
11168   
11169   if (*PI != StoreBB) {
11170     if (OtherBB)
11171       return false;
11172     OtherBB = *PI;
11173   }
11174   if (++PI != pred_end(DestBB))
11175     return false;
11176
11177   // Bail out if all the relevant blocks aren't distinct (this can happen,
11178   // for example, if SI is in an infinite loop)
11179   if (StoreBB == DestBB || OtherBB == DestBB)
11180     return false;
11181
11182   // Verify that the other block ends in a branch and is not otherwise empty.
11183   BasicBlock::iterator BBI = OtherBB->getTerminator();
11184   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11185   if (!OtherBr || BBI == OtherBB->begin())
11186     return false;
11187   
11188   // If the other block ends in an unconditional branch, check for the 'if then
11189   // else' case.  there is an instruction before the branch.
11190   StoreInst *OtherStore = 0;
11191   if (OtherBr->isUnconditional()) {
11192     // If this isn't a store, or isn't a store to the same location, bail out.
11193     --BBI;
11194     OtherStore = dyn_cast<StoreInst>(BBI);
11195     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11196       return false;
11197   } else {
11198     // Otherwise, the other block ended with a conditional branch. If one of the
11199     // destinations is StoreBB, then we have the if/then case.
11200     if (OtherBr->getSuccessor(0) != StoreBB && 
11201         OtherBr->getSuccessor(1) != StoreBB)
11202       return false;
11203     
11204     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11205     // if/then triangle.  See if there is a store to the same ptr as SI that
11206     // lives in OtherBB.
11207     for (;; --BBI) {
11208       // Check to see if we find the matching store.
11209       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11210         if (OtherStore->getOperand(1) != SI.getOperand(1))
11211           return false;
11212         break;
11213       }
11214       // If we find something that may be using or overwriting the stored
11215       // value, or if we run out of instructions, we can't do the xform.
11216       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11217           BBI == OtherBB->begin())
11218         return false;
11219     }
11220     
11221     // In order to eliminate the store in OtherBr, we have to
11222     // make sure nothing reads or overwrites the stored value in
11223     // StoreBB.
11224     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11225       // FIXME: This should really be AA driven.
11226       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11227         return false;
11228     }
11229   }
11230   
11231   // Insert a PHI node now if we need it.
11232   Value *MergedVal = OtherStore->getOperand(0);
11233   if (MergedVal != SI.getOperand(0)) {
11234     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11235     PN->reserveOperandSpace(2);
11236     PN->addIncoming(SI.getOperand(0), SI.getParent());
11237     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11238     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11239   }
11240   
11241   // Advance to a place where it is safe to insert the new store and
11242   // insert it.
11243   BBI = DestBB->getFirstNonPHI();
11244   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11245                                     OtherStore->isVolatile()), *BBI);
11246   
11247   // Nuke the old stores.
11248   EraseInstFromFunction(SI);
11249   EraseInstFromFunction(*OtherStore);
11250   ++NumCombined;
11251   return true;
11252 }
11253
11254
11255 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11256   // Change br (not X), label True, label False to: br X, label False, True
11257   Value *X = 0;
11258   BasicBlock *TrueDest;
11259   BasicBlock *FalseDest;
11260   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11261       !isa<Constant>(X)) {
11262     // Swap Destinations and condition...
11263     BI.setCondition(X);
11264     BI.setSuccessor(0, FalseDest);
11265     BI.setSuccessor(1, TrueDest);
11266     return &BI;
11267   }
11268
11269   // Cannonicalize fcmp_one -> fcmp_oeq
11270   FCmpInst::Predicate FPred; Value *Y;
11271   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11272                              TrueDest, FalseDest)))
11273     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11274          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11275       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11276       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11277       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11278       NewSCC->takeName(I);
11279       // Swap Destinations and condition...
11280       BI.setCondition(NewSCC);
11281       BI.setSuccessor(0, FalseDest);
11282       BI.setSuccessor(1, TrueDest);
11283       RemoveFromWorkList(I);
11284       I->eraseFromParent();
11285       AddToWorkList(NewSCC);
11286       return &BI;
11287     }
11288
11289   // Cannonicalize icmp_ne -> icmp_eq
11290   ICmpInst::Predicate IPred;
11291   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11292                       TrueDest, FalseDest)))
11293     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11294          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11295          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11296       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11297       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11298       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11299       NewSCC->takeName(I);
11300       // Swap Destinations and condition...
11301       BI.setCondition(NewSCC);
11302       BI.setSuccessor(0, FalseDest);
11303       BI.setSuccessor(1, TrueDest);
11304       RemoveFromWorkList(I);
11305       I->eraseFromParent();;
11306       AddToWorkList(NewSCC);
11307       return &BI;
11308     }
11309
11310   return 0;
11311 }
11312
11313 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11314   Value *Cond = SI.getCondition();
11315   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11316     if (I->getOpcode() == Instruction::Add)
11317       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11318         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11319         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11320           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11321                                                 AddRHS));
11322         SI.setOperand(0, I->getOperand(0));
11323         AddToWorkList(I);
11324         return &SI;
11325       }
11326   }
11327   return 0;
11328 }
11329
11330 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11331   Value *Agg = EV.getAggregateOperand();
11332
11333   if (!EV.hasIndices())
11334     return ReplaceInstUsesWith(EV, Agg);
11335
11336   if (Constant *C = dyn_cast<Constant>(Agg)) {
11337     if (isa<UndefValue>(C))
11338       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11339       
11340     if (isa<ConstantAggregateZero>(C))
11341       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11342
11343     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11344       // Extract the element indexed by the first index out of the constant
11345       Value *V = C->getOperand(*EV.idx_begin());
11346       if (EV.getNumIndices() > 1)
11347         // Extract the remaining indices out of the constant indexed by the
11348         // first index
11349         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11350       else
11351         return ReplaceInstUsesWith(EV, V);
11352     }
11353     return 0; // Can't handle other constants
11354   } 
11355   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11356     // We're extracting from an insertvalue instruction, compare the indices
11357     const unsigned *exti, *exte, *insi, *inse;
11358     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11359          exte = EV.idx_end(), inse = IV->idx_end();
11360          exti != exte && insi != inse;
11361          ++exti, ++insi) {
11362       if (*insi != *exti)
11363         // The insert and extract both reference distinctly different elements.
11364         // This means the extract is not influenced by the insert, and we can
11365         // replace the aggregate operand of the extract with the aggregate
11366         // operand of the insert. i.e., replace
11367         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11368         // %E = extractvalue { i32, { i32 } } %I, 0
11369         // with
11370         // %E = extractvalue { i32, { i32 } } %A, 0
11371         return ExtractValueInst::Create(IV->getAggregateOperand(),
11372                                         EV.idx_begin(), EV.idx_end());
11373     }
11374     if (exti == exte && insi == inse)
11375       // Both iterators are at the end: Index lists are identical. Replace
11376       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11377       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11378       // with "i32 42"
11379       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11380     if (exti == exte) {
11381       // The extract list is a prefix of the insert list. i.e. replace
11382       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11383       // %E = extractvalue { i32, { i32 } } %I, 1
11384       // with
11385       // %X = extractvalue { i32, { i32 } } %A, 1
11386       // %E = insertvalue { i32 } %X, i32 42, 0
11387       // by switching the order of the insert and extract (though the
11388       // insertvalue should be left in, since it may have other uses).
11389       Value *NewEV = InsertNewInstBefore(
11390         ExtractValueInst::Create(IV->getAggregateOperand(),
11391                                  EV.idx_begin(), EV.idx_end()),
11392         EV);
11393       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11394                                      insi, inse);
11395     }
11396     if (insi == inse)
11397       // The insert list is a prefix of the extract list
11398       // We can simply remove the common indices from the extract and make it
11399       // operate on the inserted value instead of the insertvalue result.
11400       // i.e., replace
11401       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11402       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11403       // with
11404       // %E extractvalue { i32 } { i32 42 }, 0
11405       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11406                                       exti, exte);
11407   }
11408   // Can't simplify extracts from other values. Note that nested extracts are
11409   // already simplified implicitely by the above (extract ( extract (insert) )
11410   // will be translated into extract ( insert ( extract ) ) first and then just
11411   // the value inserted, if appropriate).
11412   return 0;
11413 }
11414
11415 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11416 /// is to leave as a vector operation.
11417 static bool CheapToScalarize(Value *V, bool isConstant) {
11418   if (isa<ConstantAggregateZero>(V)) 
11419     return true;
11420   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11421     if (isConstant) return true;
11422     // If all elts are the same, we can extract.
11423     Constant *Op0 = C->getOperand(0);
11424     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11425       if (C->getOperand(i) != Op0)
11426         return false;
11427     return true;
11428   }
11429   Instruction *I = dyn_cast<Instruction>(V);
11430   if (!I) return false;
11431   
11432   // Insert element gets simplified to the inserted element or is deleted if
11433   // this is constant idx extract element and its a constant idx insertelt.
11434   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11435       isa<ConstantInt>(I->getOperand(2)))
11436     return true;
11437   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11438     return true;
11439   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11440     if (BO->hasOneUse() &&
11441         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11442          CheapToScalarize(BO->getOperand(1), isConstant)))
11443       return true;
11444   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11445     if (CI->hasOneUse() &&
11446         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11447          CheapToScalarize(CI->getOperand(1), isConstant)))
11448       return true;
11449   
11450   return false;
11451 }
11452
11453 /// Read and decode a shufflevector mask.
11454 ///
11455 /// It turns undef elements into values that are larger than the number of
11456 /// elements in the input.
11457 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11458   unsigned NElts = SVI->getType()->getNumElements();
11459   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11460     return std::vector<unsigned>(NElts, 0);
11461   if (isa<UndefValue>(SVI->getOperand(2)))
11462     return std::vector<unsigned>(NElts, 2*NElts);
11463
11464   std::vector<unsigned> Result;
11465   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11466   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11467     if (isa<UndefValue>(*i))
11468       Result.push_back(NElts*2);  // undef -> 8
11469     else
11470       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11471   return Result;
11472 }
11473
11474 /// FindScalarElement - Given a vector and an element number, see if the scalar
11475 /// value is already around as a register, for example if it were inserted then
11476 /// extracted from the vector.
11477 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11478   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11479   const VectorType *PTy = cast<VectorType>(V->getType());
11480   unsigned Width = PTy->getNumElements();
11481   if (EltNo >= Width)  // Out of range access.
11482     return UndefValue::get(PTy->getElementType());
11483   
11484   if (isa<UndefValue>(V))
11485     return UndefValue::get(PTy->getElementType());
11486   else if (isa<ConstantAggregateZero>(V))
11487     return Constant::getNullValue(PTy->getElementType());
11488   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11489     return CP->getOperand(EltNo);
11490   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11491     // If this is an insert to a variable element, we don't know what it is.
11492     if (!isa<ConstantInt>(III->getOperand(2))) 
11493       return 0;
11494     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11495     
11496     // If this is an insert to the element we are looking for, return the
11497     // inserted value.
11498     if (EltNo == IIElt) 
11499       return III->getOperand(1);
11500     
11501     // Otherwise, the insertelement doesn't modify the value, recurse on its
11502     // vector input.
11503     return FindScalarElement(III->getOperand(0), EltNo);
11504   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11505     unsigned LHSWidth =
11506       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11507     unsigned InEl = getShuffleMask(SVI)[EltNo];
11508     if (InEl < LHSWidth)
11509       return FindScalarElement(SVI->getOperand(0), InEl);
11510     else if (InEl < LHSWidth*2)
11511       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11512     else
11513       return UndefValue::get(PTy->getElementType());
11514   }
11515   
11516   // Otherwise, we don't know.
11517   return 0;
11518 }
11519
11520 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11521   // If vector val is undef, replace extract with scalar undef.
11522   if (isa<UndefValue>(EI.getOperand(0)))
11523     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11524
11525   // If vector val is constant 0, replace extract with scalar 0.
11526   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11527     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11528   
11529   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11530     // If vector val is constant with all elements the same, replace EI with
11531     // that element. When the elements are not identical, we cannot replace yet
11532     // (we do that below, but only when the index is constant).
11533     Constant *op0 = C->getOperand(0);
11534     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11535       if (C->getOperand(i) != op0) {
11536         op0 = 0; 
11537         break;
11538       }
11539     if (op0)
11540       return ReplaceInstUsesWith(EI, op0);
11541   }
11542   
11543   // If extracting a specified index from the vector, see if we can recursively
11544   // find a previously computed scalar that was inserted into the vector.
11545   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11546     unsigned IndexVal = IdxC->getZExtValue();
11547     unsigned VectorWidth = 
11548       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11549       
11550     // If this is extracting an invalid index, turn this into undef, to avoid
11551     // crashing the code below.
11552     if (IndexVal >= VectorWidth)
11553       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11554     
11555     // This instruction only demands the single element from the input vector.
11556     // If the input vector has a single use, simplify it based on this use
11557     // property.
11558     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11559       uint64_t UndefElts;
11560       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11561                                                 1 << IndexVal,
11562                                                 UndefElts)) {
11563         EI.setOperand(0, V);
11564         return &EI;
11565       }
11566     }
11567     
11568     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11569       return ReplaceInstUsesWith(EI, Elt);
11570     
11571     // If the this extractelement is directly using a bitcast from a vector of
11572     // the same number of elements, see if we can find the source element from
11573     // it.  In this case, we will end up needing to bitcast the scalars.
11574     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11575       if (const VectorType *VT = 
11576               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11577         if (VT->getNumElements() == VectorWidth)
11578           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11579             return new BitCastInst(Elt, EI.getType());
11580     }
11581   }
11582   
11583   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11584     if (I->hasOneUse()) {
11585       // Push extractelement into predecessor operation if legal and
11586       // profitable to do so
11587       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11588         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11589         if (CheapToScalarize(BO, isConstantElt)) {
11590           ExtractElementInst *newEI0 = 
11591             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11592                                    EI.getName()+".lhs");
11593           ExtractElementInst *newEI1 =
11594             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11595                                    EI.getName()+".rhs");
11596           InsertNewInstBefore(newEI0, EI);
11597           InsertNewInstBefore(newEI1, EI);
11598           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11599         }
11600       } else if (isa<LoadInst>(I)) {
11601         unsigned AS = 
11602           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11603         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11604                                          PointerType::get(EI.getType(), AS),EI);
11605         GetElementPtrInst *GEP =
11606           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11607         InsertNewInstBefore(GEP, EI);
11608         return new LoadInst(GEP);
11609       }
11610     }
11611     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11612       // Extracting the inserted element?
11613       if (IE->getOperand(2) == EI.getOperand(1))
11614         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11615       // If the inserted and extracted elements are constants, they must not
11616       // be the same value, extract from the pre-inserted value instead.
11617       if (isa<Constant>(IE->getOperand(2)) &&
11618           isa<Constant>(EI.getOperand(1))) {
11619         AddUsesToWorkList(EI);
11620         EI.setOperand(0, IE->getOperand(0));
11621         return &EI;
11622       }
11623     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11624       // If this is extracting an element from a shufflevector, figure out where
11625       // it came from and extract from the appropriate input element instead.
11626       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11627         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11628         Value *Src;
11629         unsigned LHSWidth =
11630           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11631
11632         if (SrcIdx < LHSWidth)
11633           Src = SVI->getOperand(0);
11634         else if (SrcIdx < LHSWidth*2) {
11635           SrcIdx -= LHSWidth;
11636           Src = SVI->getOperand(1);
11637         } else {
11638           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11639         }
11640         return new ExtractElementInst(Src, SrcIdx);
11641       }
11642     }
11643   }
11644   return 0;
11645 }
11646
11647 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11648 /// elements from either LHS or RHS, return the shuffle mask and true. 
11649 /// Otherwise, return false.
11650 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11651                                          std::vector<Constant*> &Mask) {
11652   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11653          "Invalid CollectSingleShuffleElements");
11654   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11655
11656   if (isa<UndefValue>(V)) {
11657     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11658     return true;
11659   } else if (V == LHS) {
11660     for (unsigned i = 0; i != NumElts; ++i)
11661       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11662     return true;
11663   } else if (V == RHS) {
11664     for (unsigned i = 0; i != NumElts; ++i)
11665       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11666     return true;
11667   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11668     // If this is an insert of an extract from some other vector, include it.
11669     Value *VecOp    = IEI->getOperand(0);
11670     Value *ScalarOp = IEI->getOperand(1);
11671     Value *IdxOp    = IEI->getOperand(2);
11672     
11673     if (!isa<ConstantInt>(IdxOp))
11674       return false;
11675     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11676     
11677     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11678       // Okay, we can handle this if the vector we are insertinting into is
11679       // transitively ok.
11680       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11681         // If so, update the mask to reflect the inserted undef.
11682         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11683         return true;
11684       }      
11685     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11686       if (isa<ConstantInt>(EI->getOperand(1)) &&
11687           EI->getOperand(0)->getType() == V->getType()) {
11688         unsigned ExtractedIdx =
11689           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11690         
11691         // This must be extracting from either LHS or RHS.
11692         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11693           // Okay, we can handle this if the vector we are insertinting into is
11694           // transitively ok.
11695           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11696             // If so, update the mask to reflect the inserted value.
11697             if (EI->getOperand(0) == LHS) {
11698               Mask[InsertedIdx % NumElts] = 
11699                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11700             } else {
11701               assert(EI->getOperand(0) == RHS);
11702               Mask[InsertedIdx % NumElts] = 
11703                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11704               
11705             }
11706             return true;
11707           }
11708         }
11709       }
11710     }
11711   }
11712   // TODO: Handle shufflevector here!
11713   
11714   return false;
11715 }
11716
11717 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11718 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11719 /// that computes V and the LHS value of the shuffle.
11720 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11721                                      Value *&RHS) {
11722   assert(isa<VectorType>(V->getType()) && 
11723          (RHS == 0 || V->getType() == RHS->getType()) &&
11724          "Invalid shuffle!");
11725   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11726
11727   if (isa<UndefValue>(V)) {
11728     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11729     return V;
11730   } else if (isa<ConstantAggregateZero>(V)) {
11731     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11732     return V;
11733   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11734     // If this is an insert of an extract from some other vector, include it.
11735     Value *VecOp    = IEI->getOperand(0);
11736     Value *ScalarOp = IEI->getOperand(1);
11737     Value *IdxOp    = IEI->getOperand(2);
11738     
11739     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11740       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11741           EI->getOperand(0)->getType() == V->getType()) {
11742         unsigned ExtractedIdx =
11743           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11744         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11745         
11746         // Either the extracted from or inserted into vector must be RHSVec,
11747         // otherwise we'd end up with a shuffle of three inputs.
11748         if (EI->getOperand(0) == RHS || RHS == 0) {
11749           RHS = EI->getOperand(0);
11750           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11751           Mask[InsertedIdx % NumElts] = 
11752             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11753           return V;
11754         }
11755         
11756         if (VecOp == RHS) {
11757           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11758           // Everything but the extracted element is replaced with the RHS.
11759           for (unsigned i = 0; i != NumElts; ++i) {
11760             if (i != InsertedIdx)
11761               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11762           }
11763           return V;
11764         }
11765         
11766         // If this insertelement is a chain that comes from exactly these two
11767         // vectors, return the vector and the effective shuffle.
11768         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11769           return EI->getOperand(0);
11770         
11771       }
11772     }
11773   }
11774   // TODO: Handle shufflevector here!
11775   
11776   // Otherwise, can't do anything fancy.  Return an identity vector.
11777   for (unsigned i = 0; i != NumElts; ++i)
11778     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11779   return V;
11780 }
11781
11782 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11783   Value *VecOp    = IE.getOperand(0);
11784   Value *ScalarOp = IE.getOperand(1);
11785   Value *IdxOp    = IE.getOperand(2);
11786   
11787   // Inserting an undef or into an undefined place, remove this.
11788   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11789     ReplaceInstUsesWith(IE, VecOp);
11790   
11791   // If the inserted element was extracted from some other vector, and if the 
11792   // indexes are constant, try to turn this into a shufflevector operation.
11793   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11794     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11795         EI->getOperand(0)->getType() == IE.getType()) {
11796       unsigned NumVectorElts = IE.getType()->getNumElements();
11797       unsigned ExtractedIdx =
11798         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11799       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11800       
11801       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11802         return ReplaceInstUsesWith(IE, VecOp);
11803       
11804       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11805         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11806       
11807       // If we are extracting a value from a vector, then inserting it right
11808       // back into the same place, just use the input vector.
11809       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11810         return ReplaceInstUsesWith(IE, VecOp);      
11811       
11812       // We could theoretically do this for ANY input.  However, doing so could
11813       // turn chains of insertelement instructions into a chain of shufflevector
11814       // instructions, and right now we do not merge shufflevectors.  As such,
11815       // only do this in a situation where it is clear that there is benefit.
11816       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11817         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11818         // the values of VecOp, except then one read from EIOp0.
11819         // Build a new shuffle mask.
11820         std::vector<Constant*> Mask;
11821         if (isa<UndefValue>(VecOp))
11822           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11823         else {
11824           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11825           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11826                                                        NumVectorElts));
11827         } 
11828         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11829         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11830                                      ConstantVector::get(Mask));
11831       }
11832       
11833       // If this insertelement isn't used by some other insertelement, turn it
11834       // (and any insertelements it points to), into one big shuffle.
11835       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11836         std::vector<Constant*> Mask;
11837         Value *RHS = 0;
11838         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11839         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11840         // We now have a shuffle of LHS, RHS, Mask.
11841         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11842       }
11843     }
11844   }
11845
11846   return 0;
11847 }
11848
11849
11850 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11851   Value *LHS = SVI.getOperand(0);
11852   Value *RHS = SVI.getOperand(1);
11853   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11854
11855   bool MadeChange = false;
11856
11857   // Undefined shuffle mask -> undefined value.
11858   if (isa<UndefValue>(SVI.getOperand(2)))
11859     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11860
11861   uint64_t UndefElts;
11862   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11863
11864   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11865     return 0;
11866
11867   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11868   if (VWidth <= 64 &&
11869       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11870     LHS = SVI.getOperand(0);
11871     RHS = SVI.getOperand(1);
11872     MadeChange = true;
11873   }
11874   
11875   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11876   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11877   if (LHS == RHS || isa<UndefValue>(LHS)) {
11878     if (isa<UndefValue>(LHS) && LHS == RHS) {
11879       // shuffle(undef,undef,mask) -> undef.
11880       return ReplaceInstUsesWith(SVI, LHS);
11881     }
11882     
11883     // Remap any references to RHS to use LHS.
11884     std::vector<Constant*> Elts;
11885     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11886       if (Mask[i] >= 2*e)
11887         Elts.push_back(UndefValue::get(Type::Int32Ty));
11888       else {
11889         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11890             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11891           Mask[i] = 2*e;     // Turn into undef.
11892           Elts.push_back(UndefValue::get(Type::Int32Ty));
11893         } else {
11894           Mask[i] = Mask[i] % e;  // Force to LHS.
11895           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11896         }
11897       }
11898     }
11899     SVI.setOperand(0, SVI.getOperand(1));
11900     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11901     SVI.setOperand(2, ConstantVector::get(Elts));
11902     LHS = SVI.getOperand(0);
11903     RHS = SVI.getOperand(1);
11904     MadeChange = true;
11905   }
11906   
11907   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11908   bool isLHSID = true, isRHSID = true;
11909     
11910   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11911     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11912     // Is this an identity shuffle of the LHS value?
11913     isLHSID &= (Mask[i] == i);
11914       
11915     // Is this an identity shuffle of the RHS value?
11916     isRHSID &= (Mask[i]-e == i);
11917   }
11918
11919   // Eliminate identity shuffles.
11920   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11921   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11922   
11923   // If the LHS is a shufflevector itself, see if we can combine it with this
11924   // one without producing an unusual shuffle.  Here we are really conservative:
11925   // we are absolutely afraid of producing a shuffle mask not in the input
11926   // program, because the code gen may not be smart enough to turn a merged
11927   // shuffle into two specific shuffles: it may produce worse code.  As such,
11928   // we only merge two shuffles if the result is one of the two input shuffle
11929   // masks.  In this case, merging the shuffles just removes one instruction,
11930   // which we know is safe.  This is good for things like turning:
11931   // (splat(splat)) -> splat.
11932   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11933     if (isa<UndefValue>(RHS)) {
11934       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11935
11936       std::vector<unsigned> NewMask;
11937       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11938         if (Mask[i] >= 2*e)
11939           NewMask.push_back(2*e);
11940         else
11941           NewMask.push_back(LHSMask[Mask[i]]);
11942       
11943       // If the result mask is equal to the src shuffle or this shuffle mask, do
11944       // the replacement.
11945       if (NewMask == LHSMask || NewMask == Mask) {
11946         std::vector<Constant*> Elts;
11947         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11948           if (NewMask[i] >= e*2) {
11949             Elts.push_back(UndefValue::get(Type::Int32Ty));
11950           } else {
11951             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11952           }
11953         }
11954         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11955                                      LHSSVI->getOperand(1),
11956                                      ConstantVector::get(Elts));
11957       }
11958     }
11959   }
11960
11961   return MadeChange ? &SVI : 0;
11962 }
11963
11964
11965
11966
11967 /// TryToSinkInstruction - Try to move the specified instruction from its
11968 /// current block into the beginning of DestBlock, which can only happen if it's
11969 /// safe to move the instruction past all of the instructions between it and the
11970 /// end of its block.
11971 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11972   assert(I->hasOneUse() && "Invariants didn't hold!");
11973
11974   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11975   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11976     return false;
11977
11978   // Do not sink alloca instructions out of the entry block.
11979   if (isa<AllocaInst>(I) && I->getParent() ==
11980         &DestBlock->getParent()->getEntryBlock())
11981     return false;
11982
11983   // We can only sink load instructions if there is nothing between the load and
11984   // the end of block that could change the value.
11985   if (I->mayReadFromMemory()) {
11986     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11987          Scan != E; ++Scan)
11988       if (Scan->mayWriteToMemory())
11989         return false;
11990   }
11991
11992   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11993
11994   I->moveBefore(InsertPos);
11995   ++NumSunkInst;
11996   return true;
11997 }
11998
11999
12000 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12001 /// all reachable code to the worklist.
12002 ///
12003 /// This has a couple of tricks to make the code faster and more powerful.  In
12004 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12005 /// them to the worklist (this significantly speeds up instcombine on code where
12006 /// many instructions are dead or constant).  Additionally, if we find a branch
12007 /// whose condition is a known constant, we only visit the reachable successors.
12008 ///
12009 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12010                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12011                                        InstCombiner &IC,
12012                                        const TargetData *TD) {
12013   SmallVector<BasicBlock*, 256> Worklist;
12014   Worklist.push_back(BB);
12015
12016   while (!Worklist.empty()) {
12017     BB = Worklist.back();
12018     Worklist.pop_back();
12019     
12020     // We have now visited this block!  If we've already been here, ignore it.
12021     if (!Visited.insert(BB)) continue;
12022
12023     DbgInfoIntrinsic *DBI_Prev = NULL;
12024     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12025       Instruction *Inst = BBI++;
12026       
12027       // DCE instruction if trivially dead.
12028       if (isInstructionTriviallyDead(Inst)) {
12029         ++NumDeadInst;
12030         DOUT << "IC: DCE: " << *Inst;
12031         Inst->eraseFromParent();
12032         continue;
12033       }
12034       
12035       // ConstantProp instruction if trivially constant.
12036       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12037         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12038         Inst->replaceAllUsesWith(C);
12039         ++NumConstProp;
12040         Inst->eraseFromParent();
12041         continue;
12042       }
12043      
12044       // If there are two consecutive llvm.dbg.stoppoint calls then
12045       // it is likely that the optimizer deleted code in between these
12046       // two intrinsics. 
12047       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12048       if (DBI_Next) {
12049         if (DBI_Prev
12050             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12051             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12052           IC.RemoveFromWorkList(DBI_Prev);
12053           DBI_Prev->eraseFromParent();
12054         }
12055         DBI_Prev = DBI_Next;
12056       }
12057
12058       IC.AddToWorkList(Inst);
12059     }
12060
12061     // Recursively visit successors.  If this is a branch or switch on a
12062     // constant, only visit the reachable successor.
12063     TerminatorInst *TI = BB->getTerminator();
12064     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12065       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12066         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12067         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12068         Worklist.push_back(ReachableBB);
12069         continue;
12070       }
12071     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12072       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12073         // See if this is an explicit destination.
12074         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12075           if (SI->getCaseValue(i) == Cond) {
12076             BasicBlock *ReachableBB = SI->getSuccessor(i);
12077             Worklist.push_back(ReachableBB);
12078             continue;
12079           }
12080         
12081         // Otherwise it is the default destination.
12082         Worklist.push_back(SI->getSuccessor(0));
12083         continue;
12084       }
12085     }
12086     
12087     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12088       Worklist.push_back(TI->getSuccessor(i));
12089   }
12090 }
12091
12092 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12093   bool Changed = false;
12094   TD = &getAnalysis<TargetData>();
12095   
12096   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12097              << F.getNameStr() << "\n");
12098
12099   {
12100     // Do a depth-first traversal of the function, populate the worklist with
12101     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12102     // track of which blocks we visit.
12103     SmallPtrSet<BasicBlock*, 64> Visited;
12104     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12105
12106     // Do a quick scan over the function.  If we find any blocks that are
12107     // unreachable, remove any instructions inside of them.  This prevents
12108     // the instcombine code from having to deal with some bad special cases.
12109     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12110       if (!Visited.count(BB)) {
12111         Instruction *Term = BB->getTerminator();
12112         while (Term != BB->begin()) {   // Remove instrs bottom-up
12113           BasicBlock::iterator I = Term; --I;
12114
12115           DOUT << "IC: DCE: " << *I;
12116           ++NumDeadInst;
12117
12118           if (!I->use_empty())
12119             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12120           I->eraseFromParent();
12121         }
12122       }
12123   }
12124
12125   while (!Worklist.empty()) {
12126     Instruction *I = RemoveOneFromWorkList();
12127     if (I == 0) continue;  // skip null values.
12128
12129     // Check to see if we can DCE the instruction.
12130     if (isInstructionTriviallyDead(I)) {
12131       // Add operands to the worklist.
12132       if (I->getNumOperands() < 4)
12133         AddUsesToWorkList(*I);
12134       ++NumDeadInst;
12135
12136       DOUT << "IC: DCE: " << *I;
12137
12138       I->eraseFromParent();
12139       RemoveFromWorkList(I);
12140       continue;
12141     }
12142
12143     // Instruction isn't dead, see if we can constant propagate it.
12144     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12145       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12146
12147       // Add operands to the worklist.
12148       AddUsesToWorkList(*I);
12149       ReplaceInstUsesWith(*I, C);
12150
12151       ++NumConstProp;
12152       I->eraseFromParent();
12153       RemoveFromWorkList(I);
12154       continue;
12155     }
12156
12157     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12158       // See if we can constant fold its operands.
12159       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12160         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12161           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12162             i->set(NewC);
12163         }
12164       }
12165     }
12166
12167     // See if we can trivially sink this instruction to a successor basic block.
12168     if (I->hasOneUse()) {
12169       BasicBlock *BB = I->getParent();
12170       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12171       if (UserParent != BB) {
12172         bool UserIsSuccessor = false;
12173         // See if the user is one of our successors.
12174         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12175           if (*SI == UserParent) {
12176             UserIsSuccessor = true;
12177             break;
12178           }
12179
12180         // If the user is one of our immediate successors, and if that successor
12181         // only has us as a predecessors (we'd have to split the critical edge
12182         // otherwise), we can keep going.
12183         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12184             next(pred_begin(UserParent)) == pred_end(UserParent))
12185           // Okay, the CFG is simple enough, try to sink this instruction.
12186           Changed |= TryToSinkInstruction(I, UserParent);
12187       }
12188     }
12189
12190     // Now that we have an instruction, try combining it to simplify it...
12191 #ifndef NDEBUG
12192     std::string OrigI;
12193 #endif
12194     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12195     if (Instruction *Result = visit(*I)) {
12196       ++NumCombined;
12197       // Should we replace the old instruction with a new one?
12198       if (Result != I) {
12199         DOUT << "IC: Old = " << *I
12200              << "    New = " << *Result;
12201
12202         // Everything uses the new instruction now.
12203         I->replaceAllUsesWith(Result);
12204
12205         // Push the new instruction and any users onto the worklist.
12206         AddToWorkList(Result);
12207         AddUsersToWorkList(*Result);
12208
12209         // Move the name to the new instruction first.
12210         Result->takeName(I);
12211
12212         // Insert the new instruction into the basic block...
12213         BasicBlock *InstParent = I->getParent();
12214         BasicBlock::iterator InsertPos = I;
12215
12216         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12217           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12218             ++InsertPos;
12219
12220         InstParent->getInstList().insert(InsertPos, Result);
12221
12222         // Make sure that we reprocess all operands now that we reduced their
12223         // use counts.
12224         AddUsesToWorkList(*I);
12225
12226         // Instructions can end up on the worklist more than once.  Make sure
12227         // we do not process an instruction that has been deleted.
12228         RemoveFromWorkList(I);
12229
12230         // Erase the old instruction.
12231         InstParent->getInstList().erase(I);
12232       } else {
12233 #ifndef NDEBUG
12234         DOUT << "IC: Mod = " << OrigI
12235              << "    New = " << *I;
12236 #endif
12237
12238         // If the instruction was modified, it's possible that it is now dead.
12239         // if so, remove it.
12240         if (isInstructionTriviallyDead(I)) {
12241           // Make sure we process all operands now that we are reducing their
12242           // use counts.
12243           AddUsesToWorkList(*I);
12244
12245           // Instructions may end up in the worklist more than once.  Erase all
12246           // occurrences of this instruction.
12247           RemoveFromWorkList(I);
12248           I->eraseFromParent();
12249         } else {
12250           AddToWorkList(I);
12251           AddUsersToWorkList(*I);
12252         }
12253       }
12254       Changed = true;
12255     }
12256   }
12257
12258   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12259     
12260   // Do an explicit clear, this shrinks the map if needed.
12261   WorklistMap.clear();
12262   return Changed;
12263 }
12264
12265
12266 bool InstCombiner::runOnFunction(Function &F) {
12267   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12268   
12269   bool EverMadeChange = false;
12270
12271   // Iterate while there is work to do.
12272   unsigned Iteration = 0;
12273   while (DoOneIteration(F, Iteration++))
12274     EverMadeChange = true;
12275   return EverMadeChange;
12276 }
12277
12278 FunctionPass *llvm::createInstructionCombiningPass() {
12279   return new InstCombiner();
12280 }
12281
12282