Fix folding of icmp's of i1 where the comparison is signed. The code
[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     std::vector<Instruction*> 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((intptr_t)&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     Instruction *commonRemTransforms(BinaryOperator &I);
176     Instruction *commonIRemTransforms(BinaryOperator &I);
177     Instruction *commonDivTransforms(BinaryOperator &I);
178     Instruction *commonIDivTransforms(BinaryOperator &I);
179     Instruction *visitUDiv(BinaryOperator &I);
180     Instruction *visitSDiv(BinaryOperator &I);
181     Instruction *visitFDiv(BinaryOperator &I);
182     Instruction *visitAnd(BinaryOperator &I);
183     Instruction *visitOr (BinaryOperator &I);
184     Instruction *visitXor(BinaryOperator &I);
185     Instruction *visitShl(BinaryOperator &I);
186     Instruction *visitAShr(BinaryOperator &I);
187     Instruction *visitLShr(BinaryOperator &I);
188     Instruction *commonShiftTransforms(BinaryOperator &I);
189     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190                                       Constant *RHSC);
191     Instruction *visitFCmpInst(FCmpInst &I);
192     Instruction *visitICmpInst(ICmpInst &I);
193     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195                                                 Instruction *LHS,
196                                                 ConstantInt *RHS);
197     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198                                 ConstantInt *DivRHS);
199
200     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201                              ICmpInst::Predicate Cond, Instruction &I);
202     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203                                      BinaryOperator &I);
204     Instruction *commonCastTransforms(CastInst &CI);
205     Instruction *commonIntCastTransforms(CastInst &CI);
206     Instruction *commonPointerCastTransforms(CastInst &CI);
207     Instruction *visitTrunc(TruncInst &CI);
208     Instruction *visitZExt(ZExtInst &CI);
209     Instruction *visitSExt(SExtInst &CI);
210     Instruction *visitFPTrunc(FPTruncInst &CI);
211     Instruction *visitFPExt(CastInst &CI);
212     Instruction *visitFPToUI(FPToUIInst &FI);
213     Instruction *visitFPToSI(FPToSIInst &FI);
214     Instruction *visitUIToFP(CastInst &CI);
215     Instruction *visitSIToFP(CastInst &CI);
216     Instruction *visitPtrToInt(CastInst &CI);
217     Instruction *visitIntToPtr(IntToPtrInst &CI);
218     Instruction *visitBitCast(BitCastInst &CI);
219     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220                                 Instruction *FI);
221     Instruction *visitSelectInst(SelectInst &CI);
222     Instruction *visitCallInst(CallInst &CI);
223     Instruction *visitInvokeInst(InvokeInst &II);
224     Instruction *visitPHINode(PHINode &PN);
225     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226     Instruction *visitAllocationInst(AllocationInst &AI);
227     Instruction *visitFreeInst(FreeInst &FI);
228     Instruction *visitLoadInst(LoadInst &LI);
229     Instruction *visitStoreInst(StoreInst &SI);
230     Instruction *visitBranchInst(BranchInst &BI);
231     Instruction *visitSwitchInst(SwitchInst &SI);
232     Instruction *visitInsertElementInst(InsertElementInst &IE);
233     Instruction *visitExtractElementInst(ExtractElementInst &EI);
234     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235     Instruction *visitExtractValueInst(ExtractValueInst &EV);
236
237     // visitInstruction - Specify what to return for unhandled instructions...
238     Instruction *visitInstruction(Instruction &I) { return 0; }
239
240   private:
241     Instruction *visitCallSite(CallSite CS);
242     bool transformConstExprCastCall(CallSite CS);
243     Instruction *transformCallThroughTrampoline(CallSite CS);
244     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245                                    bool DoXform = true);
246     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247
248   public:
249     // InsertNewInstBefore - insert an instruction New before instruction Old
250     // in the program.  Add the new instruction to the worklist.
251     //
252     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253       assert(New && New->getParent() == 0 &&
254              "New instruction already inserted into a basic block!");
255       BasicBlock *BB = Old.getParent();
256       BB->getInstList().insert(&Old, New);  // Insert inst
257       AddToWorkList(New);
258       return New;
259     }
260
261     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262     /// This also adds the cast to the worklist.  Finally, this returns the
263     /// cast.
264     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265                             Instruction &Pos) {
266       if (V->getType() == Ty) return V;
267
268       if (Constant *CV = dyn_cast<Constant>(V))
269         return ConstantExpr::getCast(opc, CV, Ty);
270       
271       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
272       AddToWorkList(C);
273       return C;
274     }
275         
276     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278     }
279
280
281     // ReplaceInstUsesWith - This method is to be used when an instruction is
282     // found to be dead, replacable with another preexisting expression.  Here
283     // we add all uses of I to the worklist, replace all uses of I with the new
284     // value, then return I, so that the inst combiner will know that I was
285     // modified.
286     //
287     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288       AddUsersToWorkList(I);         // Add all modified instrs to worklist
289       if (&I != V) {
290         I.replaceAllUsesWith(V);
291         return &I;
292       } else {
293         // If we are replacing the instruction with itself, this must be in a
294         // segment of unreachable code, so just clobber the instruction.
295         I.replaceAllUsesWith(UndefValue::get(I.getType()));
296         return &I;
297       }
298     }
299
300     // UpdateValueUsesWith - This method is to be used when an value is
301     // found to be replacable with another preexisting expression or was
302     // updated.  Here we add all uses of I to the worklist, replace all uses of
303     // I with the new value (unless the instruction was just updated), then
304     // return true, so that the inst combiner will know that I was modified.
305     //
306     bool UpdateValueUsesWith(Value *Old, Value *New) {
307       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
308       if (Old != New)
309         Old->replaceAllUsesWith(New);
310       if (Instruction *I = dyn_cast<Instruction>(Old))
311         AddToWorkList(I);
312       if (Instruction *I = dyn_cast<Instruction>(New))
313         AddToWorkList(I);
314       return true;
315     }
316     
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
345     /// casts that are known to not do anything...
346     ///
347     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348                                    Value *V, const Type *DestTy,
349                                    Instruction *InsertBefore);
350
351     /// SimplifyCommutative - This performs a few simplifications for 
352     /// commutative operators.
353     bool SimplifyCommutative(BinaryOperator &I);
354
355     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356     /// most-complex to least-complex order.
357     bool SimplifyCompare(CmpInst &I);
358
359     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360     /// on the demanded bits.
361     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
362                               APInt& KnownZero, APInt& KnownOne,
363                               unsigned Depth = 0);
364
365     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366                                       uint64_t &UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
438 /// expression bitcast,  return the operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441     return I->getOperand(0);
442   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443     if (CE->getOpcode() == Instruction::BitCast)
444       return CE->getOperand(0);
445   return 0;
446 }
447
448 /// This function is a wrapper around CastInst::isEliminableCastPair. It
449 /// simply extracts arguments and returns what that function returns.
450 static Instruction::CastOps 
451 isEliminableCastPair(
452   const CastInst *CI, ///< The first cast instruction
453   unsigned opcode,       ///< The opcode of the second cast instruction
454   const Type *DstTy,     ///< The target type for the second cast instruction
455   TargetData *TD         ///< The target data for pointer size
456 ) {
457   
458   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
459   const Type *MidTy = CI->getType();                  // B from above
460
461   // Get the opcodes of the two Cast instructions
462   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
464
465   return Instruction::CastOps(
466       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467                                      DstTy, TD->getIntPtrType()));
468 }
469
470 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471 /// in any code being generated.  It does not require codegen if V is simple
472 /// enough or if the cast can be folded into other casts.
473 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
474                               const Type *Ty, TargetData *TD) {
475   if (V->getType() == Ty || isa<Constant>(V)) return false;
476   
477   // If this is another cast that can be eliminated, it isn't codegen either.
478   if (const CastInst *CI = dyn_cast<CastInst>(V))
479     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
480       return false;
481   return true;
482 }
483
484 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
486 /// casts that are known to not do anything...
487 ///
488 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489                                              Value *V, const Type *DestTy,
490                                              Instruction *InsertBefore) {
491   if (V->getType() == DestTy) return V;
492   if (Constant *C = dyn_cast<Constant>(V))
493     return ConstantExpr::getCast(opcode, C, DestTy);
494   
495   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
496 }
497
498 // SimplifyCommutative - This performs a few simplifications for commutative
499 // operators:
500 //
501 //  1. Order operands such that they are listed from right (least complex) to
502 //     left (most complex).  This puts constants before unary operators before
503 //     binary operators.
504 //
505 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507 //
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509   bool Changed = false;
510   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511     Changed = !I.swapOperands();
512
513   if (!I.isAssociative()) return Changed;
514   Instruction::BinaryOps Opcode = I.getOpcode();
515   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517       if (isa<Constant>(I.getOperand(1))) {
518         Constant *Folded = ConstantExpr::get(I.getOpcode(),
519                                              cast<Constant>(I.getOperand(1)),
520                                              cast<Constant>(Op->getOperand(1)));
521         I.setOperand(0, Op->getOperand(0));
522         I.setOperand(1, Folded);
523         return true;
524       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526             isOnlyUse(Op) && isOnlyUse(Op1)) {
527           Constant *C1 = cast<Constant>(Op->getOperand(1));
528           Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
532           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
533                                                     Op1->getOperand(0),
534                                                     Op1->getName(), &I);
535           AddToWorkList(New);
536           I.setOperand(0, New);
537           I.setOperand(1, Folded);
538           return true;
539         }
540     }
541   return Changed;
542 }
543
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549     return false;
550   I.swapOperands();
551   // Compare instructions are not associative so there's nothing else we can do.
552   return true;
553 }
554
555 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556 // if the LHS is a constant zero (which is the 'negate' form).
557 //
558 static inline Value *dyn_castNegVal(Value *V) {
559   if (BinaryOperator::isNeg(V))
560     return BinaryOperator::getNegArgument(V);
561
562   // Constants can be considered to be negated values if they can be folded.
563   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564     return ConstantExpr::getNeg(C);
565
566   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567     if (C->getType()->getElementType()->isInteger())
568       return ConstantExpr::getNeg(C);
569
570   return 0;
571 }
572
573 static inline Value *dyn_castNotVal(Value *V) {
574   if (BinaryOperator::isNot(V))
575     return BinaryOperator::getNotArgument(V);
576
577   // Constants can be considered to be not'ed values...
578   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579     return ConstantInt::get(~C->getValue());
580   return 0;
581 }
582
583 // dyn_castFoldableMul - If this value is a multiply that can be folded into
584 // other computations (because it has a constant operand), return the
585 // non-constant operand of the multiply, and set CST to point to the multiplier.
586 // Otherwise, return null.
587 //
588 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589   if (V->hasOneUse() && V->getType()->isInteger())
590     if (Instruction *I = dyn_cast<Instruction>(V)) {
591       if (I->getOpcode() == Instruction::Mul)
592         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593           return I->getOperand(0);
594       if (I->getOpcode() == Instruction::Shl)
595         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596           // The multiplier is really 1 << CST.
597           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600           return I->getOperand(0);
601         }
602     }
603   return 0;
604 }
605
606 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607 /// expression, return it.
608 static User *dyn_castGetElementPtr(Value *V) {
609   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611     if (CE->getOpcode() == Instruction::GetElementPtr)
612       return cast<User>(V);
613   return false;
614 }
615
616 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
617 /// opcode value. Otherwise return UserOp1.
618 static unsigned getOpcode(const Value *V) {
619   if (const Instruction *I = dyn_cast<Instruction>(V))
620     return I->getOpcode();
621   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
622     return CE->getOpcode();
623   // Use UserOp1 to mean there's no opcode.
624   return Instruction::UserOp1;
625 }
626
627 /// AddOne - Add one to a ConstantInt
628 static ConstantInt *AddOne(ConstantInt *C) {
629   APInt Val(C->getValue());
630   return ConstantInt::get(++Val);
631 }
632 /// SubOne - Subtract one from a ConstantInt
633 static ConstantInt *SubOne(ConstantInt *C) {
634   APInt Val(C->getValue());
635   return ConstantInt::get(--Val);
636 }
637 /// Add - Add two ConstantInts together
638 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() + C2->getValue());
640 }
641 /// And - Bitwise AND two ConstantInts together
642 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() & C2->getValue());
644 }
645 /// Subtract - Subtract one ConstantInt from another
646 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() - C2->getValue());
648 }
649 /// Multiply - Multiply two ConstantInts together
650 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651   return ConstantInt::get(C1->getValue() * C2->getValue());
652 }
653 /// MultiplyOverflows - True if the multiply can not be expressed in an int
654 /// this size.
655 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656   uint32_t W = C1->getBitWidth();
657   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658   if (sign) {
659     LHSExt.sext(W * 2);
660     RHSExt.sext(W * 2);
661   } else {
662     LHSExt.zext(W * 2);
663     RHSExt.zext(W * 2);
664   }
665
666   APInt MulExt = LHSExt * RHSExt;
667
668   if (sign) {
669     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671     return MulExt.slt(Min) || MulExt.sgt(Max);
672   } else 
673     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674 }
675
676
677 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
678 /// specified instruction is a constant integer.  If so, check to see if there
679 /// are any bits set in the constant that are not demanded.  If so, shrink the
680 /// constant and return true.
681 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
682                                    APInt Demanded) {
683   assert(I && "No instruction?");
684   assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686   // If the operand is not a constant integer, nothing to do.
687   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688   if (!OpC) return false;
689
690   // If there are no bits set that aren't demanded, nothing to do.
691   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692   if ((~Demanded & OpC->getValue()) == 0)
693     return false;
694
695   // This instruction is producing bits that are not demanded. Shrink the RHS.
696   Demanded &= OpC->getValue();
697   I->setOperand(OpNo, ConstantInt::get(Demanded));
698   return true;
699 }
700
701 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
702 // set of known zero and one bits, compute the maximum and minimum values that
703 // could have the specified known zero and known one bits, returning them in
704 // min/max.
705 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706                                                    const APInt& KnownZero,
707                                                    const APInt& KnownOne,
708                                                    APInt& Min, APInt& Max) {
709   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710   assert(KnownZero.getBitWidth() == BitWidth && 
711          KnownOne.getBitWidth() == BitWidth &&
712          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714   APInt UnknownBits = ~(KnownZero|KnownOne);
715
716   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717   // bit if it is unknown.
718   Min = KnownOne;
719   Max = KnownOne|UnknownBits;
720   
721   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
722     Min.set(BitWidth-1);
723     Max.clear(BitWidth-1);
724   }
725 }
726
727 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728 // a set of known zero and one bits, compute the maximum and minimum values that
729 // could have the specified known zero and known one bits, returning them in
730 // min/max.
731 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
732                                                      const APInt &KnownZero,
733                                                      const APInt &KnownOne,
734                                                      APInt &Min, APInt &Max) {
735   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
736   assert(KnownZero.getBitWidth() == BitWidth && 
737          KnownOne.getBitWidth() == BitWidth &&
738          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740   APInt UnknownBits = ~(KnownZero|KnownOne);
741   
742   // The minimum value is when the unknown bits are all zeros.
743   Min = KnownOne;
744   // The maximum value is when the unknown bits are all ones.
745   Max = KnownOne|UnknownBits;
746 }
747
748 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
749 /// value based on the demanded bits. When this function is called, it is known
750 /// that only the bits set in DemandedMask of the result of V are ever used
751 /// downstream. Consequently, depending on the mask and V, it may be possible
752 /// to replace V with a constant or one of its operands. In such cases, this
753 /// function does the replacement and returns true. In all other cases, it
754 /// returns false after analyzing the expression and setting KnownOne and known
755 /// to be one in the expression. KnownZero contains all the bits that are known
756 /// to be zero in the expression. These are provided to potentially allow the
757 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758 /// the expression. KnownOne and KnownZero always follow the invariant that 
759 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
761 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762 /// and KnownOne must all be the same.
763 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764                                         APInt& KnownZero, APInt& KnownOne,
765                                         unsigned Depth) {
766   assert(V != 0 && "Null pointer of Value???");
767   assert(Depth <= 6 && "Limit Search Depth");
768   uint32_t BitWidth = DemandedMask.getBitWidth();
769   const IntegerType *VTy = cast<IntegerType>(V->getType());
770   assert(VTy->getBitWidth() == BitWidth && 
771          KnownZero.getBitWidth() == BitWidth && 
772          KnownOne.getBitWidth() == BitWidth &&
773          "Value *V, DemandedMask, KnownZero and KnownOne \
774           must have same BitWidth");
775   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776     // We know all of the bits for a constant!
777     KnownOne = CI->getValue() & DemandedMask;
778     KnownZero = ~KnownOne & DemandedMask;
779     return false;
780   }
781   
782   KnownZero.clear(); 
783   KnownOne.clear();
784   if (!V->hasOneUse()) {    // Other users may use these bits.
785     if (Depth != 0) {       // Not at the root.
786       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788       return false;
789     }
790     // If this is the root being simplified, allow it to have multiple uses,
791     // just set the DemandedMask to all bits.
792     DemandedMask = APInt::getAllOnesValue(BitWidth);
793   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
794     if (V != UndefValue::get(VTy))
795       return UpdateValueUsesWith(V, UndefValue::get(VTy));
796     return false;
797   } else if (Depth == 6) {        // Limit search depth.
798     return false;
799   }
800   
801   Instruction *I = dyn_cast<Instruction>(V);
802   if (!I) return false;        // Only analyze instructions.
803
804   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806   switch (I->getOpcode()) {
807   default:
808     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809     break;
810   case Instruction::And:
811     // If either the LHS or the RHS are Zero, the result is zero.
812     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813                              RHSKnownZero, RHSKnownOne, Depth+1))
814       return true;
815     assert((RHSKnownZero & RHSKnownOne) == 0 && 
816            "Bits known to be one AND zero?"); 
817
818     // If something is known zero on the RHS, the bits aren't demanded on the
819     // LHS.
820     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821                              LHSKnownZero, LHSKnownOne, Depth+1))
822       return true;
823     assert((LHSKnownZero & LHSKnownOne) == 0 && 
824            "Bits known to be one AND zero?"); 
825
826     // If all of the demanded bits are known 1 on one side, return the other.
827     // These bits cannot contribute to the result of the 'and'.
828     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
829         (DemandedMask & ~LHSKnownZero))
830       return UpdateValueUsesWith(I, I->getOperand(0));
831     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
832         (DemandedMask & ~RHSKnownZero))
833       return UpdateValueUsesWith(I, I->getOperand(1));
834     
835     // If all of the demanded bits in the inputs are known zeros, return zero.
836     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838       
839     // If the RHS is a constant, see if we can simplify it.
840     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841       return UpdateValueUsesWith(I, I);
842       
843     // Output known-1 bits are only known if set in both the LHS & RHS.
844     RHSKnownOne &= LHSKnownOne;
845     // Output known-0 are known to be clear if zero in either the LHS | RHS.
846     RHSKnownZero |= LHSKnownZero;
847     break;
848   case Instruction::Or:
849     // If either the LHS or the RHS are One, the result is One.
850     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
851                              RHSKnownZero, RHSKnownOne, Depth+1))
852       return true;
853     assert((RHSKnownZero & RHSKnownOne) == 0 && 
854            "Bits known to be one AND zero?"); 
855     // If something is known one on the RHS, the bits aren't demanded on the
856     // LHS.
857     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
858                              LHSKnownZero, LHSKnownOne, Depth+1))
859       return true;
860     assert((LHSKnownZero & LHSKnownOne) == 0 && 
861            "Bits known to be one AND zero?"); 
862     
863     // If all of the demanded bits are known zero on one side, return the other.
864     // These bits cannot contribute to the result of the 'or'.
865     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
866         (DemandedMask & ~LHSKnownOne))
867       return UpdateValueUsesWith(I, I->getOperand(0));
868     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
869         (DemandedMask & ~RHSKnownOne))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871
872     // If all of the potentially set bits on one side are known to be set on
873     // the other side, just use the 'other' side.
874     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
875         (DemandedMask & (~RHSKnownZero)))
876       return UpdateValueUsesWith(I, I->getOperand(0));
877     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
878         (DemandedMask & (~LHSKnownZero)))
879       return UpdateValueUsesWith(I, I->getOperand(1));
880         
881     // If the RHS is a constant, see if we can simplify it.
882     if (ShrinkDemandedConstant(I, 1, DemandedMask))
883       return UpdateValueUsesWith(I, I);
884           
885     // Output known-0 bits are only known if clear in both the LHS & RHS.
886     RHSKnownZero &= LHSKnownZero;
887     // Output known-1 are known to be set if set in either the LHS | RHS.
888     RHSKnownOne |= LHSKnownOne;
889     break;
890   case Instruction::Xor: {
891     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892                              RHSKnownZero, RHSKnownOne, Depth+1))
893       return true;
894     assert((RHSKnownZero & RHSKnownOne) == 0 && 
895            "Bits known to be one AND zero?"); 
896     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
897                              LHSKnownZero, LHSKnownOne, Depth+1))
898       return true;
899     assert((LHSKnownZero & LHSKnownOne) == 0 && 
900            "Bits known to be one AND zero?"); 
901     
902     // If all of the demanded bits are known zero on one side, return the other.
903     // These bits cannot contribute to the result of the 'xor'.
904     if ((DemandedMask & RHSKnownZero) == DemandedMask)
905       return UpdateValueUsesWith(I, I->getOperand(0));
906     if ((DemandedMask & LHSKnownZero) == DemandedMask)
907       return UpdateValueUsesWith(I, I->getOperand(1));
908     
909     // Output known-0 bits are known if clear or set in both the LHS & RHS.
910     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
911                          (RHSKnownOne & LHSKnownOne);
912     // Output known-1 are known to be set if set in only one of the LHS, RHS.
913     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
914                         (RHSKnownOne & LHSKnownZero);
915     
916     // If all of the demanded bits are known to be zero on one side or the
917     // other, turn this into an *inclusive* or.
918     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920       Instruction *Or =
921         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
922                                  I->getName());
923       InsertNewInstBefore(Or, *I);
924       return UpdateValueUsesWith(I, Or);
925     }
926     
927     // If all of the demanded bits on one side are known, and all of the set
928     // bits on that side are also known to be set on the other side, turn this
929     // into an AND, as we know the bits will be cleared.
930     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
932       // all known
933       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935         Instruction *And = 
936           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
937         InsertNewInstBefore(And, *I);
938         return UpdateValueUsesWith(I, And);
939       }
940     }
941     
942     // If the RHS is a constant, see if we can simplify it.
943     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944     if (ShrinkDemandedConstant(I, 1, DemandedMask))
945       return UpdateValueUsesWith(I, I);
946     
947     RHSKnownZero = KnownZeroOut;
948     RHSKnownOne  = KnownOneOut;
949     break;
950   }
951   case Instruction::Select:
952     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953                              RHSKnownZero, RHSKnownOne, Depth+1))
954       return true;
955     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
956                              LHSKnownZero, LHSKnownOne, Depth+1))
957       return true;
958     assert((RHSKnownZero & RHSKnownOne) == 0 && 
959            "Bits known to be one AND zero?"); 
960     assert((LHSKnownZero & LHSKnownOne) == 0 && 
961            "Bits known to be one AND zero?"); 
962     
963     // If the operands are constants, see if we can simplify them.
964     if (ShrinkDemandedConstant(I, 1, DemandedMask))
965       return UpdateValueUsesWith(I, I);
966     if (ShrinkDemandedConstant(I, 2, DemandedMask))
967       return UpdateValueUsesWith(I, I);
968     
969     // Only known if known in both the LHS and RHS.
970     RHSKnownOne &= LHSKnownOne;
971     RHSKnownZero &= LHSKnownZero;
972     break;
973   case Instruction::Trunc: {
974     uint32_t truncBf = 
975       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976     DemandedMask.zext(truncBf);
977     RHSKnownZero.zext(truncBf);
978     RHSKnownOne.zext(truncBf);
979     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
980                              RHSKnownZero, RHSKnownOne, Depth+1))
981       return true;
982     DemandedMask.trunc(BitWidth);
983     RHSKnownZero.trunc(BitWidth);
984     RHSKnownOne.trunc(BitWidth);
985     assert((RHSKnownZero & RHSKnownOne) == 0 && 
986            "Bits known to be one AND zero?"); 
987     break;
988   }
989   case Instruction::BitCast:
990     if (!I->getOperand(0)->getType()->isInteger())
991       return false;
992       
993     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994                              RHSKnownZero, RHSKnownOne, Depth+1))
995       return true;
996     assert((RHSKnownZero & RHSKnownOne) == 0 && 
997            "Bits known to be one AND zero?"); 
998     break;
999   case Instruction::ZExt: {
1000     // Compute the bits in the result that are not present in the input.
1001     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1003     
1004     DemandedMask.trunc(SrcBitWidth);
1005     RHSKnownZero.trunc(SrcBitWidth);
1006     RHSKnownOne.trunc(SrcBitWidth);
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              RHSKnownZero, RHSKnownOne, Depth+1))
1009       return true;
1010     DemandedMask.zext(BitWidth);
1011     RHSKnownZero.zext(BitWidth);
1012     RHSKnownOne.zext(BitWidth);
1013     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1014            "Bits known to be one AND zero?"); 
1015     // The top bits are known to be zero.
1016     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1017     break;
1018   }
1019   case Instruction::SExt: {
1020     // Compute the bits in the result that are not present in the input.
1021     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1023     
1024     APInt InputDemandedBits = DemandedMask & 
1025                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1026
1027     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028     // If any of the sign extended bits are demanded, we know that the sign
1029     // bit is demanded.
1030     if ((NewBits & DemandedMask) != 0)
1031       InputDemandedBits.set(SrcBitWidth-1);
1032       
1033     InputDemandedBits.trunc(SrcBitWidth);
1034     RHSKnownZero.trunc(SrcBitWidth);
1035     RHSKnownOne.trunc(SrcBitWidth);
1036     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037                              RHSKnownZero, RHSKnownOne, Depth+1))
1038       return true;
1039     InputDemandedBits.zext(BitWidth);
1040     RHSKnownZero.zext(BitWidth);
1041     RHSKnownOne.zext(BitWidth);
1042     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1043            "Bits known to be one AND zero?"); 
1044       
1045     // If the sign bit of the input is known set or clear, then we know the
1046     // top bits of the result.
1047
1048     // If the input sign bit is known zero, or if the NewBits are not demanded
1049     // convert this into a zero extension.
1050     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1051     {
1052       // Convert to ZExt cast
1053       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054       return UpdateValueUsesWith(I, NewCast);
1055     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1056       RHSKnownOne |= NewBits;
1057     }
1058     break;
1059   }
1060   case Instruction::Add: {
1061     // Figure out what the input bits are.  If the top bits of the and result
1062     // are not demanded, then the add doesn't demand them from its input
1063     // either.
1064     uint32_t NLZ = DemandedMask.countLeadingZeros();
1065       
1066     // If there is a constant on the RHS, there are a variety of xformations
1067     // we can do.
1068     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069       // If null, this should be simplified elsewhere.  Some of the xforms here
1070       // won't work if the RHS is zero.
1071       if (RHS->isZero())
1072         break;
1073       
1074       // If the top bit of the output is demanded, demand everything from the
1075       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1076       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1077
1078       // Find information about known zero/one bits in the input.
1079       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1080                                LHSKnownZero, LHSKnownOne, Depth+1))
1081         return true;
1082
1083       // If the RHS of the add has bits set that can't affect the input, reduce
1084       // the constant.
1085       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086         return UpdateValueUsesWith(I, I);
1087       
1088       // Avoid excess work.
1089       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090         break;
1091       
1092       // Turn it into OR if input bits are zero.
1093       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094         Instruction *Or =
1095           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1096                                    I->getName());
1097         InsertNewInstBefore(Or, *I);
1098         return UpdateValueUsesWith(I, Or);
1099       }
1100       
1101       // We can say something about the output known-zero and known-one bits,
1102       // depending on potential carries from the input constant and the
1103       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1104       // bits set and the RHS constant is 0x01001, then we know we have a known
1105       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106       
1107       // To compute this, we first compute the potential carry bits.  These are
1108       // the bits which may be modified.  I'm not aware of a better way to do
1109       // this scan.
1110       const APInt& RHSVal = RHS->getValue();
1111       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1112       
1113       // Now that we know which bits have carries, compute the known-1/0 sets.
1114       
1115       // Bits are known one if they are known zero in one operand and one in the
1116       // other, and there is no input carry.
1117       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1118                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119       
1120       // Bits are known zero if they are known zero in both operands and there
1121       // is no input carry.
1122       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123     } else {
1124       // If the high-bits of this ADD are not demanded, then it does not demand
1125       // the high bits of its LHS or RHS.
1126       if (DemandedMask[BitWidth-1] == 0) {
1127         // Right fill the mask of bits for this ADD to demand the most
1128         // significant bit and all those below it.
1129         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131                                  LHSKnownZero, LHSKnownOne, Depth+1))
1132           return true;
1133         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134                                  LHSKnownZero, LHSKnownOne, Depth+1))
1135           return true;
1136       }
1137     }
1138     break;
1139   }
1140   case Instruction::Sub:
1141     // If the high-bits of this SUB are not demanded, then it does not demand
1142     // the high bits of its LHS or RHS.
1143     if (DemandedMask[BitWidth-1] == 0) {
1144       // Right fill the mask of bits for this SUB to demand the most
1145       // significant bit and all those below it.
1146       uint32_t NLZ = DemandedMask.countLeadingZeros();
1147       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149                                LHSKnownZero, LHSKnownOne, Depth+1))
1150         return true;
1151       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152                                LHSKnownZero, LHSKnownOne, Depth+1))
1153         return true;
1154     }
1155     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156     // the known zeros and ones.
1157     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1158     break;
1159   case Instruction::Shl:
1160     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1164                                RHSKnownZero, RHSKnownOne, Depth+1))
1165         return true;
1166       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1167              "Bits known to be one AND zero?"); 
1168       RHSKnownZero <<= ShiftAmt;
1169       RHSKnownOne  <<= ShiftAmt;
1170       // low bits known zero.
1171       if (ShiftAmt)
1172         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1173     }
1174     break;
1175   case Instruction::LShr:
1176     // For a logical shift right
1177     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1179       
1180       // Unsigned shift right.
1181       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183                                RHSKnownZero, RHSKnownOne, Depth+1))
1184         return true;
1185       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1186              "Bits known to be one AND zero?"); 
1187       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1189       if (ShiftAmt) {
1190         // Compute the new bits that are at the top now.
1191         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192         RHSKnownZero |= HighBits;  // high bits known zero.
1193       }
1194     }
1195     break;
1196   case Instruction::AShr:
1197     // If this is an arithmetic shift right and only the low-bit is set, we can
1198     // always convert this into a logical shr, even if the shift amount is
1199     // variable.  The low bit of the shift cannot be an input sign bit unless
1200     // the shift amount is >= the size of the datatype, which is undefined.
1201     if (DemandedMask == 1) {
1202       // Perform the logical shift right.
1203       Value *NewVal = BinaryOperator::CreateLShr(
1204                         I->getOperand(0), I->getOperand(1), I->getName());
1205       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206       return UpdateValueUsesWith(I, NewVal);
1207     }    
1208
1209     // If the sign bit is the only bit demanded by this ashr, then there is no
1210     // need to do it, the shift doesn't change the high bit.
1211     if (DemandedMask.isSignBit())
1212       return UpdateValueUsesWith(I, I->getOperand(0));
1213     
1214     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1216       
1217       // Signed shift right.
1218       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219       // If any of the "high bits" are demanded, we should set the sign bit as
1220       // demanded.
1221       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222         DemandedMaskIn.set(BitWidth-1);
1223       if (SimplifyDemandedBits(I->getOperand(0),
1224                                DemandedMaskIn,
1225                                RHSKnownZero, RHSKnownOne, Depth+1))
1226         return true;
1227       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1228              "Bits known to be one AND zero?"); 
1229       // Compute the new bits that are at the top now.
1230       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233         
1234       // Handle the sign bits.
1235       APInt SignBit(APInt::getSignBit(BitWidth));
1236       // Adjust to where it is now in the mask.
1237       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1238         
1239       // If the input sign bit is known to be zero, or if none of the top bits
1240       // are demanded, turn this into an unsigned shift right.
1241       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1242           (HighBits & ~DemandedMask) == HighBits) {
1243         // Perform the logical shift right.
1244         Value *NewVal = BinaryOperator::CreateLShr(
1245                           I->getOperand(0), SA, I->getName());
1246         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247         return UpdateValueUsesWith(I, NewVal);
1248       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249         RHSKnownOne |= HighBits;
1250       }
1251     }
1252     break;
1253   case Instruction::SRem:
1254     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255       APInt RA = Rem->getValue();
1256       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1257         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1258         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260                                  LHSKnownZero, LHSKnownOne, Depth+1))
1261           return true;
1262
1263         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264           LHSKnownZero |= ~LowBits;
1265         else if (LHSKnownOne[BitWidth-1])
1266           LHSKnownOne |= ~LowBits;
1267
1268         KnownZero |= LHSKnownZero & DemandedMask;
1269         KnownOne |= LHSKnownOne & DemandedMask;
1270
1271         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1272       }
1273     }
1274     break;
1275   case Instruction::URem: {
1276     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277       APInt RA = Rem->getValue();
1278       if (RA.isPowerOf2()) {
1279         APInt LowBits = (RA - 1);
1280         APInt Mask2 = LowBits & DemandedMask;
1281         KnownZero |= ~LowBits & DemandedMask;
1282         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283                                  KnownZero, KnownOne, Depth+1))
1284           return true;
1285
1286         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1287         break;
1288       }
1289     }
1290
1291     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1293     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294                              KnownZero2, KnownOne2, Depth+1))
1295       return true;
1296
1297     uint32_t Leaders = KnownZero2.countLeadingOnes();
1298     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1299                              KnownZero2, KnownOne2, Depth+1))
1300       return true;
1301
1302     Leaders = std::max(Leaders,
1303                        KnownZero2.countLeadingOnes());
1304     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1305     break;
1306   }
1307   case Instruction::Call:
1308     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309       switch (II->getIntrinsicID()) {
1310       default: break;
1311       case Intrinsic::bswap: {
1312         // If the only bits demanded come from one byte of the bswap result,
1313         // just shift the input byte into position to eliminate the bswap.
1314         unsigned NLZ = DemandedMask.countLeadingZeros();
1315         unsigned NTZ = DemandedMask.countTrailingZeros();
1316           
1317         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1318         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1319         // have 14 leading zeros, round to 8.
1320         NLZ &= ~7;
1321         NTZ &= ~7;
1322         // If we need exactly one byte, we can do this transformation.
1323         if (BitWidth-NLZ-NTZ == 8) {
1324           unsigned ResultBit = NTZ;
1325           unsigned InputBit = BitWidth-NTZ-8;
1326           
1327           // Replace this with either a left or right shift to get the byte into
1328           // the right place.
1329           Instruction *NewVal;
1330           if (InputBit > ResultBit)
1331             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1333           else
1334             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1336           NewVal->takeName(I);
1337           InsertNewInstBefore(NewVal, *I);
1338           return UpdateValueUsesWith(I, NewVal);
1339         }
1340           
1341         // TODO: Could compute known zero/one bits based on the input.
1342         break;
1343       }
1344       }
1345     }
1346     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1347     break;
1348   }
1349   
1350   // If the client is only demanding bits that we know, return the known
1351   // constant.
1352   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1353     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1354   return false;
1355 }
1356
1357
1358 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1359 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1360 /// actually used by the caller.  This method analyzes which elements of the
1361 /// operand are undef and returns that information in UndefElts.
1362 ///
1363 /// If the information about demanded elements can be used to simplify the
1364 /// operation, the operation is simplified, then the resultant value is
1365 /// returned.  This returns null if no change was made.
1366 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1367                                                 uint64_t &UndefElts,
1368                                                 unsigned Depth) {
1369   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1370   assert(VWidth <= 64 && "Vector too wide to analyze!");
1371   uint64_t EltMask = ~0ULL >> (64-VWidth);
1372   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1373          "Invalid DemandedElts!");
1374
1375   if (isa<UndefValue>(V)) {
1376     // If the entire vector is undefined, just return this info.
1377     UndefElts = EltMask;
1378     return 0;
1379   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1380     UndefElts = EltMask;
1381     return UndefValue::get(V->getType());
1382   }
1383   
1384   UndefElts = 0;
1385   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1386     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1387     Constant *Undef = UndefValue::get(EltTy);
1388
1389     std::vector<Constant*> Elts;
1390     for (unsigned i = 0; i != VWidth; ++i)
1391       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1392         Elts.push_back(Undef);
1393         UndefElts |= (1ULL << i);
1394       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1395         Elts.push_back(Undef);
1396         UndefElts |= (1ULL << i);
1397       } else {                               // Otherwise, defined.
1398         Elts.push_back(CP->getOperand(i));
1399       }
1400         
1401     // If we changed the constant, return it.
1402     Constant *NewCP = ConstantVector::get(Elts);
1403     return NewCP != CP ? NewCP : 0;
1404   } else if (isa<ConstantAggregateZero>(V)) {
1405     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1406     // set to undef.
1407     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1408     Constant *Zero = Constant::getNullValue(EltTy);
1409     Constant *Undef = UndefValue::get(EltTy);
1410     std::vector<Constant*> Elts;
1411     for (unsigned i = 0; i != VWidth; ++i)
1412       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1413     UndefElts = DemandedElts ^ EltMask;
1414     return ConstantVector::get(Elts);
1415   }
1416   
1417   if (!V->hasOneUse()) {    // Other users may use these bits.
1418     if (Depth != 0) {       // Not at the root.
1419       // TODO: Just compute the UndefElts information recursively.
1420       return false;
1421     }
1422     return false;
1423   } else if (Depth == 10) {        // Limit search depth.
1424     return false;
1425   }
1426   
1427   Instruction *I = dyn_cast<Instruction>(V);
1428   if (!I) return false;        // Only analyze instructions.
1429   
1430   bool MadeChange = false;
1431   uint64_t UndefElts2;
1432   Value *TmpV;
1433   switch (I->getOpcode()) {
1434   default: break;
1435     
1436   case Instruction::InsertElement: {
1437     // If this is a variable index, we don't know which element it overwrites.
1438     // demand exactly the same input as we produce.
1439     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1440     if (Idx == 0) {
1441       // Note that we can't propagate undef elt info, because we don't know
1442       // which elt is getting updated.
1443       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1444                                         UndefElts2, Depth+1);
1445       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1446       break;
1447     }
1448     
1449     // If this is inserting an element that isn't demanded, remove this
1450     // insertelement.
1451     unsigned IdxNo = Idx->getZExtValue();
1452     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1453       return AddSoonDeadInstToWorklist(*I, 0);
1454     
1455     // Otherwise, the element inserted overwrites whatever was there, so the
1456     // input demanded set is simpler than the output set.
1457     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1458                                       DemandedElts & ~(1ULL << IdxNo),
1459                                       UndefElts, Depth+1);
1460     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1461
1462     // The inserted element is defined.
1463     UndefElts |= 1ULL << IdxNo;
1464     break;
1465   }
1466   case Instruction::BitCast: {
1467     // Vector->vector casts only.
1468     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1469     if (!VTy) break;
1470     unsigned InVWidth = VTy->getNumElements();
1471     uint64_t InputDemandedElts = 0;
1472     unsigned Ratio;
1473
1474     if (VWidth == InVWidth) {
1475       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1476       // elements as are demanded of us.
1477       Ratio = 1;
1478       InputDemandedElts = DemandedElts;
1479     } else if (VWidth > InVWidth) {
1480       // Untested so far.
1481       break;
1482       
1483       // If there are more elements in the result than there are in the source,
1484       // then an input element is live if any of the corresponding output
1485       // elements are live.
1486       Ratio = VWidth/InVWidth;
1487       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1488         if (DemandedElts & (1ULL << OutIdx))
1489           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1490       }
1491     } else {
1492       // Untested so far.
1493       break;
1494       
1495       // If there are more elements in the source than there are in the result,
1496       // then an input element is live if the corresponding output element is
1497       // live.
1498       Ratio = InVWidth/VWidth;
1499       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1500         if (DemandedElts & (1ULL << InIdx/Ratio))
1501           InputDemandedElts |= 1ULL << InIdx;
1502     }
1503     
1504     // div/rem demand all inputs, because they don't want divide by zero.
1505     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1506                                       UndefElts2, Depth+1);
1507     if (TmpV) {
1508       I->setOperand(0, TmpV);
1509       MadeChange = true;
1510     }
1511     
1512     UndefElts = UndefElts2;
1513     if (VWidth > InVWidth) {
1514       assert(0 && "Unimp");
1515       // If there are more elements in the result than there are in the source,
1516       // then an output element is undef if the corresponding input element is
1517       // undef.
1518       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1519         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1520           UndefElts |= 1ULL << OutIdx;
1521     } else if (VWidth < InVWidth) {
1522       assert(0 && "Unimp");
1523       // If there are more elements in the source than there are in the result,
1524       // then a result element is undef if all of the corresponding input
1525       // elements are undef.
1526       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1527       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1529           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1530     }
1531     break;
1532   }
1533   case Instruction::And:
1534   case Instruction::Or:
1535   case Instruction::Xor:
1536   case Instruction::Add:
1537   case Instruction::Sub:
1538   case Instruction::Mul:
1539     // div/rem demand all inputs, because they don't want divide by zero.
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1544                                       UndefElts2, Depth+1);
1545     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1546       
1547     // Output elements are undefined if both are undefined.  Consider things
1548     // like undef&0.  The result is known zero, not undef.
1549     UndefElts &= UndefElts2;
1550     break;
1551     
1552   case Instruction::Call: {
1553     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1554     if (!II) break;
1555     switch (II->getIntrinsicID()) {
1556     default: break;
1557       
1558     // Binary vector operations that work column-wise.  A dest element is a
1559     // function of the corresponding input elements from the two inputs.
1560     case Intrinsic::x86_sse_sub_ss:
1561     case Intrinsic::x86_sse_mul_ss:
1562     case Intrinsic::x86_sse_min_ss:
1563     case Intrinsic::x86_sse_max_ss:
1564     case Intrinsic::x86_sse2_sub_sd:
1565     case Intrinsic::x86_sse2_mul_sd:
1566     case Intrinsic::x86_sse2_min_sd:
1567     case Intrinsic::x86_sse2_max_sd:
1568       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1569                                         UndefElts, Depth+1);
1570       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1571       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1572                                         UndefElts2, Depth+1);
1573       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1574
1575       // If only the low elt is demanded and this is a scalarizable intrinsic,
1576       // scalarize it now.
1577       if (DemandedElts == 1) {
1578         switch (II->getIntrinsicID()) {
1579         default: break;
1580         case Intrinsic::x86_sse_sub_ss:
1581         case Intrinsic::x86_sse_mul_ss:
1582         case Intrinsic::x86_sse2_sub_sd:
1583         case Intrinsic::x86_sse2_mul_sd:
1584           // TODO: Lower MIN/MAX/ABS/etc
1585           Value *LHS = II->getOperand(1);
1586           Value *RHS = II->getOperand(2);
1587           // Extract the element as scalars.
1588           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1589           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1590           
1591           switch (II->getIntrinsicID()) {
1592           default: assert(0 && "Case stmts out of sync!");
1593           case Intrinsic::x86_sse_sub_ss:
1594           case Intrinsic::x86_sse2_sub_sd:
1595             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1596                                                         II->getName()), *II);
1597             break;
1598           case Intrinsic::x86_sse_mul_ss:
1599           case Intrinsic::x86_sse2_mul_sd:
1600             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1601                                                          II->getName()), *II);
1602             break;
1603           }
1604           
1605           Instruction *New =
1606             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1607                                       II->getName());
1608           InsertNewInstBefore(New, *II);
1609           AddSoonDeadInstToWorklist(*II, 0);
1610           return New;
1611         }            
1612       }
1613         
1614       // Output elements are undefined if both are undefined.  Consider things
1615       // like undef&0.  The result is known zero, not undef.
1616       UndefElts &= UndefElts2;
1617       break;
1618     }
1619     break;
1620   }
1621   }
1622   return MadeChange ? I : 0;
1623 }
1624
1625
1626 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1627 /// function is designed to check a chain of associative operators for a
1628 /// potential to apply a certain optimization.  Since the optimization may be
1629 /// applicable if the expression was reassociated, this checks the chain, then
1630 /// reassociates the expression as necessary to expose the optimization
1631 /// opportunity.  This makes use of a special Functor, which must define
1632 /// 'shouldApply' and 'apply' methods.
1633 ///
1634 template<typename Functor>
1635 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1636   unsigned Opcode = Root.getOpcode();
1637   Value *LHS = Root.getOperand(0);
1638
1639   // Quick check, see if the immediate LHS matches...
1640   if (F.shouldApply(LHS))
1641     return F.apply(Root);
1642
1643   // Otherwise, if the LHS is not of the same opcode as the root, return.
1644   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1645   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1646     // Should we apply this transform to the RHS?
1647     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1648
1649     // If not to the RHS, check to see if we should apply to the LHS...
1650     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1651       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1652       ShouldApply = true;
1653     }
1654
1655     // If the functor wants to apply the optimization to the RHS of LHSI,
1656     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1657     if (ShouldApply) {
1658       // Now all of the instructions are in the current basic block, go ahead
1659       // and perform the reassociation.
1660       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1661
1662       // First move the selected RHS to the LHS of the root...
1663       Root.setOperand(0, LHSI->getOperand(1));
1664
1665       // Make what used to be the LHS of the root be the user of the root...
1666       Value *ExtraOperand = TmpLHSI->getOperand(1);
1667       if (&Root == TmpLHSI) {
1668         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1669         return 0;
1670       }
1671       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1672       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1673       BasicBlock::iterator ARI = &Root; ++ARI;
1674       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1675       ARI = Root;
1676
1677       // Now propagate the ExtraOperand down the chain of instructions until we
1678       // get to LHSI.
1679       while (TmpLHSI != LHSI) {
1680         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1681         // Move the instruction to immediately before the chain we are
1682         // constructing to avoid breaking dominance properties.
1683         NextLHSI->moveBefore(ARI);
1684         ARI = NextLHSI;
1685
1686         Value *NextOp = NextLHSI->getOperand(1);
1687         NextLHSI->setOperand(1, ExtraOperand);
1688         TmpLHSI = NextLHSI;
1689         ExtraOperand = NextOp;
1690       }
1691
1692       // Now that the instructions are reassociated, have the functor perform
1693       // the transformation...
1694       return F.apply(Root);
1695     }
1696
1697     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1698   }
1699   return 0;
1700 }
1701
1702 namespace {
1703
1704 // AddRHS - Implements: X + X --> X << 1
1705 struct AddRHS {
1706   Value *RHS;
1707   AddRHS(Value *rhs) : RHS(rhs) {}
1708   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1709   Instruction *apply(BinaryOperator &Add) const {
1710     return BinaryOperator::CreateShl(Add.getOperand(0),
1711                                      ConstantInt::get(Add.getType(), 1));
1712   }
1713 };
1714
1715 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1716 //                 iff C1&C2 == 0
1717 struct AddMaskingAnd {
1718   Constant *C2;
1719   AddMaskingAnd(Constant *c) : C2(c) {}
1720   bool shouldApply(Value *LHS) const {
1721     ConstantInt *C1;
1722     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1723            ConstantExpr::getAnd(C1, C2)->isNullValue();
1724   }
1725   Instruction *apply(BinaryOperator &Add) const {
1726     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1727   }
1728 };
1729
1730 }
1731
1732 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1733                                              InstCombiner *IC) {
1734   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1735     if (Constant *SOC = dyn_cast<Constant>(SO))
1736       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1737
1738     return IC->InsertNewInstBefore(CastInst::Create(
1739           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1740   }
1741
1742   // Figure out if the constant is the left or the right argument.
1743   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1744   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1745
1746   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1747     if (ConstIsRHS)
1748       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1749     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1750   }
1751
1752   Value *Op0 = SO, *Op1 = ConstOperand;
1753   if (!ConstIsRHS)
1754     std::swap(Op0, Op1);
1755   Instruction *New;
1756   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1757     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1758   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1759     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1760                           SO->getName()+".cmp");
1761   else {
1762     assert(0 && "Unknown binary instruction type!");
1763     abort();
1764   }
1765   return IC->InsertNewInstBefore(New, I);
1766 }
1767
1768 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1769 // constant as the other operand, try to fold the binary operator into the
1770 // select arguments.  This also works for Cast instructions, which obviously do
1771 // not have a second operand.
1772 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1773                                      InstCombiner *IC) {
1774   // Don't modify shared select instructions
1775   if (!SI->hasOneUse()) return 0;
1776   Value *TV = SI->getOperand(1);
1777   Value *FV = SI->getOperand(2);
1778
1779   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1780     // Bool selects with constant operands can be folded to logical ops.
1781     if (SI->getType() == Type::Int1Ty) return 0;
1782
1783     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1784     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1785
1786     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1787                               SelectFalseVal);
1788   }
1789   return 0;
1790 }
1791
1792
1793 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1794 /// node as operand #0, see if we can fold the instruction into the PHI (which
1795 /// is only possible if all operands to the PHI are constants).
1796 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1797   PHINode *PN = cast<PHINode>(I.getOperand(0));
1798   unsigned NumPHIValues = PN->getNumIncomingValues();
1799   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1800
1801   // Check to see if all of the operands of the PHI are constants.  If there is
1802   // one non-constant value, remember the BB it is.  If there is more than one
1803   // or if *it* is a PHI, bail out.
1804   BasicBlock *NonConstBB = 0;
1805   for (unsigned i = 0; i != NumPHIValues; ++i)
1806     if (!isa<Constant>(PN->getIncomingValue(i))) {
1807       if (NonConstBB) return 0;  // More than one non-const value.
1808       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1809       NonConstBB = PN->getIncomingBlock(i);
1810       
1811       // If the incoming non-constant value is in I's block, we have an infinite
1812       // loop.
1813       if (NonConstBB == I.getParent())
1814         return 0;
1815     }
1816   
1817   // If there is exactly one non-constant value, we can insert a copy of the
1818   // operation in that block.  However, if this is a critical edge, we would be
1819   // inserting the computation one some other paths (e.g. inside a loop).  Only
1820   // do this if the pred block is unconditionally branching into the phi block.
1821   if (NonConstBB) {
1822     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1823     if (!BI || !BI->isUnconditional()) return 0;
1824   }
1825
1826   // Okay, we can do the transformation: create the new PHI node.
1827   PHINode *NewPN = PHINode::Create(I.getType(), "");
1828   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1829   InsertNewInstBefore(NewPN, *PN);
1830   NewPN->takeName(PN);
1831
1832   // Next, add all of the operands to the PHI.
1833   if (I.getNumOperands() == 2) {
1834     Constant *C = cast<Constant>(I.getOperand(1));
1835     for (unsigned i = 0; i != NumPHIValues; ++i) {
1836       Value *InV = 0;
1837       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1838         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1839           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1840         else
1841           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1842       } else {
1843         assert(PN->getIncomingBlock(i) == NonConstBB);
1844         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1845           InV = BinaryOperator::Create(BO->getOpcode(),
1846                                        PN->getIncomingValue(i), C, "phitmp",
1847                                        NonConstBB->getTerminator());
1848         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1849           InV = CmpInst::Create(CI->getOpcode(), 
1850                                 CI->getPredicate(),
1851                                 PN->getIncomingValue(i), C, "phitmp",
1852                                 NonConstBB->getTerminator());
1853         else
1854           assert(0 && "Unknown binop!");
1855         
1856         AddToWorkList(cast<Instruction>(InV));
1857       }
1858       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1859     }
1860   } else { 
1861     CastInst *CI = cast<CastInst>(&I);
1862     const Type *RetTy = CI->getType();
1863     for (unsigned i = 0; i != NumPHIValues; ++i) {
1864       Value *InV;
1865       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1866         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1867       } else {
1868         assert(PN->getIncomingBlock(i) == NonConstBB);
1869         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1870                                I.getType(), "phitmp", 
1871                                NonConstBB->getTerminator());
1872         AddToWorkList(cast<Instruction>(InV));
1873       }
1874       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1875     }
1876   }
1877   return ReplaceInstUsesWith(I, NewPN);
1878 }
1879
1880
1881 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1882 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1883 /// This basically requires proving that the add in the original type would not
1884 /// overflow to change the sign bit or have a carry out.
1885 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1886   // There are different heuristics we can use for this.  Here are some simple
1887   // ones.
1888   
1889   // Add has the property that adding any two 2's complement numbers can only 
1890   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1891   // have at least two sign bits, we know that the addition of the two values will
1892   // sign extend fine.
1893   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1894     return true;
1895   
1896   
1897   // If one of the operands only has one non-zero bit, and if the other operand
1898   // has a known-zero bit in a more significant place than it (not including the
1899   // sign bit) the ripple may go up to and fill the zero, but won't change the
1900   // sign.  For example, (X & ~4) + 1.
1901   
1902   // TODO: Implement.
1903   
1904   return false;
1905 }
1906
1907
1908 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1909   bool Changed = SimplifyCommutative(I);
1910   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1911
1912   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1913     // X + undef -> undef
1914     if (isa<UndefValue>(RHS))
1915       return ReplaceInstUsesWith(I, RHS);
1916
1917     // X + 0 --> X
1918     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1919       if (RHSC->isNullValue())
1920         return ReplaceInstUsesWith(I, LHS);
1921     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1922       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1923                               (I.getType())->getValueAPF()))
1924         return ReplaceInstUsesWith(I, LHS);
1925     }
1926
1927     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1928       // X + (signbit) --> X ^ signbit
1929       const APInt& Val = CI->getValue();
1930       uint32_t BitWidth = Val.getBitWidth();
1931       if (Val == APInt::getSignBit(BitWidth))
1932         return BinaryOperator::CreateXor(LHS, RHS);
1933       
1934       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1935       // (X & 254)+1 -> (X&254)|1
1936       if (!isa<VectorType>(I.getType())) {
1937         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1938         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1939                                  KnownZero, KnownOne))
1940           return &I;
1941       }
1942     }
1943
1944     if (isa<PHINode>(LHS))
1945       if (Instruction *NV = FoldOpIntoPhi(I))
1946         return NV;
1947     
1948     ConstantInt *XorRHS = 0;
1949     Value *XorLHS = 0;
1950     if (isa<ConstantInt>(RHSC) &&
1951         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1952       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1953       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1954       
1955       uint32_t Size = TySizeBits / 2;
1956       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1957       APInt CFF80Val(-C0080Val);
1958       do {
1959         if (TySizeBits > Size) {
1960           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1961           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1962           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1963               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1964             // This is a sign extend if the top bits are known zero.
1965             if (!MaskedValueIsZero(XorLHS, 
1966                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1967               Size = 0;  // Not a sign ext, but can't be any others either.
1968             break;
1969           }
1970         }
1971         Size >>= 1;
1972         C0080Val = APIntOps::lshr(C0080Val, Size);
1973         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1974       } while (Size >= 1);
1975       
1976       // FIXME: This shouldn't be necessary. When the backends can handle types
1977       // with funny bit widths then this switch statement should be removed. It
1978       // is just here to get the size of the "middle" type back up to something
1979       // that the back ends can handle.
1980       const Type *MiddleType = 0;
1981       switch (Size) {
1982         default: break;
1983         case 32: MiddleType = Type::Int32Ty; break;
1984         case 16: MiddleType = Type::Int16Ty; break;
1985         case  8: MiddleType = Type::Int8Ty; break;
1986       }
1987       if (MiddleType) {
1988         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1989         InsertNewInstBefore(NewTrunc, I);
1990         return new SExtInst(NewTrunc, I.getType(), I.getName());
1991       }
1992     }
1993   }
1994
1995   if (I.getType() == Type::Int1Ty)
1996     return BinaryOperator::CreateXor(LHS, RHS);
1997
1998   // X + X --> X << 1
1999   if (I.getType()->isInteger()) {
2000     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2001
2002     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2003       if (RHSI->getOpcode() == Instruction::Sub)
2004         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2005           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2006     }
2007     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2008       if (LHSI->getOpcode() == Instruction::Sub)
2009         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2010           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2011     }
2012   }
2013
2014   // -A + B  -->  B - A
2015   // -A + -B  -->  -(A + B)
2016   if (Value *LHSV = dyn_castNegVal(LHS)) {
2017     if (LHS->getType()->isIntOrIntVector()) {
2018       if (Value *RHSV = dyn_castNegVal(RHS)) {
2019         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2020         InsertNewInstBefore(NewAdd, I);
2021         return BinaryOperator::CreateNeg(NewAdd);
2022       }
2023     }
2024     
2025     return BinaryOperator::CreateSub(RHS, LHSV);
2026   }
2027
2028   // A + -B  -->  A - B
2029   if (!isa<Constant>(RHS))
2030     if (Value *V = dyn_castNegVal(RHS))
2031       return BinaryOperator::CreateSub(LHS, V);
2032
2033
2034   ConstantInt *C2;
2035   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2036     if (X == RHS)   // X*C + X --> X * (C+1)
2037       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2038
2039     // X*C1 + X*C2 --> X * (C1+C2)
2040     ConstantInt *C1;
2041     if (X == dyn_castFoldableMul(RHS, C1))
2042       return BinaryOperator::CreateMul(X, Add(C1, C2));
2043   }
2044
2045   // X + X*C --> X * (C+1)
2046   if (dyn_castFoldableMul(RHS, C2) == LHS)
2047     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2048
2049   // X + ~X --> -1   since   ~X = -X-1
2050   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2051     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2052   
2053
2054   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2055   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2056     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2057       return R;
2058   
2059   // A+B --> A|B iff A and B have no bits set in common.
2060   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2061     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2062     APInt LHSKnownOne(IT->getBitWidth(), 0);
2063     APInt LHSKnownZero(IT->getBitWidth(), 0);
2064     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2065     if (LHSKnownZero != 0) {
2066       APInt RHSKnownOne(IT->getBitWidth(), 0);
2067       APInt RHSKnownZero(IT->getBitWidth(), 0);
2068       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2069       
2070       // No bits in common -> bitwise or.
2071       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2072         return BinaryOperator::CreateOr(LHS, RHS);
2073     }
2074   }
2075
2076   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2077   if (I.getType()->isIntOrIntVector()) {
2078     Value *W, *X, *Y, *Z;
2079     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2080         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2081       if (W != Y) {
2082         if (W == Z) {
2083           std::swap(Y, Z);
2084         } else if (Y == X) {
2085           std::swap(W, X);
2086         } else if (X == Z) {
2087           std::swap(Y, Z);
2088           std::swap(W, X);
2089         }
2090       }
2091
2092       if (W == Y) {
2093         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2094                                                             LHS->getName()), I);
2095         return BinaryOperator::CreateMul(W, NewAdd);
2096       }
2097     }
2098   }
2099
2100   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2101     Value *X = 0;
2102     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2103       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2104
2105     // (X & FF00) + xx00  -> (X+xx00) & FF00
2106     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2107       Constant *Anded = And(CRHS, C2);
2108       if (Anded == CRHS) {
2109         // See if all bits from the first bit set in the Add RHS up are included
2110         // in the mask.  First, get the rightmost bit.
2111         const APInt& AddRHSV = CRHS->getValue();
2112
2113         // Form a mask of all bits from the lowest bit added through the top.
2114         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2115
2116         // See if the and mask includes all of these bits.
2117         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2118
2119         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2120           // Okay, the xform is safe.  Insert the new add pronto.
2121           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2122                                                             LHS->getName()), I);
2123           return BinaryOperator::CreateAnd(NewAdd, C2);
2124         }
2125       }
2126     }
2127
2128     // Try to fold constant add into select arguments.
2129     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2130       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2131         return R;
2132   }
2133
2134   // add (cast *A to intptrtype) B -> 
2135   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2136   {
2137     CastInst *CI = dyn_cast<CastInst>(LHS);
2138     Value *Other = RHS;
2139     if (!CI) {
2140       CI = dyn_cast<CastInst>(RHS);
2141       Other = LHS;
2142     }
2143     if (CI && CI->getType()->isSized() && 
2144         (CI->getType()->getPrimitiveSizeInBits() == 
2145          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2146         && isa<PointerType>(CI->getOperand(0)->getType())) {
2147       unsigned AS =
2148         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2149       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2150                                       PointerType::get(Type::Int8Ty, AS), I);
2151       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2152       return new PtrToIntInst(I2, CI->getType());
2153     }
2154   }
2155   
2156   // add (select X 0 (sub n A)) A  -->  select X A n
2157   {
2158     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2159     Value *Other = RHS;
2160     if (!SI) {
2161       SI = dyn_cast<SelectInst>(RHS);
2162       Other = LHS;
2163     }
2164     if (SI && SI->hasOneUse()) {
2165       Value *TV = SI->getTrueValue();
2166       Value *FV = SI->getFalseValue();
2167       Value *A, *N;
2168
2169       // Can we fold the add into the argument of the select?
2170       // We check both true and false select arguments for a matching subtract.
2171       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2172           A == Other)  // Fold the add into the true select value.
2173         return SelectInst::Create(SI->getCondition(), N, A);
2174       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2175           A == Other)  // Fold the add into the false select value.
2176         return SelectInst::Create(SI->getCondition(), A, N);
2177     }
2178   }
2179   
2180   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2181   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2182     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2183       return ReplaceInstUsesWith(I, LHS);
2184
2185   // Check for (add (sext x), y), see if we can merge this into an
2186   // integer add followed by a sext.
2187   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2188     // (add (sext x), cst) --> (sext (add x, cst'))
2189     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2190       Constant *CI = 
2191         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2192       if (LHSConv->hasOneUse() &&
2193           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2194           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2195         // Insert the new, smaller add.
2196         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2197                                                         CI, "addconv");
2198         InsertNewInstBefore(NewAdd, I);
2199         return new SExtInst(NewAdd, I.getType());
2200       }
2201     }
2202     
2203     // (add (sext x), (sext y)) --> (sext (add int x, y))
2204     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2205       // Only do this if x/y have the same type, if at last one of them has a
2206       // single use (so we don't increase the number of sexts), and if the
2207       // integer add will not overflow.
2208       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2209           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2210           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2211                                    RHSConv->getOperand(0))) {
2212         // Insert the new integer add.
2213         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2214                                                         RHSConv->getOperand(0),
2215                                                         "addconv");
2216         InsertNewInstBefore(NewAdd, I);
2217         return new SExtInst(NewAdd, I.getType());
2218       }
2219     }
2220   }
2221   
2222   // Check for (add double (sitofp x), y), see if we can merge this into an
2223   // integer add followed by a promotion.
2224   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2225     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2226     // ... if the constant fits in the integer value.  This is useful for things
2227     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2228     // requires a constant pool load, and generally allows the add to be better
2229     // instcombined.
2230     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2231       Constant *CI = 
2232       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2233       if (LHSConv->hasOneUse() &&
2234           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2235           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2236         // Insert the new integer add.
2237         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2238                                                         CI, "addconv");
2239         InsertNewInstBefore(NewAdd, I);
2240         return new SIToFPInst(NewAdd, I.getType());
2241       }
2242     }
2243     
2244     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2245     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2246       // Only do this if x/y have the same type, if at last one of them has a
2247       // single use (so we don't increase the number of int->fp conversions),
2248       // and if the integer add will not overflow.
2249       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2250           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2251           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2252                                    RHSConv->getOperand(0))) {
2253         // Insert the new integer add.
2254         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2255                                                         RHSConv->getOperand(0),
2256                                                         "addconv");
2257         InsertNewInstBefore(NewAdd, I);
2258         return new SIToFPInst(NewAdd, I.getType());
2259       }
2260     }
2261   }
2262   
2263   return Changed ? &I : 0;
2264 }
2265
2266 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2267   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2268
2269   if (Op0 == Op1)         // sub X, X  -> 0
2270     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2271
2272   // If this is a 'B = x-(-A)', change to B = x+A...
2273   if (Value *V = dyn_castNegVal(Op1))
2274     return BinaryOperator::CreateAdd(Op0, V);
2275
2276   if (isa<UndefValue>(Op0))
2277     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2278   if (isa<UndefValue>(Op1))
2279     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2280
2281   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2282     // Replace (-1 - A) with (~A)...
2283     if (C->isAllOnesValue())
2284       return BinaryOperator::CreateNot(Op1);
2285
2286     // C - ~X == X + (1+C)
2287     Value *X = 0;
2288     if (match(Op1, m_Not(m_Value(X))))
2289       return BinaryOperator::CreateAdd(X, AddOne(C));
2290
2291     // -(X >>u 31) -> (X >>s 31)
2292     // -(X >>s 31) -> (X >>u 31)
2293     if (C->isZero()) {
2294       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2295         if (SI->getOpcode() == Instruction::LShr) {
2296           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2297             // Check to see if we are shifting out everything but the sign bit.
2298             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2299                 SI->getType()->getPrimitiveSizeInBits()-1) {
2300               // Ok, the transformation is safe.  Insert AShr.
2301               return BinaryOperator::Create(Instruction::AShr, 
2302                                           SI->getOperand(0), CU, SI->getName());
2303             }
2304           }
2305         }
2306         else if (SI->getOpcode() == Instruction::AShr) {
2307           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2308             // Check to see if we are shifting out everything but the sign bit.
2309             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2310                 SI->getType()->getPrimitiveSizeInBits()-1) {
2311               // Ok, the transformation is safe.  Insert LShr. 
2312               return BinaryOperator::CreateLShr(
2313                                           SI->getOperand(0), CU, SI->getName());
2314             }
2315           }
2316         }
2317       }
2318     }
2319
2320     // Try to fold constant sub into select arguments.
2321     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2322       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2323         return R;
2324
2325     if (isa<PHINode>(Op0))
2326       if (Instruction *NV = FoldOpIntoPhi(I))
2327         return NV;
2328   }
2329
2330   if (I.getType() == Type::Int1Ty)
2331     return BinaryOperator::CreateXor(Op0, Op1);
2332
2333   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2334     if (Op1I->getOpcode() == Instruction::Add &&
2335         !Op0->getType()->isFPOrFPVector()) {
2336       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2337         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2338       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2339         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2340       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2341         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2342           // C1-(X+C2) --> (C1-C2)-X
2343           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2344                                            Op1I->getOperand(0));
2345       }
2346     }
2347
2348     if (Op1I->hasOneUse()) {
2349       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2350       // is not used by anyone else...
2351       //
2352       if (Op1I->getOpcode() == Instruction::Sub &&
2353           !Op1I->getType()->isFPOrFPVector()) {
2354         // Swap the two operands of the subexpr...
2355         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2356         Op1I->setOperand(0, IIOp1);
2357         Op1I->setOperand(1, IIOp0);
2358
2359         // Create the new top level add instruction...
2360         return BinaryOperator::CreateAdd(Op0, Op1);
2361       }
2362
2363       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2364       //
2365       if (Op1I->getOpcode() == Instruction::And &&
2366           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2367         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2368
2369         Value *NewNot =
2370           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2371         return BinaryOperator::CreateAnd(Op0, NewNot);
2372       }
2373
2374       // 0 - (X sdiv C)  -> (X sdiv -C)
2375       if (Op1I->getOpcode() == Instruction::SDiv)
2376         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2377           if (CSI->isZero())
2378             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2379               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2380                                                ConstantExpr::getNeg(DivRHS));
2381
2382       // X - X*C --> X * (1-C)
2383       ConstantInt *C2 = 0;
2384       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2385         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2386         return BinaryOperator::CreateMul(Op0, CP1);
2387       }
2388
2389       // X - ((X / Y) * Y) --> X % Y
2390       if (Op1I->getOpcode() == Instruction::Mul)
2391         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2392           if (Op0 == I->getOperand(0) &&
2393               Op1I->getOperand(1) == I->getOperand(1)) {
2394             if (I->getOpcode() == Instruction::SDiv)
2395               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2396             if (I->getOpcode() == Instruction::UDiv)
2397               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2398           }
2399     }
2400   }
2401
2402   if (!Op0->getType()->isFPOrFPVector())
2403     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2404       if (Op0I->getOpcode() == Instruction::Add) {
2405         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2406           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2407         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2408           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2409       } else if (Op0I->getOpcode() == Instruction::Sub) {
2410         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2411           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2412       }
2413     }
2414
2415   ConstantInt *C1;
2416   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2417     if (X == Op1)  // X*C - X --> X * (C-1)
2418       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2419
2420     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2421     if (X == dyn_castFoldableMul(Op1, C2))
2422       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2423   }
2424   return 0;
2425 }
2426
2427 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2428 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2429 /// TrueIfSigned if the result of the comparison is true when the input value is
2430 /// signed.
2431 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2432                            bool &TrueIfSigned) {
2433   switch (pred) {
2434   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2435     TrueIfSigned = true;
2436     return RHS->isZero();
2437   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2438     TrueIfSigned = true;
2439     return RHS->isAllOnesValue();
2440   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2441     TrueIfSigned = false;
2442     return RHS->isAllOnesValue();
2443   case ICmpInst::ICMP_UGT:
2444     // True if LHS u> RHS and RHS == high-bit-mask - 1
2445     TrueIfSigned = true;
2446     return RHS->getValue() ==
2447       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2448   case ICmpInst::ICMP_UGE: 
2449     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2450     TrueIfSigned = true;
2451     return RHS->getValue().isSignBit();
2452   default:
2453     return false;
2454   }
2455 }
2456
2457 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2458   bool Changed = SimplifyCommutative(I);
2459   Value *Op0 = I.getOperand(0);
2460
2461   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2462     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
2464   // Simplify mul instructions with a constant RHS...
2465   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2466     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2467
2468       // ((X << C1)*C2) == (X * (C2 << C1))
2469       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2470         if (SI->getOpcode() == Instruction::Shl)
2471           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2472             return BinaryOperator::CreateMul(SI->getOperand(0),
2473                                              ConstantExpr::getShl(CI, ShOp));
2474
2475       if (CI->isZero())
2476         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2477       if (CI->equalsInt(1))                  // X * 1  == X
2478         return ReplaceInstUsesWith(I, Op0);
2479       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2480         return BinaryOperator::CreateNeg(Op0, I.getName());
2481
2482       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2483       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2484         return BinaryOperator::CreateShl(Op0,
2485                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2486       }
2487     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2488       if (Op1F->isNullValue())
2489         return ReplaceInstUsesWith(I, Op1);
2490
2491       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2492       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2493       // We need a better interface for long double here.
2494       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2495         if (Op1F->isExactlyValue(1.0))
2496           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2497     }
2498     
2499     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2500       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2501           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2502         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2503         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2504                                                      Op1, "tmp");
2505         InsertNewInstBefore(Add, I);
2506         Value *C1C2 = ConstantExpr::getMul(Op1, 
2507                                            cast<Constant>(Op0I->getOperand(1)));
2508         return BinaryOperator::CreateAdd(Add, C1C2);
2509         
2510       }
2511
2512     // Try to fold constant mul into select arguments.
2513     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2514       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2515         return R;
2516
2517     if (isa<PHINode>(Op0))
2518       if (Instruction *NV = FoldOpIntoPhi(I))
2519         return NV;
2520   }
2521
2522   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2523     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2524       return BinaryOperator::CreateMul(Op0v, Op1v);
2525
2526   if (I.getType() == Type::Int1Ty)
2527     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2528
2529   // If one of the operands of the multiply is a cast from a boolean value, then
2530   // we know the bool is either zero or one, so this is a 'masking' multiply.
2531   // See if we can simplify things based on how the boolean was originally
2532   // formed.
2533   CastInst *BoolCast = 0;
2534   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2535     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2536       BoolCast = CI;
2537   if (!BoolCast)
2538     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2539       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2540         BoolCast = CI;
2541   if (BoolCast) {
2542     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2543       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2544       const Type *SCOpTy = SCIOp0->getType();
2545       bool TIS = false;
2546       
2547       // If the icmp is true iff the sign bit of X is set, then convert this
2548       // multiply into a shift/and combination.
2549       if (isa<ConstantInt>(SCIOp1) &&
2550           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2551           TIS) {
2552         // Shift the X value right to turn it into "all signbits".
2553         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2554                                           SCOpTy->getPrimitiveSizeInBits()-1);
2555         Value *V =
2556           InsertNewInstBefore(
2557             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2558                                             BoolCast->getOperand(0)->getName()+
2559                                             ".mask"), I);
2560
2561         // If the multiply type is not the same as the source type, sign extend
2562         // or truncate to the multiply type.
2563         if (I.getType() != V->getType()) {
2564           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2565           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2566           Instruction::CastOps opcode = 
2567             (SrcBits == DstBits ? Instruction::BitCast : 
2568              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2569           V = InsertCastBefore(opcode, V, I.getType(), I);
2570         }
2571
2572         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2573         return BinaryOperator::CreateAnd(V, OtherOp);
2574       }
2575     }
2576   }
2577
2578   return Changed ? &I : 0;
2579 }
2580
2581 /// This function implements the transforms on div instructions that work
2582 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2583 /// used by the visitors to those instructions.
2584 /// @brief Transforms common to all three div instructions
2585 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588   // undef / X -> 0        for integer.
2589   // undef / X -> undef    for FP (the undef could be a snan).
2590   if (isa<UndefValue>(Op0)) {
2591     if (Op0->getType()->isFPOrFPVector())
2592       return ReplaceInstUsesWith(I, Op0);
2593     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2594   }
2595
2596   // X / undef -> undef
2597   if (isa<UndefValue>(Op1))
2598     return ReplaceInstUsesWith(I, Op1);
2599
2600   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2601   // This does not apply for fdiv.
2602   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2603     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2604     // the same basic block, then we replace the select with Y, and the
2605     // condition of the select with false (if the cond value is in the same BB).
2606     // If the select has uses other than the div, this allows them to be
2607     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2608     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2609       if (ST->isNullValue()) {
2610         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2611         if (CondI && CondI->getParent() == I.getParent())
2612           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2613         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2614           I.setOperand(1, SI->getOperand(2));
2615         else
2616           UpdateValueUsesWith(SI, SI->getOperand(2));
2617         return &I;
2618       }
2619
2620     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2621     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2622       if (ST->isNullValue()) {
2623         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2624         if (CondI && CondI->getParent() == I.getParent())
2625           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2626         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2627           I.setOperand(1, SI->getOperand(1));
2628         else
2629           UpdateValueUsesWith(SI, SI->getOperand(1));
2630         return &I;
2631       }
2632   }
2633
2634   return 0;
2635 }
2636
2637 /// This function implements the transforms common to both integer division
2638 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2639 /// division instructions.
2640 /// @brief Common integer divide transforms
2641 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2642   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2643
2644   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2645   if (Op0 == Op1) {
2646     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2647       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2648       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2649       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2650     }
2651
2652     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2653     return ReplaceInstUsesWith(I, CI);
2654   }
2655   
2656   if (Instruction *Common = commonDivTransforms(I))
2657     return Common;
2658
2659   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2660     // div X, 1 == X
2661     if (RHS->equalsInt(1))
2662       return ReplaceInstUsesWith(I, Op0);
2663
2664     // (X / C1) / C2  -> X / (C1*C2)
2665     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2666       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2667         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2668           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2669             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2670           else 
2671             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2672                                           Multiply(RHS, LHSRHS));
2673         }
2674
2675     if (!RHS->isZero()) { // avoid X udiv 0
2676       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2677         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2678           return R;
2679       if (isa<PHINode>(Op0))
2680         if (Instruction *NV = FoldOpIntoPhi(I))
2681           return NV;
2682     }
2683   }
2684
2685   // 0 / X == 0, we don't need to preserve faults!
2686   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2687     if (LHS->equalsInt(0))
2688       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2689
2690   // It can't be division by zero, hence it must be division by one.
2691   if (I.getType() == Type::Int1Ty)
2692     return ReplaceInstUsesWith(I, Op0);
2693
2694   return 0;
2695 }
2696
2697 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2698   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2699
2700   // Handle the integer div common cases
2701   if (Instruction *Common = commonIDivTransforms(I))
2702     return Common;
2703
2704   // X udiv C^2 -> X >> C
2705   // Check to see if this is an unsigned division with an exact power of 2,
2706   // if so, convert to a right shift.
2707   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2708     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2709       return BinaryOperator::CreateLShr(Op0, 
2710                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2711   }
2712
2713   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2714   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2715     if (RHSI->getOpcode() == Instruction::Shl &&
2716         isa<ConstantInt>(RHSI->getOperand(0))) {
2717       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2718       if (C1.isPowerOf2()) {
2719         Value *N = RHSI->getOperand(1);
2720         const Type *NTy = N->getType();
2721         if (uint32_t C2 = C1.logBase2()) {
2722           Constant *C2V = ConstantInt::get(NTy, C2);
2723           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2724         }
2725         return BinaryOperator::CreateLShr(Op0, N);
2726       }
2727     }
2728   }
2729   
2730   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2731   // where C1&C2 are powers of two.
2732   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2733     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2734       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2735         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2736         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2737           // Compute the shift amounts
2738           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2739           // Construct the "on true" case of the select
2740           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2741           Instruction *TSI = BinaryOperator::CreateLShr(
2742                                                  Op0, TC, SI->getName()+".t");
2743           TSI = InsertNewInstBefore(TSI, I);
2744   
2745           // Construct the "on false" case of the select
2746           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2747           Instruction *FSI = BinaryOperator::CreateLShr(
2748                                                  Op0, FC, SI->getName()+".f");
2749           FSI = InsertNewInstBefore(FSI, I);
2750
2751           // construct the select instruction and return it.
2752           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2753         }
2754       }
2755   return 0;
2756 }
2757
2758 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2759   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2760
2761   // Handle the integer div common cases
2762   if (Instruction *Common = commonIDivTransforms(I))
2763     return Common;
2764
2765   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2766     // sdiv X, -1 == -X
2767     if (RHS->isAllOnesValue())
2768       return BinaryOperator::CreateNeg(Op0);
2769
2770     // -X/C -> X/-C
2771     if (Value *LHSNeg = dyn_castNegVal(Op0))
2772       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2773   }
2774
2775   // If the sign bits of both operands are zero (i.e. we can prove they are
2776   // unsigned inputs), turn this into a udiv.
2777   if (I.getType()->isInteger()) {
2778     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2779     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2780       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2781       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2782     }
2783   }      
2784   
2785   return 0;
2786 }
2787
2788 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2789   return commonDivTransforms(I);
2790 }
2791
2792 /// This function implements the transforms on rem instructions that work
2793 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2794 /// is used by the visitors to those instructions.
2795 /// @brief Transforms common to all three rem instructions
2796 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2797   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
2799   // 0 % X == 0 for integer, we don't need to preserve faults!
2800   if (Constant *LHS = dyn_cast<Constant>(Op0))
2801     if (LHS->isNullValue())
2802       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2803
2804   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2805     if (I.getType()->isFPOrFPVector())
2806       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2807     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2808   }
2809   if (isa<UndefValue>(Op1))
2810     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2811
2812   // Handle cases involving: rem X, (select Cond, Y, Z)
2813   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2814     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2815     // the same basic block, then we replace the select with Y, and the
2816     // condition of the select with false (if the cond value is in the same
2817     // BB).  If the select has uses other than the div, this allows them to be
2818     // simplified also.
2819     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2820       if (ST->isNullValue()) {
2821         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2822         if (CondI && CondI->getParent() == I.getParent())
2823           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2824         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2825           I.setOperand(1, SI->getOperand(2));
2826         else
2827           UpdateValueUsesWith(SI, SI->getOperand(2));
2828         return &I;
2829       }
2830     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2831     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2832       if (ST->isNullValue()) {
2833         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2834         if (CondI && CondI->getParent() == I.getParent())
2835           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2836         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2837           I.setOperand(1, SI->getOperand(1));
2838         else
2839           UpdateValueUsesWith(SI, SI->getOperand(1));
2840         return &I;
2841       }
2842   }
2843
2844   return 0;
2845 }
2846
2847 /// This function implements the transforms common to both integer remainder
2848 /// instructions (urem and srem). It is called by the visitors to those integer
2849 /// remainder instructions.
2850 /// @brief Common integer remainder transforms
2851 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2852   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854   if (Instruction *common = commonRemTransforms(I))
2855     return common;
2856
2857   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2858     // X % 0 == undef, we don't need to preserve faults!
2859     if (RHS->equalsInt(0))
2860       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2861     
2862     if (RHS->equalsInt(1))  // X % 1 == 0
2863       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2864
2865     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2866       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2867         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2868           return R;
2869       } else if (isa<PHINode>(Op0I)) {
2870         if (Instruction *NV = FoldOpIntoPhi(I))
2871           return NV;
2872       }
2873
2874       // See if we can fold away this rem instruction.
2875       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2876       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2877       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2878                                KnownZero, KnownOne))
2879         return &I;
2880     }
2881   }
2882
2883   return 0;
2884 }
2885
2886 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2887   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2888
2889   if (Instruction *common = commonIRemTransforms(I))
2890     return common;
2891   
2892   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2893     // X urem C^2 -> X and C
2894     // Check to see if this is an unsigned remainder with an exact power of 2,
2895     // if so, convert to a bitwise and.
2896     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2897       if (C->getValue().isPowerOf2())
2898         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2899   }
2900
2901   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2902     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2903     if (RHSI->getOpcode() == Instruction::Shl &&
2904         isa<ConstantInt>(RHSI->getOperand(0))) {
2905       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2906         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2907         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2908                                                                    "tmp"), I);
2909         return BinaryOperator::CreateAnd(Op0, Add);
2910       }
2911     }
2912   }
2913
2914   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2915   // where C1&C2 are powers of two.
2916   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2917     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2918       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2919         // STO == 0 and SFO == 0 handled above.
2920         if ((STO->getValue().isPowerOf2()) && 
2921             (SFO->getValue().isPowerOf2())) {
2922           Value *TrueAnd = InsertNewInstBefore(
2923             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2924           Value *FalseAnd = InsertNewInstBefore(
2925             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2926           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2927         }
2928       }
2929   }
2930   
2931   return 0;
2932 }
2933
2934 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2935   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2936
2937   // Handle the integer rem common cases
2938   if (Instruction *common = commonIRemTransforms(I))
2939     return common;
2940   
2941   if (Value *RHSNeg = dyn_castNegVal(Op1))
2942     if (!isa<ConstantInt>(RHSNeg) || 
2943         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2944       // X % -Y -> X % Y
2945       AddUsesToWorkList(I);
2946       I.setOperand(1, RHSNeg);
2947       return &I;
2948     }
2949  
2950   // If the sign bits of both operands are zero (i.e. we can prove they are
2951   // unsigned inputs), turn this into a urem.
2952   if (I.getType()->isInteger()) {
2953     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2954     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2955       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2956       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2957     }
2958   }
2959
2960   return 0;
2961 }
2962
2963 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2964   return commonRemTransforms(I);
2965 }
2966
2967 // isMaxValueMinusOne - return true if this is Max-1
2968 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2969   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2970   if (!isSigned)
2971     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2972   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2973 }
2974
2975 // isMinValuePlusOne - return true if this is Min+1
2976 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2977   if (!isSigned)
2978     return C->getValue() == 1; // unsigned
2979     
2980   // Calculate 1111111111000000000000
2981   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2982   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2983 }
2984
2985 // isOneBitSet - Return true if there is exactly one bit set in the specified
2986 // constant.
2987 static bool isOneBitSet(const ConstantInt *CI) {
2988   return CI->getValue().isPowerOf2();
2989 }
2990
2991 // isHighOnes - Return true if the constant is of the form 1+0+.
2992 // This is the same as lowones(~X).
2993 static bool isHighOnes(const ConstantInt *CI) {
2994   return (~CI->getValue() + 1).isPowerOf2();
2995 }
2996
2997 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2998 /// are carefully arranged to allow folding of expressions such as:
2999 ///
3000 ///      (A < B) | (A > B) --> (A != B)
3001 ///
3002 /// Note that this is only valid if the first and second predicates have the
3003 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3004 ///
3005 /// Three bits are used to represent the condition, as follows:
3006 ///   0  A > B
3007 ///   1  A == B
3008 ///   2  A < B
3009 ///
3010 /// <=>  Value  Definition
3011 /// 000     0   Always false
3012 /// 001     1   A >  B
3013 /// 010     2   A == B
3014 /// 011     3   A >= B
3015 /// 100     4   A <  B
3016 /// 101     5   A != B
3017 /// 110     6   A <= B
3018 /// 111     7   Always true
3019 ///  
3020 static unsigned getICmpCode(const ICmpInst *ICI) {
3021   switch (ICI->getPredicate()) {
3022     // False -> 0
3023   case ICmpInst::ICMP_UGT: return 1;  // 001
3024   case ICmpInst::ICMP_SGT: return 1;  // 001
3025   case ICmpInst::ICMP_EQ:  return 2;  // 010
3026   case ICmpInst::ICMP_UGE: return 3;  // 011
3027   case ICmpInst::ICMP_SGE: return 3;  // 011
3028   case ICmpInst::ICMP_ULT: return 4;  // 100
3029   case ICmpInst::ICMP_SLT: return 4;  // 100
3030   case ICmpInst::ICMP_NE:  return 5;  // 101
3031   case ICmpInst::ICMP_ULE: return 6;  // 110
3032   case ICmpInst::ICMP_SLE: return 6;  // 110
3033     // True -> 7
3034   default:
3035     assert(0 && "Invalid ICmp predicate!");
3036     return 0;
3037   }
3038 }
3039
3040 /// getICmpValue - This is the complement of getICmpCode, which turns an
3041 /// opcode and two operands into either a constant true or false, or a brand 
3042 /// new ICmp instruction. The sign is passed in to determine which kind
3043 /// of predicate to use in new icmp instructions.
3044 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3045   switch (code) {
3046   default: assert(0 && "Illegal ICmp code!");
3047   case  0: return ConstantInt::getFalse();
3048   case  1: 
3049     if (sign)
3050       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3051     else
3052       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3053   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3054   case  3: 
3055     if (sign)
3056       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3057     else
3058       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3059   case  4: 
3060     if (sign)
3061       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3062     else
3063       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3064   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3065   case  6: 
3066     if (sign)
3067       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3068     else
3069       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3070   case  7: return ConstantInt::getTrue();
3071   }
3072 }
3073
3074 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3075   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3076     (ICmpInst::isSignedPredicate(p1) && 
3077      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3078     (ICmpInst::isSignedPredicate(p2) && 
3079      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3080 }
3081
3082 namespace { 
3083 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3084 struct FoldICmpLogical {
3085   InstCombiner &IC;
3086   Value *LHS, *RHS;
3087   ICmpInst::Predicate pred;
3088   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3089     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3090       pred(ICI->getPredicate()) {}
3091   bool shouldApply(Value *V) const {
3092     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3093       if (PredicatesFoldable(pred, ICI->getPredicate()))
3094         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3095                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3096     return false;
3097   }
3098   Instruction *apply(Instruction &Log) const {
3099     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3100     if (ICI->getOperand(0) != LHS) {
3101       assert(ICI->getOperand(1) == LHS);
3102       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3103     }
3104
3105     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3106     unsigned LHSCode = getICmpCode(ICI);
3107     unsigned RHSCode = getICmpCode(RHSICI);
3108     unsigned Code;
3109     switch (Log.getOpcode()) {
3110     case Instruction::And: Code = LHSCode & RHSCode; break;
3111     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3112     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3113     default: assert(0 && "Illegal logical opcode!"); return 0;
3114     }
3115
3116     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3117                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3118       
3119     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3120     if (Instruction *I = dyn_cast<Instruction>(RV))
3121       return I;
3122     // Otherwise, it's a constant boolean value...
3123     return IC.ReplaceInstUsesWith(Log, RV);
3124   }
3125 };
3126 } // end anonymous namespace
3127
3128 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3129 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3130 // guaranteed to be a binary operator.
3131 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3132                                     ConstantInt *OpRHS,
3133                                     ConstantInt *AndRHS,
3134                                     BinaryOperator &TheAnd) {
3135   Value *X = Op->getOperand(0);
3136   Constant *Together = 0;
3137   if (!Op->isShift())
3138     Together = And(AndRHS, OpRHS);
3139
3140   switch (Op->getOpcode()) {
3141   case Instruction::Xor:
3142     if (Op->hasOneUse()) {
3143       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3144       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3145       InsertNewInstBefore(And, TheAnd);
3146       And->takeName(Op);
3147       return BinaryOperator::CreateXor(And, Together);
3148     }
3149     break;
3150   case Instruction::Or:
3151     if (Together == AndRHS) // (X | C) & C --> C
3152       return ReplaceInstUsesWith(TheAnd, AndRHS);
3153
3154     if (Op->hasOneUse() && Together != OpRHS) {
3155       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3156       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3157       InsertNewInstBefore(Or, TheAnd);
3158       Or->takeName(Op);
3159       return BinaryOperator::CreateAnd(Or, AndRHS);
3160     }
3161     break;
3162   case Instruction::Add:
3163     if (Op->hasOneUse()) {
3164       // Adding a one to a single bit bit-field should be turned into an XOR
3165       // of the bit.  First thing to check is to see if this AND is with a
3166       // single bit constant.
3167       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3168
3169       // If there is only one bit set...
3170       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3171         // Ok, at this point, we know that we are masking the result of the
3172         // ADD down to exactly one bit.  If the constant we are adding has
3173         // no bits set below this bit, then we can eliminate the ADD.
3174         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3175
3176         // Check to see if any bits below the one bit set in AndRHSV are set.
3177         if ((AddRHS & (AndRHSV-1)) == 0) {
3178           // If not, the only thing that can effect the output of the AND is
3179           // the bit specified by AndRHSV.  If that bit is set, the effect of
3180           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3181           // no effect.
3182           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3183             TheAnd.setOperand(0, X);
3184             return &TheAnd;
3185           } else {
3186             // Pull the XOR out of the AND.
3187             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3188             InsertNewInstBefore(NewAnd, TheAnd);
3189             NewAnd->takeName(Op);
3190             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3191           }
3192         }
3193       }
3194     }
3195     break;
3196
3197   case Instruction::Shl: {
3198     // We know that the AND will not produce any of the bits shifted in, so if
3199     // the anded constant includes them, clear them now!
3200     //
3201     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3202     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3203     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3204     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3205
3206     if (CI->getValue() == ShlMask) { 
3207     // Masking out bits that the shift already masks
3208       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3209     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3210       TheAnd.setOperand(1, CI);
3211       return &TheAnd;
3212     }
3213     break;
3214   }
3215   case Instruction::LShr:
3216   {
3217     // We know that the AND will not produce any of the bits shifted in, so if
3218     // the anded constant includes them, clear them now!  This only applies to
3219     // unsigned shifts, because a signed shr may bring in set bits!
3220     //
3221     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3222     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3223     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3224     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3225
3226     if (CI->getValue() == ShrMask) {   
3227     // Masking out bits that the shift already masks.
3228       return ReplaceInstUsesWith(TheAnd, Op);
3229     } else if (CI != AndRHS) {
3230       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3231       return &TheAnd;
3232     }
3233     break;
3234   }
3235   case Instruction::AShr:
3236     // Signed shr.
3237     // See if this is shifting in some sign extension, then masking it out
3238     // with an and.
3239     if (Op->hasOneUse()) {
3240       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3241       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3242       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3243       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3244       if (C == AndRHS) {          // Masking out bits shifted in.
3245         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3246         // Make the argument unsigned.
3247         Value *ShVal = Op->getOperand(0);
3248         ShVal = InsertNewInstBefore(
3249             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3250                                    Op->getName()), TheAnd);
3251         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3252       }
3253     }
3254     break;
3255   }
3256   return 0;
3257 }
3258
3259
3260 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3261 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3262 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3263 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3264 /// insert new instructions.
3265 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3266                                            bool isSigned, bool Inside, 
3267                                            Instruction &IB) {
3268   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3269             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3270          "Lo is not <= Hi in range emission code!");
3271     
3272   if (Inside) {
3273     if (Lo == Hi)  // Trivially false.
3274       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3275
3276     // V >= Min && V < Hi --> V < Hi
3277     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3278       ICmpInst::Predicate pred = (isSigned ? 
3279         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3280       return new ICmpInst(pred, V, Hi);
3281     }
3282
3283     // Emit V-Lo <u Hi-Lo
3284     Constant *NegLo = ConstantExpr::getNeg(Lo);
3285     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3286     InsertNewInstBefore(Add, IB);
3287     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3288     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3289   }
3290
3291   if (Lo == Hi)  // Trivially true.
3292     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3293
3294   // V < Min || V >= Hi -> V > Hi-1
3295   Hi = SubOne(cast<ConstantInt>(Hi));
3296   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3297     ICmpInst::Predicate pred = (isSigned ? 
3298         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3299     return new ICmpInst(pred, V, Hi);
3300   }
3301
3302   // Emit V-Lo >u Hi-1-Lo
3303   // Note that Hi has already had one subtracted from it, above.
3304   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3305   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3306   InsertNewInstBefore(Add, IB);
3307   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3308   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3309 }
3310
3311 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3312 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3313 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3314 // not, since all 1s are not contiguous.
3315 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3316   const APInt& V = Val->getValue();
3317   uint32_t BitWidth = Val->getType()->getBitWidth();
3318   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3319
3320   // look for the first zero bit after the run of ones
3321   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3322   // look for the first non-zero bit
3323   ME = V.getActiveBits(); 
3324   return true;
3325 }
3326
3327 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3328 /// where isSub determines whether the operator is a sub.  If we can fold one of
3329 /// the following xforms:
3330 /// 
3331 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3332 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3333 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3334 ///
3335 /// return (A +/- B).
3336 ///
3337 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3338                                         ConstantInt *Mask, bool isSub,
3339                                         Instruction &I) {
3340   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3341   if (!LHSI || LHSI->getNumOperands() != 2 ||
3342       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3343
3344   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3345
3346   switch (LHSI->getOpcode()) {
3347   default: return 0;
3348   case Instruction::And:
3349     if (And(N, Mask) == Mask) {
3350       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3351       if ((Mask->getValue().countLeadingZeros() + 
3352            Mask->getValue().countPopulation()) == 
3353           Mask->getValue().getBitWidth())
3354         break;
3355
3356       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3357       // part, we don't need any explicit masks to take them out of A.  If that
3358       // is all N is, ignore it.
3359       uint32_t MB = 0, ME = 0;
3360       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3361         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3362         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3363         if (MaskedValueIsZero(RHS, Mask))
3364           break;
3365       }
3366     }
3367     return 0;
3368   case Instruction::Or:
3369   case Instruction::Xor:
3370     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3371     if ((Mask->getValue().countLeadingZeros() + 
3372          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3373         && And(N, Mask)->isZero())
3374       break;
3375     return 0;
3376   }
3377   
3378   Instruction *New;
3379   if (isSub)
3380     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3381   else
3382     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3383   return InsertNewInstBefore(New, I);
3384 }
3385
3386 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3387   bool Changed = SimplifyCommutative(I);
3388   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3389
3390   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3391     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3392
3393   // and X, X = X
3394   if (Op0 == Op1)
3395     return ReplaceInstUsesWith(I, Op1);
3396
3397   // See if we can simplify any instructions used by the instruction whose sole 
3398   // purpose is to compute bits we don't care about.
3399   if (!isa<VectorType>(I.getType())) {
3400     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3401     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3402     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3403                              KnownZero, KnownOne))
3404       return &I;
3405   } else {
3406     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3407       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3408         return ReplaceInstUsesWith(I, I.getOperand(0));
3409     } else if (isa<ConstantAggregateZero>(Op1)) {
3410       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3411     }
3412   }
3413   
3414   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3415     const APInt& AndRHSMask = AndRHS->getValue();
3416     APInt NotAndRHS(~AndRHSMask);
3417
3418     // Optimize a variety of ((val OP C1) & C2) combinations...
3419     if (isa<BinaryOperator>(Op0)) {
3420       Instruction *Op0I = cast<Instruction>(Op0);
3421       Value *Op0LHS = Op0I->getOperand(0);
3422       Value *Op0RHS = Op0I->getOperand(1);
3423       switch (Op0I->getOpcode()) {
3424       case Instruction::Xor:
3425       case Instruction::Or:
3426         // If the mask is only needed on one incoming arm, push it up.
3427         if (Op0I->hasOneUse()) {
3428           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3429             // Not masking anything out for the LHS, move to RHS.
3430             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3431                                                    Op0RHS->getName()+".masked");
3432             InsertNewInstBefore(NewRHS, I);
3433             return BinaryOperator::Create(
3434                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3435           }
3436           if (!isa<Constant>(Op0RHS) &&
3437               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3438             // Not masking anything out for the RHS, move to LHS.
3439             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3440                                                    Op0LHS->getName()+".masked");
3441             InsertNewInstBefore(NewLHS, I);
3442             return BinaryOperator::Create(
3443                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3444           }
3445         }
3446
3447         break;
3448       case Instruction::Add:
3449         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3450         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3451         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3452         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3453           return BinaryOperator::CreateAnd(V, AndRHS);
3454         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3455           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3456         break;
3457
3458       case Instruction::Sub:
3459         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3460         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3461         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3462         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3463           return BinaryOperator::CreateAnd(V, AndRHS);
3464
3465         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3466         // has 1's for all bits that the subtraction with A might affect.
3467         if (Op0I->hasOneUse()) {
3468           uint32_t BitWidth = AndRHSMask.getBitWidth();
3469           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3470           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3471
3472           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3473           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3474               MaskedValueIsZero(Op0LHS, Mask)) {
3475             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3476             InsertNewInstBefore(NewNeg, I);
3477             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3478           }
3479         }
3480         break;
3481
3482       case Instruction::Shl:
3483       case Instruction::LShr:
3484         // (1 << x) & 1 --> zext(x == 0)
3485         // (1 >> x) & 1 --> zext(x == 0)
3486         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3487           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3488                                            Constant::getNullValue(I.getType()));
3489           InsertNewInstBefore(NewICmp, I);
3490           return new ZExtInst(NewICmp, I.getType());
3491         }
3492         break;
3493       }
3494
3495       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3496         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3497           return Res;
3498     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3499       // If this is an integer truncation or change from signed-to-unsigned, and
3500       // if the source is an and/or with immediate, transform it.  This
3501       // frequently occurs for bitfield accesses.
3502       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3503         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3504             CastOp->getNumOperands() == 2)
3505           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3506             if (CastOp->getOpcode() == Instruction::And) {
3507               // Change: and (cast (and X, C1) to T), C2
3508               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3509               // This will fold the two constants together, which may allow 
3510               // other simplifications.
3511               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3512                 CastOp->getOperand(0), I.getType(), 
3513                 CastOp->getName()+".shrunk");
3514               NewCast = InsertNewInstBefore(NewCast, I);
3515               // trunc_or_bitcast(C1)&C2
3516               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3517               C3 = ConstantExpr::getAnd(C3, AndRHS);
3518               return BinaryOperator::CreateAnd(NewCast, C3);
3519             } else if (CastOp->getOpcode() == Instruction::Or) {
3520               // Change: and (cast (or X, C1) to T), C2
3521               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3522               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3523               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3524                 return ReplaceInstUsesWith(I, AndRHS);
3525             }
3526           }
3527       }
3528     }
3529
3530     // Try to fold constant and into select arguments.
3531     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3532       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3533         return R;
3534     if (isa<PHINode>(Op0))
3535       if (Instruction *NV = FoldOpIntoPhi(I))
3536         return NV;
3537   }
3538
3539   Value *Op0NotVal = dyn_castNotVal(Op0);
3540   Value *Op1NotVal = dyn_castNotVal(Op1);
3541
3542   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3543     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3544
3545   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3546   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3547     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3548                                                I.getName()+".demorgan");
3549     InsertNewInstBefore(Or, I);
3550     return BinaryOperator::CreateNot(Or);
3551   }
3552   
3553   {
3554     Value *A = 0, *B = 0, *C = 0, *D = 0;
3555     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3556       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3557         return ReplaceInstUsesWith(I, Op1);
3558     
3559       // (A|B) & ~(A&B) -> A^B
3560       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3561         if ((A == C && B == D) || (A == D && B == C))
3562           return BinaryOperator::CreateXor(A, B);
3563       }
3564     }
3565     
3566     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3567       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3568         return ReplaceInstUsesWith(I, Op0);
3569
3570       // ~(A&B) & (A|B) -> A^B
3571       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3572         if ((A == C && B == D) || (A == D && B == C))
3573           return BinaryOperator::CreateXor(A, B);
3574       }
3575     }
3576     
3577     if (Op0->hasOneUse() &&
3578         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3579       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3580         I.swapOperands();     // Simplify below
3581         std::swap(Op0, Op1);
3582       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3583         cast<BinaryOperator>(Op0)->swapOperands();
3584         I.swapOperands();     // Simplify below
3585         std::swap(Op0, Op1);
3586       }
3587     }
3588     if (Op1->hasOneUse() &&
3589         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3590       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3591         cast<BinaryOperator>(Op1)->swapOperands();
3592         std::swap(A, B);
3593       }
3594       if (A == Op0) {                                // A&(A^B) -> A & ~B
3595         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3596         InsertNewInstBefore(NotB, I);
3597         return BinaryOperator::CreateAnd(A, NotB);
3598       }
3599     }
3600   }
3601   
3602   
3603   { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3604     // where C is a power of 2
3605     Value *A, *B;
3606     ConstantInt *C1, *C2;
3607     ICmpInst::Predicate LHSCC, RHSCC;
3608     if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3609                         m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3610       if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3611           (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3612         Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3613         InsertNewInstBefore(NewOr, I);
3614         return new ICmpInst(LHSCC, NewOr, C1);
3615       }
3616   }
3617
3618   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3619     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3620     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3621       return R;
3622
3623     Value *LHSVal, *RHSVal;
3624     ConstantInt *LHSCst, *RHSCst;
3625     ICmpInst::Predicate LHSCC, RHSCC;
3626     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3627       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3628         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3629             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3630             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3631             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3632             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3633             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3634             
3635             // Don't try to fold ICMP_SLT + ICMP_ULT.
3636             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3637              ICmpInst::isSignedPredicate(LHSCC) == 
3638                  ICmpInst::isSignedPredicate(RHSCC))) {
3639           // Ensure that the larger constant is on the RHS.
3640           ICmpInst::Predicate GT;
3641           if (ICmpInst::isSignedPredicate(LHSCC) ||
3642               (ICmpInst::isEquality(LHSCC) && 
3643                ICmpInst::isSignedPredicate(RHSCC)))
3644             GT = ICmpInst::ICMP_SGT;
3645           else
3646             GT = ICmpInst::ICMP_UGT;
3647           
3648           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3649           ICmpInst *LHS = cast<ICmpInst>(Op0);
3650           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3651             std::swap(LHS, RHS);
3652             std::swap(LHSCst, RHSCst);
3653             std::swap(LHSCC, RHSCC);
3654           }
3655
3656           // At this point, we know we have have two icmp instructions
3657           // comparing a value against two constants and and'ing the result
3658           // together.  Because of the above check, we know that we only have
3659           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3660           // (from the FoldICmpLogical check above), that the two constants 
3661           // are not equal and that the larger constant is on the RHS
3662           assert(LHSCst != RHSCst && "Compares not folded above?");
3663
3664           switch (LHSCC) {
3665           default: assert(0 && "Unknown integer condition code!");
3666           case ICmpInst::ICMP_EQ:
3667             switch (RHSCC) {
3668             default: assert(0 && "Unknown integer condition code!");
3669             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3670             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3671             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3672               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3673             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3674             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3675             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3676               return ReplaceInstUsesWith(I, LHS);
3677             }
3678           case ICmpInst::ICMP_NE:
3679             switch (RHSCC) {
3680             default: assert(0 && "Unknown integer condition code!");
3681             case ICmpInst::ICMP_ULT:
3682               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3683                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3684               break;                        // (X != 13 & X u< 15) -> no change
3685             case ICmpInst::ICMP_SLT:
3686               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3687                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3688               break;                        // (X != 13 & X s< 15) -> no change
3689             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3690             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3691             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3692               return ReplaceInstUsesWith(I, RHS);
3693             case ICmpInst::ICMP_NE:
3694               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3695                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3696                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3697                                                       LHSVal->getName()+".off");
3698                 InsertNewInstBefore(Add, I);
3699                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3700                                     ConstantInt::get(Add->getType(), 1));
3701               }
3702               break;                        // (X != 13 & X != 15) -> no change
3703             }
3704             break;
3705           case ICmpInst::ICMP_ULT:
3706             switch (RHSCC) {
3707             default: assert(0 && "Unknown integer condition code!");
3708             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3709             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3710               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3711             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3712               break;
3713             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3714             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3715               return ReplaceInstUsesWith(I, LHS);
3716             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3717               break;
3718             }
3719             break;
3720           case ICmpInst::ICMP_SLT:
3721             switch (RHSCC) {
3722             default: assert(0 && "Unknown integer condition code!");
3723             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3724             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3725               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3726             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3727               break;
3728             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3729             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3730               return ReplaceInstUsesWith(I, LHS);
3731             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3732               break;
3733             }
3734             break;
3735           case ICmpInst::ICMP_UGT:
3736             switch (RHSCC) {
3737             default: assert(0 && "Unknown integer condition code!");
3738             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3739             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3740               return ReplaceInstUsesWith(I, RHS);
3741             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3742               break;
3743             case ICmpInst::ICMP_NE:
3744               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3745                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3746               break;                        // (X u> 13 & X != 15) -> no change
3747             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3748               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3749                                      true, I);
3750             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3751               break;
3752             }
3753             break;
3754           case ICmpInst::ICMP_SGT:
3755             switch (RHSCC) {
3756             default: assert(0 && "Unknown integer condition code!");
3757             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3758             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3759               return ReplaceInstUsesWith(I, RHS);
3760             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3761               break;
3762             case ICmpInst::ICMP_NE:
3763               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3764                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3765               break;                        // (X s> 13 & X != 15) -> no change
3766             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3767               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3768                                      true, I);
3769             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3770               break;
3771             }
3772             break;
3773           }
3774         }
3775   }
3776
3777   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3778   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3779     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3780       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3781         const Type *SrcTy = Op0C->getOperand(0)->getType();
3782         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3783             // Only do this if the casts both really cause code to be generated.
3784             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3785                               I.getType(), TD) &&
3786             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3787                               I.getType(), TD)) {
3788           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3789                                                          Op1C->getOperand(0),
3790                                                          I.getName());
3791           InsertNewInstBefore(NewOp, I);
3792           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3793         }
3794       }
3795     
3796   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3797   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3798     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3799       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3800           SI0->getOperand(1) == SI1->getOperand(1) &&
3801           (SI0->hasOneUse() || SI1->hasOneUse())) {
3802         Instruction *NewOp =
3803           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3804                                                         SI1->getOperand(0),
3805                                                         SI0->getName()), I);
3806         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3807                                       SI1->getOperand(1));
3808       }
3809   }
3810
3811   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3812   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3813     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3814       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3815           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3816         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3817           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3818             // If either of the constants are nans, then the whole thing returns
3819             // false.
3820             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3821               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3822             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3823                                 RHS->getOperand(0));
3824           }
3825     }
3826   }
3827
3828   return Changed ? &I : 0;
3829 }
3830
3831 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3832 /// in the result.  If it does, and if the specified byte hasn't been filled in
3833 /// yet, fill it in and return false.
3834 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3835   Instruction *I = dyn_cast<Instruction>(V);
3836   if (I == 0) return true;
3837
3838   // If this is an or instruction, it is an inner node of the bswap.
3839   if (I->getOpcode() == Instruction::Or)
3840     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3841            CollectBSwapParts(I->getOperand(1), ByteValues);
3842   
3843   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3844   // If this is a shift by a constant int, and it is "24", then its operand
3845   // defines a byte.  We only handle unsigned types here.
3846   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3847     // Not shifting the entire input by N-1 bytes?
3848     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3849         8*(ByteValues.size()-1))
3850       return true;
3851     
3852     unsigned DestNo;
3853     if (I->getOpcode() == Instruction::Shl) {
3854       // X << 24 defines the top byte with the lowest of the input bytes.
3855       DestNo = ByteValues.size()-1;
3856     } else {
3857       // X >>u 24 defines the low byte with the highest of the input bytes.
3858       DestNo = 0;
3859     }
3860     
3861     // If the destination byte value is already defined, the values are or'd
3862     // together, which isn't a bswap (unless it's an or of the same bits).
3863     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3864       return true;
3865     ByteValues[DestNo] = I->getOperand(0);
3866     return false;
3867   }
3868   
3869   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3870   // don't have this.
3871   Value *Shift = 0, *ShiftLHS = 0;
3872   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3873   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3874       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3875     return true;
3876   Instruction *SI = cast<Instruction>(Shift);
3877
3878   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3879   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3880       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3881     return true;
3882   
3883   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3884   unsigned DestByte;
3885   if (AndAmt->getValue().getActiveBits() > 64)
3886     return true;
3887   uint64_t AndAmtVal = AndAmt->getZExtValue();
3888   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3889     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3890       break;
3891   // Unknown mask for bswap.
3892   if (DestByte == ByteValues.size()) return true;
3893   
3894   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3895   unsigned SrcByte;
3896   if (SI->getOpcode() == Instruction::Shl)
3897     SrcByte = DestByte - ShiftBytes;
3898   else
3899     SrcByte = DestByte + ShiftBytes;
3900   
3901   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3902   if (SrcByte != ByteValues.size()-DestByte-1)
3903     return true;
3904   
3905   // If the destination byte value is already defined, the values are or'd
3906   // together, which isn't a bswap (unless it's an or of the same bits).
3907   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3908     return true;
3909   ByteValues[DestByte] = SI->getOperand(0);
3910   return false;
3911 }
3912
3913 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3914 /// If so, insert the new bswap intrinsic and return it.
3915 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3916   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3917   if (!ITy || ITy->getBitWidth() % 16) 
3918     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3919   
3920   /// ByteValues - For each byte of the result, we keep track of which value
3921   /// defines each byte.
3922   SmallVector<Value*, 8> ByteValues;
3923   ByteValues.resize(ITy->getBitWidth()/8);
3924     
3925   // Try to find all the pieces corresponding to the bswap.
3926   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3927       CollectBSwapParts(I.getOperand(1), ByteValues))
3928     return 0;
3929   
3930   // Check to see if all of the bytes come from the same value.
3931   Value *V = ByteValues[0];
3932   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3933   
3934   // Check to make sure that all of the bytes come from the same value.
3935   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3936     if (ByteValues[i] != V)
3937       return 0;
3938   const Type *Tys[] = { ITy };
3939   Module *M = I.getParent()->getParent()->getParent();
3940   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3941   return CallInst::Create(F, V);
3942 }
3943
3944
3945 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3946   bool Changed = SimplifyCommutative(I);
3947   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3948
3949   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3950     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3951
3952   // or X, X = X
3953   if (Op0 == Op1)
3954     return ReplaceInstUsesWith(I, Op0);
3955
3956   // See if we can simplify any instructions used by the instruction whose sole 
3957   // purpose is to compute bits we don't care about.
3958   if (!isa<VectorType>(I.getType())) {
3959     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3960     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3961     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3962                              KnownZero, KnownOne))
3963       return &I;
3964   } else if (isa<ConstantAggregateZero>(Op1)) {
3965     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3966   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3967     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3968       return ReplaceInstUsesWith(I, I.getOperand(1));
3969   }
3970     
3971
3972   
3973   // or X, -1 == -1
3974   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3975     ConstantInt *C1 = 0; Value *X = 0;
3976     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3977     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3978       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3979       InsertNewInstBefore(Or, I);
3980       Or->takeName(Op0);
3981       return BinaryOperator::CreateAnd(Or, 
3982                ConstantInt::get(RHS->getValue() | C1->getValue()));
3983     }
3984
3985     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3986     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3987       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3988       InsertNewInstBefore(Or, I);
3989       Or->takeName(Op0);
3990       return BinaryOperator::CreateXor(Or,
3991                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3992     }
3993
3994     // Try to fold constant and into select arguments.
3995     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3996       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3997         return R;
3998     if (isa<PHINode>(Op0))
3999       if (Instruction *NV = FoldOpIntoPhi(I))
4000         return NV;
4001   }
4002
4003   Value *A = 0, *B = 0;
4004   ConstantInt *C1 = 0, *C2 = 0;
4005
4006   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4007     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4008       return ReplaceInstUsesWith(I, Op1);
4009   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4010     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4011       return ReplaceInstUsesWith(I, Op0);
4012
4013   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4014   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4015   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4016       match(Op1, m_Or(m_Value(), m_Value())) ||
4017       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4018        match(Op1, m_Shift(m_Value(), m_Value())))) {
4019     if (Instruction *BSwap = MatchBSwap(I))
4020       return BSwap;
4021   }
4022   
4023   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4024   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4025       MaskedValueIsZero(Op1, C1->getValue())) {
4026     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4027     InsertNewInstBefore(NOr, I);
4028     NOr->takeName(Op0);
4029     return BinaryOperator::CreateXor(NOr, C1);
4030   }
4031
4032   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4033   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4034       MaskedValueIsZero(Op0, C1->getValue())) {
4035     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4036     InsertNewInstBefore(NOr, I);
4037     NOr->takeName(Op0);
4038     return BinaryOperator::CreateXor(NOr, C1);
4039   }
4040
4041   // (A & C)|(B & D)
4042   Value *C = 0, *D = 0;
4043   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4044       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4045     Value *V1 = 0, *V2 = 0, *V3 = 0;
4046     C1 = dyn_cast<ConstantInt>(C);
4047     C2 = dyn_cast<ConstantInt>(D);
4048     if (C1 && C2) {  // (A & C1)|(B & C2)
4049       // If we have: ((V + N) & C1) | (V & C2)
4050       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4051       // replace with V+N.
4052       if (C1->getValue() == ~C2->getValue()) {
4053         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4054             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4055           // Add commutes, try both ways.
4056           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4057             return ReplaceInstUsesWith(I, A);
4058           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4059             return ReplaceInstUsesWith(I, A);
4060         }
4061         // Or commutes, try both ways.
4062         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4063             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4064           // Add commutes, try both ways.
4065           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4066             return ReplaceInstUsesWith(I, B);
4067           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4068             return ReplaceInstUsesWith(I, B);
4069         }
4070       }
4071       V1 = 0; V2 = 0; V3 = 0;
4072     }
4073     
4074     // Check to see if we have any common things being and'ed.  If so, find the
4075     // terms for V1 & (V2|V3).
4076     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4077       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4078         V1 = A, V2 = C, V3 = D;
4079       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4080         V1 = A, V2 = B, V3 = C;
4081       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4082         V1 = C, V2 = A, V3 = D;
4083       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4084         V1 = C, V2 = A, V3 = B;
4085       
4086       if (V1) {
4087         Value *Or =
4088           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4089         return BinaryOperator::CreateAnd(V1, Or);
4090       }
4091     }
4092   }
4093   
4094   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4095   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4096     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4097       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4098           SI0->getOperand(1) == SI1->getOperand(1) &&
4099           (SI0->hasOneUse() || SI1->hasOneUse())) {
4100         Instruction *NewOp =
4101         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4102                                                      SI1->getOperand(0),
4103                                                      SI0->getName()), I);
4104         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4105                                       SI1->getOperand(1));
4106       }
4107   }
4108
4109   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4110     if (A == Op1)   // ~A | A == -1
4111       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4112   } else {
4113     A = 0;
4114   }
4115   // Note, A is still live here!
4116   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4117     if (Op0 == B)
4118       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4119
4120     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4121     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4122       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4123                                               I.getName()+".demorgan"), I);
4124       return BinaryOperator::CreateNot(And);
4125     }
4126   }
4127
4128   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4129   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4130     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4131       return R;
4132
4133     Value *LHSVal, *RHSVal;
4134     ConstantInt *LHSCst, *RHSCst;
4135     ICmpInst::Predicate LHSCC, RHSCC;
4136     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4137       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4138         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4139             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4140             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4141             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4142             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4143             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4144             // We can't fold (ugt x, C) | (sgt x, C2).
4145             PredicatesFoldable(LHSCC, RHSCC)) {
4146           // Ensure that the larger constant is on the RHS.
4147           ICmpInst *LHS = cast<ICmpInst>(Op0);
4148           bool NeedsSwap;
4149           if (ICmpInst::isSignedPredicate(LHSCC))
4150             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4151           else
4152             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4153             
4154           if (NeedsSwap) {
4155             std::swap(LHS, RHS);
4156             std::swap(LHSCst, RHSCst);
4157             std::swap(LHSCC, RHSCC);
4158           }
4159
4160           // At this point, we know we have have two icmp instructions
4161           // comparing a value against two constants and or'ing the result
4162           // together.  Because of the above check, we know that we only have
4163           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4164           // FoldICmpLogical check above), that the two constants are not
4165           // equal.
4166           assert(LHSCst != RHSCst && "Compares not folded above?");
4167
4168           switch (LHSCC) {
4169           default: assert(0 && "Unknown integer condition code!");
4170           case ICmpInst::ICMP_EQ:
4171             switch (RHSCC) {
4172             default: assert(0 && "Unknown integer condition code!");
4173             case ICmpInst::ICMP_EQ:
4174               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4175                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4176                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4177                                                       LHSVal->getName()+".off");
4178                 InsertNewInstBefore(Add, I);
4179                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4180                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4181               }
4182               break;                         // (X == 13 | X == 15) -> no change
4183             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4184             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4185               break;
4186             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4187             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4188             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4189               return ReplaceInstUsesWith(I, RHS);
4190             }
4191             break;
4192           case ICmpInst::ICMP_NE:
4193             switch (RHSCC) {
4194             default: assert(0 && "Unknown integer condition code!");
4195             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4196             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4197             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4198               return ReplaceInstUsesWith(I, LHS);
4199             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4200             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4201             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4202               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4203             }
4204             break;
4205           case ICmpInst::ICMP_ULT:
4206             switch (RHSCC) {
4207             default: assert(0 && "Unknown integer condition code!");
4208             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4209               break;
4210             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4211               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4212               // this can cause overflow.
4213               if (RHSCst->isMaxValue(false))
4214                 return ReplaceInstUsesWith(I, LHS);
4215               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4216                                      false, I);
4217             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4218               break;
4219             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4220             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4221               return ReplaceInstUsesWith(I, RHS);
4222             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4223               break;
4224             }
4225             break;
4226           case ICmpInst::ICMP_SLT:
4227             switch (RHSCC) {
4228             default: assert(0 && "Unknown integer condition code!");
4229             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4230               break;
4231             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4232               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4233               // this can cause overflow.
4234               if (RHSCst->isMaxValue(true))
4235                 return ReplaceInstUsesWith(I, LHS);
4236               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4237                                      false, I);
4238             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4239               break;
4240             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4241             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4242               return ReplaceInstUsesWith(I, RHS);
4243             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4244               break;
4245             }
4246             break;
4247           case ICmpInst::ICMP_UGT:
4248             switch (RHSCC) {
4249             default: assert(0 && "Unknown integer condition code!");
4250             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4251             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4252               return ReplaceInstUsesWith(I, LHS);
4253             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4254               break;
4255             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4256             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4257               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4258             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4259               break;
4260             }
4261             break;
4262           case ICmpInst::ICMP_SGT:
4263             switch (RHSCC) {
4264             default: assert(0 && "Unknown integer condition code!");
4265             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4266             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4267               return ReplaceInstUsesWith(I, LHS);
4268             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4269               break;
4270             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4271             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4272               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4273             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4274               break;
4275             }
4276             break;
4277           }
4278         }
4279   }
4280     
4281   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4282   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4283     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4285         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4286             !isa<ICmpInst>(Op1C->getOperand(0))) {
4287           const Type *SrcTy = Op0C->getOperand(0)->getType();
4288           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4289               // Only do this if the casts both really cause code to be
4290               // generated.
4291               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4292                                 I.getType(), TD) &&
4293               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4294                                 I.getType(), TD)) {
4295             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4296                                                           Op1C->getOperand(0),
4297                                                           I.getName());
4298             InsertNewInstBefore(NewOp, I);
4299             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4300           }
4301         }
4302       }
4303   }
4304   
4305     
4306   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4307   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4308     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4309       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4310           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4311           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4312         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4313           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4314             // If either of the constants are nans, then the whole thing returns
4315             // true.
4316             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4317               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4318             
4319             // Otherwise, no need to compare the two constants, compare the
4320             // rest.
4321             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4322                                 RHS->getOperand(0));
4323           }
4324     }
4325   }
4326
4327   return Changed ? &I : 0;
4328 }
4329
4330 namespace {
4331
4332 // XorSelf - Implements: X ^ X --> 0
4333 struct XorSelf {
4334   Value *RHS;
4335   XorSelf(Value *rhs) : RHS(rhs) {}
4336   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4337   Instruction *apply(BinaryOperator &Xor) const {
4338     return &Xor;
4339   }
4340 };
4341
4342 }
4343
4344 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4345   bool Changed = SimplifyCommutative(I);
4346   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4347
4348   if (isa<UndefValue>(Op1)) {
4349     if (isa<UndefValue>(Op0))
4350       // Handle undef ^ undef -> 0 special case. This is a common
4351       // idiom (misuse).
4352       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4353     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4354   }
4355
4356   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4357   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4358     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4359     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4360   }
4361   
4362   // See if we can simplify any instructions used by the instruction whose sole 
4363   // purpose is to compute bits we don't care about.
4364   if (!isa<VectorType>(I.getType())) {
4365     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4366     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4367     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4368                              KnownZero, KnownOne))
4369       return &I;
4370   } else if (isa<ConstantAggregateZero>(Op1)) {
4371     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4372   }
4373
4374   // Is this a ~ operation?
4375   if (Value *NotOp = dyn_castNotVal(&I)) {
4376     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4377     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4378     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4379       if (Op0I->getOpcode() == Instruction::And || 
4380           Op0I->getOpcode() == Instruction::Or) {
4381         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4382         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4383           Instruction *NotY =
4384             BinaryOperator::CreateNot(Op0I->getOperand(1),
4385                                       Op0I->getOperand(1)->getName()+".not");
4386           InsertNewInstBefore(NotY, I);
4387           if (Op0I->getOpcode() == Instruction::And)
4388             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4389           else
4390             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4391         }
4392       }
4393     }
4394   }
4395   
4396   
4397   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4398     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4399     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4400       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4401         return new ICmpInst(ICI->getInversePredicate(),
4402                             ICI->getOperand(0), ICI->getOperand(1));
4403
4404       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4405         return new FCmpInst(FCI->getInversePredicate(),
4406                             FCI->getOperand(0), FCI->getOperand(1));
4407     }
4408
4409     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4410     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4411       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4412         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4413           Instruction::CastOps Opcode = Op0C->getOpcode();
4414           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4415             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4416                                              Op0C->getDestTy())) {
4417               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4418                                      CI->getOpcode(), CI->getInversePredicate(),
4419                                      CI->getOperand(0), CI->getOperand(1)), I);
4420               NewCI->takeName(CI);
4421               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4422             }
4423           }
4424         }
4425       }
4426     }
4427
4428     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4429       // ~(c-X) == X-c-1 == X+(-c-1)
4430       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4431         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4432           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4433           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4434                                               ConstantInt::get(I.getType(), 1));
4435           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4436         }
4437           
4438       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4439         if (Op0I->getOpcode() == Instruction::Add) {
4440           // ~(X-c) --> (-c-1)-X
4441           if (RHS->isAllOnesValue()) {
4442             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4443             return BinaryOperator::CreateSub(
4444                            ConstantExpr::getSub(NegOp0CI,
4445                                              ConstantInt::get(I.getType(), 1)),
4446                                           Op0I->getOperand(0));
4447           } else if (RHS->getValue().isSignBit()) {
4448             // (X + C) ^ signbit -> (X + C + signbit)
4449             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4450             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4451
4452           }
4453         } else if (Op0I->getOpcode() == Instruction::Or) {
4454           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4455           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4456             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4457             // Anything in both C1 and C2 is known to be zero, remove it from
4458             // NewRHS.
4459             Constant *CommonBits = And(Op0CI, RHS);
4460             NewRHS = ConstantExpr::getAnd(NewRHS, 
4461                                           ConstantExpr::getNot(CommonBits));
4462             AddToWorkList(Op0I);
4463             I.setOperand(0, Op0I->getOperand(0));
4464             I.setOperand(1, NewRHS);
4465             return &I;
4466           }
4467         }
4468       }
4469     }
4470
4471     // Try to fold constant and into select arguments.
4472     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4473       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4474         return R;
4475     if (isa<PHINode>(Op0))
4476       if (Instruction *NV = FoldOpIntoPhi(I))
4477         return NV;
4478   }
4479
4480   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4481     if (X == Op1)
4482       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4483
4484   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4485     if (X == Op0)
4486       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4487
4488   
4489   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4490   if (Op1I) {
4491     Value *A, *B;
4492     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4493       if (A == Op0) {              // B^(B|A) == (A|B)^B
4494         Op1I->swapOperands();
4495         I.swapOperands();
4496         std::swap(Op0, Op1);
4497       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4498         I.swapOperands();     // Simplified below.
4499         std::swap(Op0, Op1);
4500       }
4501     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4502       if (Op0 == A)                                          // A^(A^B) == B
4503         return ReplaceInstUsesWith(I, B);
4504       else if (Op0 == B)                                     // A^(B^A) == B
4505         return ReplaceInstUsesWith(I, A);
4506     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4507       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4508         Op1I->swapOperands();
4509         std::swap(A, B);
4510       }
4511       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4512         I.swapOperands();     // Simplified below.
4513         std::swap(Op0, Op1);
4514       }
4515     }
4516   }
4517   
4518   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4519   if (Op0I) {
4520     Value *A, *B;
4521     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4522       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4523         std::swap(A, B);
4524       if (B == Op1) {                                // (A|B)^B == A & ~B
4525         Instruction *NotB =
4526           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4527         return BinaryOperator::CreateAnd(A, NotB);
4528       }
4529     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4530       if (Op1 == A)                                          // (A^B)^A == B
4531         return ReplaceInstUsesWith(I, B);
4532       else if (Op1 == B)                                     // (B^A)^A == B
4533         return ReplaceInstUsesWith(I, A);
4534     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4535       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4536         std::swap(A, B);
4537       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4538           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4539         Instruction *N =
4540           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4541         return BinaryOperator::CreateAnd(N, Op1);
4542       }
4543     }
4544   }
4545   
4546   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4547   if (Op0I && Op1I && Op0I->isShift() && 
4548       Op0I->getOpcode() == Op1I->getOpcode() && 
4549       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4550       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4551     Instruction *NewOp =
4552       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4553                                                     Op1I->getOperand(0),
4554                                                     Op0I->getName()), I);
4555     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4556                                   Op1I->getOperand(1));
4557   }
4558     
4559   if (Op0I && Op1I) {
4560     Value *A, *B, *C, *D;
4561     // (A & B)^(A | B) -> A ^ B
4562     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4563         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4564       if ((A == C && B == D) || (A == D && B == C)) 
4565         return BinaryOperator::CreateXor(A, B);
4566     }
4567     // (A | B)^(A & B) -> A ^ B
4568     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4569         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4570       if ((A == C && B == D) || (A == D && B == C)) 
4571         return BinaryOperator::CreateXor(A, B);
4572     }
4573     
4574     // (A & B)^(C & D)
4575     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4576         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4577         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4578       // (X & Y)^(X & Y) -> (Y^Z) & X
4579       Value *X = 0, *Y = 0, *Z = 0;
4580       if (A == C)
4581         X = A, Y = B, Z = D;
4582       else if (A == D)
4583         X = A, Y = B, Z = C;
4584       else if (B == C)
4585         X = B, Y = A, Z = D;
4586       else if (B == D)
4587         X = B, Y = A, Z = C;
4588       
4589       if (X) {
4590         Instruction *NewOp =
4591         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4592         return BinaryOperator::CreateAnd(NewOp, X);
4593       }
4594     }
4595   }
4596     
4597   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4598   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4599     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4600       return R;
4601
4602   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4603   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4604     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4605       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4606         const Type *SrcTy = Op0C->getOperand(0)->getType();
4607         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4608             // Only do this if the casts both really cause code to be generated.
4609             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4610                               I.getType(), TD) &&
4611             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4612                               I.getType(), TD)) {
4613           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4614                                                          Op1C->getOperand(0),
4615                                                          I.getName());
4616           InsertNewInstBefore(NewOp, I);
4617           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4618         }
4619       }
4620   }
4621
4622   return Changed ? &I : 0;
4623 }
4624
4625 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4626 /// overflowed for this type.
4627 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4628                             ConstantInt *In2, bool IsSigned = false) {
4629   Result = cast<ConstantInt>(Add(In1, In2));
4630
4631   if (IsSigned)
4632     if (In2->getValue().isNegative())
4633       return Result->getValue().sgt(In1->getValue());
4634     else
4635       return Result->getValue().slt(In1->getValue());
4636   else
4637     return Result->getValue().ult(In1->getValue());
4638 }
4639
4640 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4641 /// code necessary to compute the offset from the base pointer (without adding
4642 /// in the base pointer).  Return the result as a signed integer of intptr size.
4643 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4644   TargetData &TD = IC.getTargetData();
4645   gep_type_iterator GTI = gep_type_begin(GEP);
4646   const Type *IntPtrTy = TD.getIntPtrType();
4647   Value *Result = Constant::getNullValue(IntPtrTy);
4648
4649   // Build a mask for high order bits.
4650   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4651   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4652
4653   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4654        ++i, ++GTI) {
4655     Value *Op = *i;
4656     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4657     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4658       if (OpC->isZero()) continue;
4659       
4660       // Handle a struct index, which adds its field offset to the pointer.
4661       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4662         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4663         
4664         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4665           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4666         else
4667           Result = IC.InsertNewInstBefore(
4668                    BinaryOperator::CreateAdd(Result,
4669                                              ConstantInt::get(IntPtrTy, Size),
4670                                              GEP->getName()+".offs"), I);
4671         continue;
4672       }
4673       
4674       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4675       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4676       Scale = ConstantExpr::getMul(OC, Scale);
4677       if (Constant *RC = dyn_cast<Constant>(Result))
4678         Result = ConstantExpr::getAdd(RC, Scale);
4679       else {
4680         // Emit an add instruction.
4681         Result = IC.InsertNewInstBefore(
4682            BinaryOperator::CreateAdd(Result, Scale,
4683                                      GEP->getName()+".offs"), I);
4684       }
4685       continue;
4686     }
4687     // Convert to correct type.
4688     if (Op->getType() != IntPtrTy) {
4689       if (Constant *OpC = dyn_cast<Constant>(Op))
4690         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4691       else
4692         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4693                                                  Op->getName()+".c"), I);
4694     }
4695     if (Size != 1) {
4696       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4697       if (Constant *OpC = dyn_cast<Constant>(Op))
4698         Op = ConstantExpr::getMul(OpC, Scale);
4699       else    // We'll let instcombine(mul) convert this to a shl if possible.
4700         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4701                                                   GEP->getName()+".idx"), I);
4702     }
4703
4704     // Emit an add instruction.
4705     if (isa<Constant>(Op) && isa<Constant>(Result))
4706       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4707                                     cast<Constant>(Result));
4708     else
4709       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4710                                                   GEP->getName()+".offs"), I);
4711   }
4712   return Result;
4713 }
4714
4715
4716 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4717 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4718 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4719 /// complex, and scales are involved.  The above expression would also be legal
4720 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4721 /// later form is less amenable to optimization though, and we are allowed to
4722 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4723 ///
4724 /// If we can't emit an optimized form for this expression, this returns null.
4725 /// 
4726 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4727                                           InstCombiner &IC) {
4728   TargetData &TD = IC.getTargetData();
4729   gep_type_iterator GTI = gep_type_begin(GEP);
4730
4731   // Check to see if this gep only has a single variable index.  If so, and if
4732   // any constant indices are a multiple of its scale, then we can compute this
4733   // in terms of the scale of the variable index.  For example, if the GEP
4734   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4735   // because the expression will cross zero at the same point.
4736   unsigned i, e = GEP->getNumOperands();
4737   int64_t Offset = 0;
4738   for (i = 1; i != e; ++i, ++GTI) {
4739     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4740       // Compute the aggregate offset of constant indices.
4741       if (CI->isZero()) continue;
4742
4743       // Handle a struct index, which adds its field offset to the pointer.
4744       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4745         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4746       } else {
4747         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4748         Offset += Size*CI->getSExtValue();
4749       }
4750     } else {
4751       // Found our variable index.
4752       break;
4753     }
4754   }
4755   
4756   // If there are no variable indices, we must have a constant offset, just
4757   // evaluate it the general way.
4758   if (i == e) return 0;
4759   
4760   Value *VariableIdx = GEP->getOperand(i);
4761   // Determine the scale factor of the variable element.  For example, this is
4762   // 4 if the variable index is into an array of i32.
4763   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4764   
4765   // Verify that there are no other variable indices.  If so, emit the hard way.
4766   for (++i, ++GTI; i != e; ++i, ++GTI) {
4767     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4768     if (!CI) return 0;
4769    
4770     // Compute the aggregate offset of constant indices.
4771     if (CI->isZero()) continue;
4772     
4773     // Handle a struct index, which adds its field offset to the pointer.
4774     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4775       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4776     } else {
4777       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4778       Offset += Size*CI->getSExtValue();
4779     }
4780   }
4781   
4782   // Okay, we know we have a single variable index, which must be a
4783   // pointer/array/vector index.  If there is no offset, life is simple, return
4784   // the index.
4785   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4786   if (Offset == 0) {
4787     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4788     // we don't need to bother extending: the extension won't affect where the
4789     // computation crosses zero.
4790     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4791       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4792                                   VariableIdx->getNameStart(), &I);
4793     return VariableIdx;
4794   }
4795   
4796   // Otherwise, there is an index.  The computation we will do will be modulo
4797   // the pointer size, so get it.
4798   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4799   
4800   Offset &= PtrSizeMask;
4801   VariableScale &= PtrSizeMask;
4802
4803   // To do this transformation, any constant index must be a multiple of the
4804   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4805   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4806   // multiple of the variable scale.
4807   int64_t NewOffs = Offset / (int64_t)VariableScale;
4808   if (Offset != NewOffs*(int64_t)VariableScale)
4809     return 0;
4810
4811   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4812   const Type *IntPtrTy = TD.getIntPtrType();
4813   if (VariableIdx->getType() != IntPtrTy)
4814     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4815                                               true /*SExt*/, 
4816                                               VariableIdx->getNameStart(), &I);
4817   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4818   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4819 }
4820
4821
4822 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4823 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4824 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4825                                        ICmpInst::Predicate Cond,
4826                                        Instruction &I) {
4827   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4828
4829   // Look through bitcasts.
4830   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4831     RHS = BCI->getOperand(0);
4832
4833   Value *PtrBase = GEPLHS->getOperand(0);
4834   if (PtrBase == RHS) {
4835     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4836     // This transformation (ignoring the base and scales) is valid because we
4837     // know pointers can't overflow.  See if we can output an optimized form.
4838     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4839     
4840     // If not, synthesize the offset the hard way.
4841     if (Offset == 0)
4842       Offset = EmitGEPOffset(GEPLHS, I, *this);
4843     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4844                         Constant::getNullValue(Offset->getType()));
4845   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4846     // If the base pointers are different, but the indices are the same, just
4847     // compare the base pointer.
4848     if (PtrBase != GEPRHS->getOperand(0)) {
4849       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4850       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4851                         GEPRHS->getOperand(0)->getType();
4852       if (IndicesTheSame)
4853         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4854           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4855             IndicesTheSame = false;
4856             break;
4857           }
4858
4859       // If all indices are the same, just compare the base pointers.
4860       if (IndicesTheSame)
4861         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4862                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4863
4864       // Otherwise, the base pointers are different and the indices are
4865       // different, bail out.
4866       return 0;
4867     }
4868
4869     // If one of the GEPs has all zero indices, recurse.
4870     bool AllZeros = true;
4871     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4872       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4873           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4874         AllZeros = false;
4875         break;
4876       }
4877     if (AllZeros)
4878       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4879                           ICmpInst::getSwappedPredicate(Cond), I);
4880
4881     // If the other GEP has all zero indices, recurse.
4882     AllZeros = true;
4883     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4884       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4885           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4886         AllZeros = false;
4887         break;
4888       }
4889     if (AllZeros)
4890       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4891
4892     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4893       // If the GEPs only differ by one index, compare it.
4894       unsigned NumDifferences = 0;  // Keep track of # differences.
4895       unsigned DiffOperand = 0;     // The operand that differs.
4896       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4897         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4898           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4899                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4900             // Irreconcilable differences.
4901             NumDifferences = 2;
4902             break;
4903           } else {
4904             if (NumDifferences++) break;
4905             DiffOperand = i;
4906           }
4907         }
4908
4909       if (NumDifferences == 0)   // SAME GEP?
4910         return ReplaceInstUsesWith(I, // No comparison is needed here.
4911                                    ConstantInt::get(Type::Int1Ty,
4912                                              ICmpInst::isTrueWhenEqual(Cond)));
4913
4914       else if (NumDifferences == 1) {
4915         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4916         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4917         // Make sure we do a signed comparison here.
4918         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4919       }
4920     }
4921
4922     // Only lower this if the icmp is the only user of the GEP or if we expect
4923     // the result to fold to a constant!
4924     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4925         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4926       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4927       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4928       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4929       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4930     }
4931   }
4932   return 0;
4933 }
4934
4935 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4936 ///
4937 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4938                                                 Instruction *LHSI,
4939                                                 Constant *RHSC) {
4940   if (!isa<ConstantFP>(RHSC)) return 0;
4941   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4942   
4943   // Get the width of the mantissa.  We don't want to hack on conversions that
4944   // might lose information from the integer, e.g. "i64 -> float"
4945   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4946   if (MantissaWidth == -1) return 0;  // Unknown.
4947   
4948   // Check to see that the input is converted from an integer type that is small
4949   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4950   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4951   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4952   
4953   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4954   if (isa<UIToFPInst>(LHSI))
4955     ++InputSize;
4956   
4957   // If the conversion would lose info, don't hack on this.
4958   if ((int)InputSize > MantissaWidth)
4959     return 0;
4960   
4961   // Otherwise, we can potentially simplify the comparison.  We know that it
4962   // will always come through as an integer value and we know the constant is
4963   // not a NAN (it would have been previously simplified).
4964   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4965   
4966   ICmpInst::Predicate Pred;
4967   switch (I.getPredicate()) {
4968   default: assert(0 && "Unexpected predicate!");
4969   case FCmpInst::FCMP_UEQ:
4970   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4971   case FCmpInst::FCMP_UGT:
4972   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4973   case FCmpInst::FCMP_UGE:
4974   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4975   case FCmpInst::FCMP_ULT:
4976   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4977   case FCmpInst::FCMP_ULE:
4978   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4979   case FCmpInst::FCMP_UNE:
4980   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4981   case FCmpInst::FCMP_ORD:
4982     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4983   case FCmpInst::FCMP_UNO:
4984     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4985   }
4986   
4987   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4988   
4989   // Now we know that the APFloat is a normal number, zero or inf.
4990   
4991   // See if the FP constant is too large for the integer.  For example,
4992   // comparing an i8 to 300.0.
4993   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4994   
4995   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4996   // and large values. 
4997   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4998   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4999                         APFloat::rmNearestTiesToEven);
5000   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5001     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5002         Pred == ICmpInst::ICMP_SLE)
5003       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5004     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5005   }
5006   
5007   // See if the RHS value is < SignedMin.
5008   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5009   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5010                         APFloat::rmNearestTiesToEven);
5011   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5012     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5013         Pred == ICmpInst::ICMP_SGE)
5014       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5015     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5016   }
5017
5018   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5019   // it may still be fractional.  See if it is fractional by casting the FP
5020   // value to the integer value and back, checking for equality.  Don't do this
5021   // for zero, because -0.0 is not fractional.
5022   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5023   if (!RHS.isZero() &&
5024       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5025     // If we had a comparison against a fractional value, we have to adjust
5026     // the compare predicate and sometimes the value.  RHSC is rounded towards
5027     // zero at this point.
5028     switch (Pred) {
5029     default: assert(0 && "Unexpected integer comparison!");
5030     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5031       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5032     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5033       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5034     case ICmpInst::ICMP_SLE:
5035       // (float)int <= 4.4   --> int <= 4
5036       // (float)int <= -4.4  --> int < -4
5037       if (RHS.isNegative())
5038         Pred = ICmpInst::ICMP_SLT;
5039       break;
5040     case ICmpInst::ICMP_SLT:
5041       // (float)int < -4.4   --> int < -4
5042       // (float)int < 4.4    --> int <= 4
5043       if (!RHS.isNegative())
5044         Pred = ICmpInst::ICMP_SLE;
5045       break;
5046     case ICmpInst::ICMP_SGT:
5047       // (float)int > 4.4    --> int > 4
5048       // (float)int > -4.4   --> int >= -4
5049       if (RHS.isNegative())
5050         Pred = ICmpInst::ICMP_SGE;
5051       break;
5052     case ICmpInst::ICMP_SGE:
5053       // (float)int >= -4.4   --> int >= -4
5054       // (float)int >= 4.4    --> int > 4
5055       if (!RHS.isNegative())
5056         Pred = ICmpInst::ICMP_SGT;
5057       break;
5058     }
5059   }
5060
5061   // Lower this FP comparison into an appropriate integer version of the
5062   // comparison.
5063   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5064 }
5065
5066 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5067   bool Changed = SimplifyCompare(I);
5068   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5069
5070   // Fold trivial predicates.
5071   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5072     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5073   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5074     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5075   
5076   // Simplify 'fcmp pred X, X'
5077   if (Op0 == Op1) {
5078     switch (I.getPredicate()) {
5079     default: assert(0 && "Unknown predicate!");
5080     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5081     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5082     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5083       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5084     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5085     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5086     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5087       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5088       
5089     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5090     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5091     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5092     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5093       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5094       I.setPredicate(FCmpInst::FCMP_UNO);
5095       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5096       return &I;
5097       
5098     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5099     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5100     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5101     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5102       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5103       I.setPredicate(FCmpInst::FCMP_ORD);
5104       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5105       return &I;
5106     }
5107   }
5108     
5109   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5110     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5111
5112   // Handle fcmp with constant RHS
5113   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5114     // If the constant is a nan, see if we can fold the comparison based on it.
5115     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5116       if (CFP->getValueAPF().isNaN()) {
5117         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5118           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5119         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5120                "Comparison must be either ordered or unordered!");
5121         // True if unordered.
5122         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5123       }
5124     }
5125     
5126     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5127       switch (LHSI->getOpcode()) {
5128       case Instruction::PHI:
5129         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5130         // block.  If in the same block, we're encouraging jump threading.  If
5131         // not, we are just pessimizing the code by making an i1 phi.
5132         if (LHSI->getParent() == I.getParent())
5133           if (Instruction *NV = FoldOpIntoPhi(I))
5134             return NV;
5135         break;
5136       case Instruction::SIToFP:
5137       case Instruction::UIToFP:
5138         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5139           return NV;
5140         break;
5141       case Instruction::Select:
5142         // If either operand of the select is a constant, we can fold the
5143         // comparison into the select arms, which will cause one to be
5144         // constant folded and the select turned into a bitwise or.
5145         Value *Op1 = 0, *Op2 = 0;
5146         if (LHSI->hasOneUse()) {
5147           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5148             // Fold the known value into the constant operand.
5149             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5150             // Insert a new FCmp of the other select operand.
5151             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5152                                                       LHSI->getOperand(2), RHSC,
5153                                                       I.getName()), I);
5154           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5155             // Fold the known value into the constant operand.
5156             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5157             // Insert a new FCmp of the other select operand.
5158             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5159                                                       LHSI->getOperand(1), RHSC,
5160                                                       I.getName()), I);
5161           }
5162         }
5163
5164         if (Op1)
5165           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5166         break;
5167       }
5168   }
5169
5170   return Changed ? &I : 0;
5171 }
5172
5173 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5174   bool Changed = SimplifyCompare(I);
5175   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5176   const Type *Ty = Op0->getType();
5177
5178   // icmp X, X
5179   if (Op0 == Op1)
5180     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5181                                                    I.isTrueWhenEqual()));
5182
5183   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5184     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5185   
5186   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5187   // addresses never equal each other!  We already know that Op0 != Op1.
5188   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5189        isa<ConstantPointerNull>(Op0)) &&
5190       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5191        isa<ConstantPointerNull>(Op1)))
5192     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5193                                                    !I.isTrueWhenEqual()));
5194
5195   // icmp's with boolean values can always be turned into bitwise operations
5196   if (Ty == Type::Int1Ty) {
5197     switch (I.getPredicate()) {
5198     default: assert(0 && "Invalid icmp instruction!");
5199     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5200       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5201       InsertNewInstBefore(Xor, I);
5202       return BinaryOperator::CreateNot(Xor);
5203     }
5204     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5205       return BinaryOperator::CreateXor(Op0, Op1);
5206
5207     case ICmpInst::ICMP_UGT:
5208       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5209       // FALL THROUGH
5210     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5211       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5212       InsertNewInstBefore(Not, I);
5213       return BinaryOperator::CreateAnd(Not, Op1);
5214     }
5215     case ICmpInst::ICMP_SGT:
5216       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5217       // FALL THROUGH
5218     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5219       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5220       InsertNewInstBefore(Not, I);
5221       return BinaryOperator::CreateAnd(Not, Op0);
5222     }
5223     case ICmpInst::ICMP_UGE:
5224       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5225       // FALL THROUGH
5226     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5227       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5228       InsertNewInstBefore(Not, I);
5229       return BinaryOperator::CreateOr(Not, Op1);
5230     }
5231     case ICmpInst::ICMP_SGE:
5232       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5233       // FALL THROUGH
5234     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5235       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5236       InsertNewInstBefore(Not, I);
5237       return BinaryOperator::CreateOr(Not, Op0);
5238     }
5239     }
5240   }
5241
5242   // See if we are doing a comparison between a constant and an instruction that
5243   // can be folded into the comparison.
5244   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5245     Value *A, *B;
5246     
5247     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5248     if (I.isEquality() && CI->isNullValue() &&
5249         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5250       // (icmp cond A B) if cond is equality
5251       return new ICmpInst(I.getPredicate(), A, B);
5252     }
5253     
5254     switch (I.getPredicate()) {
5255     default: break;
5256     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5257       if (CI->isMinValue(false))
5258         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5259       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5260         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5261       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5262         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5263       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5264       if (CI->isMinValue(true))
5265         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5266                             ConstantInt::getAllOnesValue(Op0->getType()));
5267           
5268       break;
5269
5270     case ICmpInst::ICMP_SLT:
5271       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5272         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5273       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5274         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5275       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5276         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5277       break;
5278
5279     case ICmpInst::ICMP_UGT:
5280       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5281         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5282       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5283         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5284       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5285         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5286         
5287       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5288       if (CI->isMaxValue(true))
5289         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5290                             ConstantInt::getNullValue(Op0->getType()));
5291       break;
5292
5293     case ICmpInst::ICMP_SGT:
5294       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5295         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5296       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5297         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5298       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5299         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5300       break;
5301
5302     case ICmpInst::ICMP_ULE:
5303       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5304         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5305       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5306         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5307       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5308         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5309       break;
5310
5311     case ICmpInst::ICMP_SLE:
5312       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5313         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5314       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5315         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5316       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5317         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5318       break;
5319
5320     case ICmpInst::ICMP_UGE:
5321       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5322         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5323       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5324         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5325       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5326         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5327       break;
5328
5329     case ICmpInst::ICMP_SGE:
5330       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5331         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5332       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5333         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5334       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5335         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5336       break;
5337     }
5338
5339     // If we still have a icmp le or icmp ge instruction, turn it into the
5340     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5341     // already been handled above, this requires little checking.
5342     //
5343     switch (I.getPredicate()) {
5344     default: break;
5345     case ICmpInst::ICMP_ULE: 
5346       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5347     case ICmpInst::ICMP_SLE:
5348       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5349     case ICmpInst::ICMP_UGE:
5350       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5351     case ICmpInst::ICMP_SGE:
5352       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5353     }
5354     
5355     // See if we can fold the comparison based on bits known to be zero or one
5356     // in the input.  If this comparison is a normal comparison, it demands all
5357     // bits, if it is a sign bit comparison, it only demands the sign bit.
5358     
5359     bool UnusedBit;
5360     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5361     
5362     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5363     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5364     if (SimplifyDemandedBits(Op0, 
5365                              isSignBit ? APInt::getSignBit(BitWidth)
5366                                        : APInt::getAllOnesValue(BitWidth),
5367                              KnownZero, KnownOne, 0))
5368       return &I;
5369         
5370     // Given the known and unknown bits, compute a range that the LHS could be
5371     // in.
5372     if ((KnownOne | KnownZero) != 0) {
5373       // Compute the Min, Max and RHS values based on the known bits. For the
5374       // EQ and NE we use unsigned values.
5375       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5376       const APInt& RHSVal = CI->getValue();
5377       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5378         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5379                                                Max);
5380       } else {
5381         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5382                                                  Max);
5383       }
5384       switch (I.getPredicate()) {  // LE/GE have been folded already.
5385       default: assert(0 && "Unknown icmp opcode!");
5386       case ICmpInst::ICMP_EQ:
5387         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5388           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5389         break;
5390       case ICmpInst::ICMP_NE:
5391         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5392           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5393         break;
5394       case ICmpInst::ICMP_ULT:
5395         if (Max.ult(RHSVal))
5396           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5397         if (Min.uge(RHSVal))
5398           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5399         break;
5400       case ICmpInst::ICMP_UGT:
5401         if (Min.ugt(RHSVal))
5402           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5403         if (Max.ule(RHSVal))
5404           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5405         break;
5406       case ICmpInst::ICMP_SLT:
5407         if (Max.slt(RHSVal))
5408           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5409         if (Min.sgt(RHSVal))
5410           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5411         if (Max == RHSVal)  // A <s MAX -> A != MAX
5412           return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5413         break;
5414       case ICmpInst::ICMP_SGT: 
5415         if (Min.sgt(RHSVal))
5416           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5417         if (Max.sle(RHSVal))
5418           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5419         break;
5420       }
5421     }
5422           
5423     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5424     // instruction, see if that instruction also has constants so that the 
5425     // instruction can be folded into the icmp 
5426     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5427       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5428         return Res;
5429   }
5430
5431   // Handle icmp with constant (but not simple integer constant) RHS
5432   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5433     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5434       switch (LHSI->getOpcode()) {
5435       case Instruction::GetElementPtr:
5436         if (RHSC->isNullValue()) {
5437           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5438           bool isAllZeros = true;
5439           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5440             if (!isa<Constant>(LHSI->getOperand(i)) ||
5441                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5442               isAllZeros = false;
5443               break;
5444             }
5445           if (isAllZeros)
5446             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5447                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5448         }
5449         break;
5450
5451       case Instruction::PHI:
5452         // Only fold icmp into the PHI if the phi and fcmp are in the same
5453         // block.  If in the same block, we're encouraging jump threading.  If
5454         // not, we are just pessimizing the code by making an i1 phi.
5455         if (LHSI->getParent() == I.getParent())
5456           if (Instruction *NV = FoldOpIntoPhi(I))
5457             return NV;
5458         break;
5459       case Instruction::Select: {
5460         // If either operand of the select is a constant, we can fold the
5461         // comparison into the select arms, which will cause one to be
5462         // constant folded and the select turned into a bitwise or.
5463         Value *Op1 = 0, *Op2 = 0;
5464         if (LHSI->hasOneUse()) {
5465           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5466             // Fold the known value into the constant operand.
5467             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5468             // Insert a new ICmp of the other select operand.
5469             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5470                                                    LHSI->getOperand(2), RHSC,
5471                                                    I.getName()), I);
5472           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5473             // Fold the known value into the constant operand.
5474             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5475             // Insert a new ICmp of the other select operand.
5476             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5477                                                    LHSI->getOperand(1), RHSC,
5478                                                    I.getName()), I);
5479           }
5480         }
5481
5482         if (Op1)
5483           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5484         break;
5485       }
5486       case Instruction::Malloc:
5487         // If we have (malloc != null), and if the malloc has a single use, we
5488         // can assume it is successful and remove the malloc.
5489         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5490           AddToWorkList(LHSI);
5491           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5492                                                          !I.isTrueWhenEqual()));
5493         }
5494         break;
5495       }
5496   }
5497
5498   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5499   if (User *GEP = dyn_castGetElementPtr(Op0))
5500     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5501       return NI;
5502   if (User *GEP = dyn_castGetElementPtr(Op1))
5503     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5504                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5505       return NI;
5506
5507   // Test to see if the operands of the icmp are casted versions of other
5508   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5509   // now.
5510   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5511     if (isa<PointerType>(Op0->getType()) && 
5512         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5513       // We keep moving the cast from the left operand over to the right
5514       // operand, where it can often be eliminated completely.
5515       Op0 = CI->getOperand(0);
5516
5517       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5518       // so eliminate it as well.
5519       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5520         Op1 = CI2->getOperand(0);
5521
5522       // If Op1 is a constant, we can fold the cast into the constant.
5523       if (Op0->getType() != Op1->getType()) {
5524         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5525           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5526         } else {
5527           // Otherwise, cast the RHS right before the icmp
5528           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5529         }
5530       }
5531       return new ICmpInst(I.getPredicate(), Op0, Op1);
5532     }
5533   }
5534   
5535   if (isa<CastInst>(Op0)) {
5536     // Handle the special case of: icmp (cast bool to X), <cst>
5537     // This comes up when you have code like
5538     //   int X = A < B;
5539     //   if (X) ...
5540     // For generality, we handle any zero-extension of any operand comparison
5541     // with a constant or another cast from the same type.
5542     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5543       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5544         return R;
5545   }
5546   
5547   // ~x < ~y --> y < x
5548   { Value *A, *B;
5549     if (match(Op0, m_Not(m_Value(A))) &&
5550         match(Op1, m_Not(m_Value(B))))
5551       return new ICmpInst(I.getPredicate(), B, A);
5552   }
5553   
5554   if (I.isEquality()) {
5555     Value *A, *B, *C, *D;
5556     
5557     // -x == -y --> x == y
5558     if (match(Op0, m_Neg(m_Value(A))) &&
5559         match(Op1, m_Neg(m_Value(B))))
5560       return new ICmpInst(I.getPredicate(), A, B);
5561     
5562     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5563       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5564         Value *OtherVal = A == Op1 ? B : A;
5565         return new ICmpInst(I.getPredicate(), OtherVal,
5566                             Constant::getNullValue(A->getType()));
5567       }
5568
5569       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5570         // A^c1 == C^c2 --> A == C^(c1^c2)
5571         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5572           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5573             if (Op1->hasOneUse()) {
5574               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5575               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5576               return new ICmpInst(I.getPredicate(), A,
5577                                   InsertNewInstBefore(Xor, I));
5578             }
5579         
5580         // A^B == A^D -> B == D
5581         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5582         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5583         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5584         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5585       }
5586     }
5587     
5588     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5589         (A == Op0 || B == Op0)) {
5590       // A == (A^B)  ->  B == 0
5591       Value *OtherVal = A == Op0 ? B : A;
5592       return new ICmpInst(I.getPredicate(), OtherVal,
5593                           Constant::getNullValue(A->getType()));
5594     }
5595     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5596       // (A-B) == A  ->  B == 0
5597       return new ICmpInst(I.getPredicate(), B,
5598                           Constant::getNullValue(B->getType()));
5599     }
5600     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5601       // A == (A-B)  ->  B == 0
5602       return new ICmpInst(I.getPredicate(), B,
5603                           Constant::getNullValue(B->getType()));
5604     }
5605     
5606     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5607     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5608         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5609         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5610       Value *X = 0, *Y = 0, *Z = 0;
5611       
5612       if (A == C) {
5613         X = B; Y = D; Z = A;
5614       } else if (A == D) {
5615         X = B; Y = C; Z = A;
5616       } else if (B == C) {
5617         X = A; Y = D; Z = B;
5618       } else if (B == D) {
5619         X = A; Y = C; Z = B;
5620       }
5621       
5622       if (X) {   // Build (X^Y) & Z
5623         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5624         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5625         I.setOperand(0, Op1);
5626         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5627         return &I;
5628       }
5629     }
5630   }
5631   return Changed ? &I : 0;
5632 }
5633
5634
5635 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5636 /// and CmpRHS are both known to be integer constants.
5637 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5638                                           ConstantInt *DivRHS) {
5639   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5640   const APInt &CmpRHSV = CmpRHS->getValue();
5641   
5642   // FIXME: If the operand types don't match the type of the divide 
5643   // then don't attempt this transform. The code below doesn't have the
5644   // logic to deal with a signed divide and an unsigned compare (and
5645   // vice versa). This is because (x /s C1) <s C2  produces different 
5646   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5647   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5648   // work. :(  The if statement below tests that condition and bails 
5649   // if it finds it. 
5650   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5651   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5652     return 0;
5653   if (DivRHS->isZero())
5654     return 0; // The ProdOV computation fails on divide by zero.
5655
5656   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5657   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5658   // C2 (CI). By solving for X we can turn this into a range check 
5659   // instead of computing a divide. 
5660   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5661
5662   // Determine if the product overflows by seeing if the product is
5663   // not equal to the divide. Make sure we do the same kind of divide
5664   // as in the LHS instruction that we're folding. 
5665   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5666                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5667
5668   // Get the ICmp opcode
5669   ICmpInst::Predicate Pred = ICI.getPredicate();
5670
5671   // Figure out the interval that is being checked.  For example, a comparison
5672   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5673   // Compute this interval based on the constants involved and the signedness of
5674   // the compare/divide.  This computes a half-open interval, keeping track of
5675   // whether either value in the interval overflows.  After analysis each
5676   // overflow variable is set to 0 if it's corresponding bound variable is valid
5677   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5678   int LoOverflow = 0, HiOverflow = 0;
5679   ConstantInt *LoBound = 0, *HiBound = 0;
5680   
5681   
5682   if (!DivIsSigned) {  // udiv
5683     // e.g. X/5 op 3  --> [15, 20)
5684     LoBound = Prod;
5685     HiOverflow = LoOverflow = ProdOV;
5686     if (!HiOverflow)
5687       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5688   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5689     if (CmpRHSV == 0) {       // (X / pos) op 0
5690       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5691       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5692       HiBound = DivRHS;
5693     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5694       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5695       HiOverflow = LoOverflow = ProdOV;
5696       if (!HiOverflow)
5697         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5698     } else {                       // (X / pos) op neg
5699       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5700       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5701       LoOverflow = AddWithOverflow(LoBound, Prod,
5702                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5703       HiBound = AddOne(Prod);
5704       HiOverflow = ProdOV ? -1 : 0;
5705     }
5706   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5707     if (CmpRHSV == 0) {       // (X / neg) op 0
5708       // e.g. X/-5 op 0  --> [-4, 5)
5709       LoBound = AddOne(DivRHS);
5710       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5711       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5712         HiOverflow = 1;            // [INTMIN+1, overflow)
5713         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5714       }
5715     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5716       // e.g. X/-5 op 3  --> [-19, -14)
5717       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5718       if (!LoOverflow)
5719         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5720       HiBound = AddOne(Prod);
5721     } else {                       // (X / neg) op neg
5722       // e.g. X/-5 op -3  --> [15, 20)
5723       LoBound = Prod;
5724       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5725       HiBound = Subtract(Prod, DivRHS);
5726     }
5727     
5728     // Dividing by a negative swaps the condition.  LT <-> GT
5729     Pred = ICmpInst::getSwappedPredicate(Pred);
5730   }
5731
5732   Value *X = DivI->getOperand(0);
5733   switch (Pred) {
5734   default: assert(0 && "Unhandled icmp opcode!");
5735   case ICmpInst::ICMP_EQ:
5736     if (LoOverflow && HiOverflow)
5737       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5738     else if (HiOverflow)
5739       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5740                           ICmpInst::ICMP_UGE, X, LoBound);
5741     else if (LoOverflow)
5742       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5743                           ICmpInst::ICMP_ULT, X, HiBound);
5744     else
5745       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5746   case ICmpInst::ICMP_NE:
5747     if (LoOverflow && HiOverflow)
5748       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5749     else if (HiOverflow)
5750       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5751                           ICmpInst::ICMP_ULT, X, LoBound);
5752     else if (LoOverflow)
5753       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5754                           ICmpInst::ICMP_UGE, X, HiBound);
5755     else
5756       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5757   case ICmpInst::ICMP_ULT:
5758   case ICmpInst::ICMP_SLT:
5759     if (LoOverflow == +1)   // Low bound is greater than input range.
5760       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5761     if (LoOverflow == -1)   // Low bound is less than input range.
5762       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5763     return new ICmpInst(Pred, X, LoBound);
5764   case ICmpInst::ICMP_UGT:
5765   case ICmpInst::ICMP_SGT:
5766     if (HiOverflow == +1)       // High bound greater than input range.
5767       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5768     else if (HiOverflow == -1)  // High bound less than input range.
5769       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5770     if (Pred == ICmpInst::ICMP_UGT)
5771       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5772     else
5773       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5774   }
5775 }
5776
5777
5778 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5779 ///
5780 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5781                                                           Instruction *LHSI,
5782                                                           ConstantInt *RHS) {
5783   const APInt &RHSV = RHS->getValue();
5784   
5785   switch (LHSI->getOpcode()) {
5786   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5787     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5788       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5789       // fold the xor.
5790       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5791           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5792         Value *CompareVal = LHSI->getOperand(0);
5793         
5794         // If the sign bit of the XorCST is not set, there is no change to
5795         // the operation, just stop using the Xor.
5796         if (!XorCST->getValue().isNegative()) {
5797           ICI.setOperand(0, CompareVal);
5798           AddToWorkList(LHSI);
5799           return &ICI;
5800         }
5801         
5802         // Was the old condition true if the operand is positive?
5803         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5804         
5805         // If so, the new one isn't.
5806         isTrueIfPositive ^= true;
5807         
5808         if (isTrueIfPositive)
5809           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5810         else
5811           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5812       }
5813     }
5814     break;
5815   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5816     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5817         LHSI->getOperand(0)->hasOneUse()) {
5818       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5819       
5820       // If the LHS is an AND of a truncating cast, we can widen the
5821       // and/compare to be the input width without changing the value
5822       // produced, eliminating a cast.
5823       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5824         // We can do this transformation if either the AND constant does not
5825         // have its sign bit set or if it is an equality comparison. 
5826         // Extending a relational comparison when we're checking the sign
5827         // bit would not work.
5828         if (Cast->hasOneUse() &&
5829             (ICI.isEquality() ||
5830              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5831           uint32_t BitWidth = 
5832             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5833           APInt NewCST = AndCST->getValue();
5834           NewCST.zext(BitWidth);
5835           APInt NewCI = RHSV;
5836           NewCI.zext(BitWidth);
5837           Instruction *NewAnd = 
5838             BinaryOperator::CreateAnd(Cast->getOperand(0),
5839                                       ConstantInt::get(NewCST),LHSI->getName());
5840           InsertNewInstBefore(NewAnd, ICI);
5841           return new ICmpInst(ICI.getPredicate(), NewAnd,
5842                               ConstantInt::get(NewCI));
5843         }
5844       }
5845       
5846       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5847       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5848       // happens a LOT in code produced by the C front-end, for bitfield
5849       // access.
5850       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5851       if (Shift && !Shift->isShift())
5852         Shift = 0;
5853       
5854       ConstantInt *ShAmt;
5855       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5856       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5857       const Type *AndTy = AndCST->getType();          // Type of the and.
5858       
5859       // We can fold this as long as we can't shift unknown bits
5860       // into the mask.  This can only happen with signed shift
5861       // rights, as they sign-extend.
5862       if (ShAmt) {
5863         bool CanFold = Shift->isLogicalShift();
5864         if (!CanFold) {
5865           // To test for the bad case of the signed shr, see if any
5866           // of the bits shifted in could be tested after the mask.
5867           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5868           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5869           
5870           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5871           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5872                AndCST->getValue()) == 0)
5873             CanFold = true;
5874         }
5875         
5876         if (CanFold) {
5877           Constant *NewCst;
5878           if (Shift->getOpcode() == Instruction::Shl)
5879             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5880           else
5881             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5882           
5883           // Check to see if we are shifting out any of the bits being
5884           // compared.
5885           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5886             // If we shifted bits out, the fold is not going to work out.
5887             // As a special case, check to see if this means that the
5888             // result is always true or false now.
5889             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5890               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5891             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5892               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5893           } else {
5894             ICI.setOperand(1, NewCst);
5895             Constant *NewAndCST;
5896             if (Shift->getOpcode() == Instruction::Shl)
5897               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5898             else
5899               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5900             LHSI->setOperand(1, NewAndCST);
5901             LHSI->setOperand(0, Shift->getOperand(0));
5902             AddToWorkList(Shift); // Shift is dead.
5903             AddUsesToWorkList(ICI);
5904             return &ICI;
5905           }
5906         }
5907       }
5908       
5909       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5910       // preferable because it allows the C<<Y expression to be hoisted out
5911       // of a loop if Y is invariant and X is not.
5912       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5913           ICI.isEquality() && !Shift->isArithmeticShift() &&
5914           isa<Instruction>(Shift->getOperand(0))) {
5915         // Compute C << Y.
5916         Value *NS;
5917         if (Shift->getOpcode() == Instruction::LShr) {
5918           NS = BinaryOperator::CreateShl(AndCST, 
5919                                          Shift->getOperand(1), "tmp");
5920         } else {
5921           // Insert a logical shift.
5922           NS = BinaryOperator::CreateLShr(AndCST,
5923                                           Shift->getOperand(1), "tmp");
5924         }
5925         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5926         
5927         // Compute X & (C << Y).
5928         Instruction *NewAnd = 
5929           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5930         InsertNewInstBefore(NewAnd, ICI);
5931         
5932         ICI.setOperand(0, NewAnd);
5933         return &ICI;
5934       }
5935     }
5936     break;
5937     
5938   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5939     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5940     if (!ShAmt) break;
5941     
5942     uint32_t TypeBits = RHSV.getBitWidth();
5943     
5944     // Check that the shift amount is in range.  If not, don't perform
5945     // undefined shifts.  When the shift is visited it will be
5946     // simplified.
5947     if (ShAmt->uge(TypeBits))
5948       break;
5949     
5950     if (ICI.isEquality()) {
5951       // If we are comparing against bits always shifted out, the
5952       // comparison cannot succeed.
5953       Constant *Comp =
5954         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5955       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5956         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5957         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5958         return ReplaceInstUsesWith(ICI, Cst);
5959       }
5960       
5961       if (LHSI->hasOneUse()) {
5962         // Otherwise strength reduce the shift into an and.
5963         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5964         Constant *Mask =
5965           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5966         
5967         Instruction *AndI =
5968           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5969                                     Mask, LHSI->getName()+".mask");
5970         Value *And = InsertNewInstBefore(AndI, ICI);
5971         return new ICmpInst(ICI.getPredicate(), And,
5972                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5973       }
5974     }
5975     
5976     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5977     bool TrueIfSigned = false;
5978     if (LHSI->hasOneUse() &&
5979         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5980       // (X << 31) <s 0  --> (X&1) != 0
5981       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5982                                            (TypeBits-ShAmt->getZExtValue()-1));
5983       Instruction *AndI =
5984         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5985                                   Mask, LHSI->getName()+".mask");
5986       Value *And = InsertNewInstBefore(AndI, ICI);
5987       
5988       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5989                           And, Constant::getNullValue(And->getType()));
5990     }
5991     break;
5992   }
5993     
5994   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5995   case Instruction::AShr: {
5996     // Only handle equality comparisons of shift-by-constant.
5997     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5998     if (!ShAmt || !ICI.isEquality()) break;
5999
6000     // Check that the shift amount is in range.  If not, don't perform
6001     // undefined shifts.  When the shift is visited it will be
6002     // simplified.
6003     uint32_t TypeBits = RHSV.getBitWidth();
6004     if (ShAmt->uge(TypeBits))
6005       break;
6006     
6007     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6008       
6009     // If we are comparing against bits always shifted out, the
6010     // comparison cannot succeed.
6011     APInt Comp = RHSV << ShAmtVal;
6012     if (LHSI->getOpcode() == Instruction::LShr)
6013       Comp = Comp.lshr(ShAmtVal);
6014     else
6015       Comp = Comp.ashr(ShAmtVal);
6016     
6017     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6018       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6019       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6020       return ReplaceInstUsesWith(ICI, Cst);
6021     }
6022     
6023     // Otherwise, check to see if the bits shifted out are known to be zero.
6024     // If so, we can compare against the unshifted value:
6025     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6026     if (LHSI->hasOneUse() &&
6027         MaskedValueIsZero(LHSI->getOperand(0), 
6028                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6029       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6030                           ConstantExpr::getShl(RHS, ShAmt));
6031     }
6032       
6033     if (LHSI->hasOneUse()) {
6034       // Otherwise strength reduce the shift into an and.
6035       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6036       Constant *Mask = ConstantInt::get(Val);
6037       
6038       Instruction *AndI =
6039         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6040                                   Mask, LHSI->getName()+".mask");
6041       Value *And = InsertNewInstBefore(AndI, ICI);
6042       return new ICmpInst(ICI.getPredicate(), And,
6043                           ConstantExpr::getShl(RHS, ShAmt));
6044     }
6045     break;
6046   }
6047     
6048   case Instruction::SDiv:
6049   case Instruction::UDiv:
6050     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6051     // Fold this div into the comparison, producing a range check. 
6052     // Determine, based on the divide type, what the range is being 
6053     // checked.  If there is an overflow on the low or high side, remember 
6054     // it, otherwise compute the range [low, hi) bounding the new value.
6055     // See: InsertRangeTest above for the kinds of replacements possible.
6056     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6057       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6058                                           DivRHS))
6059         return R;
6060     break;
6061
6062   case Instruction::Add:
6063     // Fold: icmp pred (add, X, C1), C2
6064
6065     if (!ICI.isEquality()) {
6066       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6067       if (!LHSC) break;
6068       const APInt &LHSV = LHSC->getValue();
6069
6070       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6071                             .subtract(LHSV);
6072
6073       if (ICI.isSignedPredicate()) {
6074         if (CR.getLower().isSignBit()) {
6075           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6076                               ConstantInt::get(CR.getUpper()));
6077         } else if (CR.getUpper().isSignBit()) {
6078           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6079                               ConstantInt::get(CR.getLower()));
6080         }
6081       } else {
6082         if (CR.getLower().isMinValue()) {
6083           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6084                               ConstantInt::get(CR.getUpper()));
6085         } else if (CR.getUpper().isMinValue()) {
6086           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6087                               ConstantInt::get(CR.getLower()));
6088         }
6089       }
6090     }
6091     break;
6092   }
6093   
6094   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6095   if (ICI.isEquality()) {
6096     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6097     
6098     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6099     // the second operand is a constant, simplify a bit.
6100     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6101       switch (BO->getOpcode()) {
6102       case Instruction::SRem:
6103         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6104         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6105           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6106           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6107             Instruction *NewRem =
6108               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6109                                          BO->getName());
6110             InsertNewInstBefore(NewRem, ICI);
6111             return new ICmpInst(ICI.getPredicate(), NewRem, 
6112                                 Constant::getNullValue(BO->getType()));
6113           }
6114         }
6115         break;
6116       case Instruction::Add:
6117         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6118         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6119           if (BO->hasOneUse())
6120             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6121                                 Subtract(RHS, BOp1C));
6122         } else if (RHSV == 0) {
6123           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6124           // efficiently invertible, or if the add has just this one use.
6125           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6126           
6127           if (Value *NegVal = dyn_castNegVal(BOp1))
6128             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6129           else if (Value *NegVal = dyn_castNegVal(BOp0))
6130             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6131           else if (BO->hasOneUse()) {
6132             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6133             InsertNewInstBefore(Neg, ICI);
6134             Neg->takeName(BO);
6135             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6136           }
6137         }
6138         break;
6139       case Instruction::Xor:
6140         // For the xor case, we can xor two constants together, eliminating
6141         // the explicit xor.
6142         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6143           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6144                               ConstantExpr::getXor(RHS, BOC));
6145         
6146         // FALLTHROUGH
6147       case Instruction::Sub:
6148         // Replace (([sub|xor] A, B) != 0) with (A != B)
6149         if (RHSV == 0)
6150           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6151                               BO->getOperand(1));
6152         break;
6153         
6154       case Instruction::Or:
6155         // If bits are being or'd in that are not present in the constant we
6156         // are comparing against, then the comparison could never succeed!
6157         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6158           Constant *NotCI = ConstantExpr::getNot(RHS);
6159           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6160             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6161                                                              isICMP_NE));
6162         }
6163         break;
6164         
6165       case Instruction::And:
6166         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6167           // If bits are being compared against that are and'd out, then the
6168           // comparison can never succeed!
6169           if ((RHSV & ~BOC->getValue()) != 0)
6170             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6171                                                              isICMP_NE));
6172           
6173           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6174           if (RHS == BOC && RHSV.isPowerOf2())
6175             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6176                                 ICmpInst::ICMP_NE, LHSI,
6177                                 Constant::getNullValue(RHS->getType()));
6178           
6179           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6180           if (BOC->getValue().isSignBit()) {
6181             Value *X = BO->getOperand(0);
6182             Constant *Zero = Constant::getNullValue(X->getType());
6183             ICmpInst::Predicate pred = isICMP_NE ? 
6184               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6185             return new ICmpInst(pred, X, Zero);
6186           }
6187           
6188           // ((X & ~7) == 0) --> X < 8
6189           if (RHSV == 0 && isHighOnes(BOC)) {
6190             Value *X = BO->getOperand(0);
6191             Constant *NegX = ConstantExpr::getNeg(BOC);
6192             ICmpInst::Predicate pred = isICMP_NE ? 
6193               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6194             return new ICmpInst(pred, X, NegX);
6195           }
6196         }
6197       default: break;
6198       }
6199     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6200       // Handle icmp {eq|ne} <intrinsic>, intcst.
6201       if (II->getIntrinsicID() == Intrinsic::bswap) {
6202         AddToWorkList(II);
6203         ICI.setOperand(0, II->getOperand(1));
6204         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6205         return &ICI;
6206       }
6207     }
6208   } else {  // Not a ICMP_EQ/ICMP_NE
6209             // If the LHS is a cast from an integral value of the same size, 
6210             // then since we know the RHS is a constant, try to simlify.
6211     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6212       Value *CastOp = Cast->getOperand(0);
6213       const Type *SrcTy = CastOp->getType();
6214       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6215       if (SrcTy->isInteger() && 
6216           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6217         // If this is an unsigned comparison, try to make the comparison use
6218         // smaller constant values.
6219         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6220           // X u< 128 => X s> -1
6221           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6222                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6223         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6224                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6225           // X u> 127 => X s< 0
6226           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6227                               Constant::getNullValue(SrcTy));
6228         }
6229       }
6230     }
6231   }
6232   return 0;
6233 }
6234
6235 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6236 /// We only handle extending casts so far.
6237 ///
6238 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6239   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6240   Value *LHSCIOp        = LHSCI->getOperand(0);
6241   const Type *SrcTy     = LHSCIOp->getType();
6242   const Type *DestTy    = LHSCI->getType();
6243   Value *RHSCIOp;
6244
6245   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6246   // integer type is the same size as the pointer type.
6247   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6248       getTargetData().getPointerSizeInBits() == 
6249          cast<IntegerType>(DestTy)->getBitWidth()) {
6250     Value *RHSOp = 0;
6251     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6252       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6253     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6254       RHSOp = RHSC->getOperand(0);
6255       // If the pointer types don't match, insert a bitcast.
6256       if (LHSCIOp->getType() != RHSOp->getType())
6257         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6258     }
6259
6260     if (RHSOp)
6261       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6262   }
6263   
6264   // The code below only handles extension cast instructions, so far.
6265   // Enforce this.
6266   if (LHSCI->getOpcode() != Instruction::ZExt &&
6267       LHSCI->getOpcode() != Instruction::SExt)
6268     return 0;
6269
6270   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6271   bool isSignedCmp = ICI.isSignedPredicate();
6272
6273   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6274     // Not an extension from the same type?
6275     RHSCIOp = CI->getOperand(0);
6276     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6277       return 0;
6278     
6279     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6280     // and the other is a zext), then we can't handle this.
6281     if (CI->getOpcode() != LHSCI->getOpcode())
6282       return 0;
6283
6284     // Deal with equality cases early.
6285     if (ICI.isEquality())
6286       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6287
6288     // A signed comparison of sign extended values simplifies into a
6289     // signed comparison.
6290     if (isSignedCmp && isSignedExt)
6291       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6292
6293     // The other three cases all fold into an unsigned comparison.
6294     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6295   }
6296
6297   // If we aren't dealing with a constant on the RHS, exit early
6298   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6299   if (!CI)
6300     return 0;
6301
6302   // Compute the constant that would happen if we truncated to SrcTy then
6303   // reextended to DestTy.
6304   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6305   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6306
6307   // If the re-extended constant didn't change...
6308   if (Res2 == CI) {
6309     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6310     // For example, we might have:
6311     //    %A = sext short %X to uint
6312     //    %B = icmp ugt uint %A, 1330
6313     // It is incorrect to transform this into 
6314     //    %B = icmp ugt short %X, 1330 
6315     // because %A may have negative value. 
6316     //
6317     // However, we allow this when the compare is EQ/NE, because they are
6318     // signless.
6319     if (isSignedExt == isSignedCmp || ICI.isEquality())
6320       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6321     return 0;
6322   }
6323
6324   // The re-extended constant changed so the constant cannot be represented 
6325   // in the shorter type. Consequently, we cannot emit a simple comparison.
6326
6327   // First, handle some easy cases. We know the result cannot be equal at this
6328   // point so handle the ICI.isEquality() cases
6329   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6330     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6331   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6332     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6333
6334   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6335   // should have been folded away previously and not enter in here.
6336   Value *Result;
6337   if (isSignedCmp) {
6338     // We're performing a signed comparison.
6339     if (cast<ConstantInt>(CI)->getValue().isNegative())
6340       Result = ConstantInt::getFalse();          // X < (small) --> false
6341     else
6342       Result = ConstantInt::getTrue();           // X < (large) --> true
6343   } else {
6344     // We're performing an unsigned comparison.
6345     if (isSignedExt) {
6346       // We're performing an unsigned comp with a sign extended value.
6347       // This is true if the input is >= 0. [aka >s -1]
6348       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6349       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6350                                    NegOne, ICI.getName()), ICI);
6351     } else {
6352       // Unsigned extend & unsigned compare -> always true.
6353       Result = ConstantInt::getTrue();
6354     }
6355   }
6356
6357   // Finally, return the value computed.
6358   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6359       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6360     return ReplaceInstUsesWith(ICI, Result);
6361
6362   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6363           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6364          "ICmp should be folded!");
6365   if (Constant *CI = dyn_cast<Constant>(Result))
6366     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6367   return BinaryOperator::CreateNot(Result);
6368 }
6369
6370 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6371   return commonShiftTransforms(I);
6372 }
6373
6374 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6375   return commonShiftTransforms(I);
6376 }
6377
6378 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6379   if (Instruction *R = commonShiftTransforms(I))
6380     return R;
6381   
6382   Value *Op0 = I.getOperand(0);
6383   
6384   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6385   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6386     if (CSI->isAllOnesValue())
6387       return ReplaceInstUsesWith(I, CSI);
6388   
6389   // See if we can turn a signed shr into an unsigned shr.
6390   if (MaskedValueIsZero(Op0, 
6391                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6392     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6393   
6394   return 0;
6395 }
6396
6397 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6398   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6399   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6400
6401   // shl X, 0 == X and shr X, 0 == X
6402   // shl 0, X == 0 and shr 0, X == 0
6403   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6404       Op0 == Constant::getNullValue(Op0->getType()))
6405     return ReplaceInstUsesWith(I, Op0);
6406   
6407   if (isa<UndefValue>(Op0)) {            
6408     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6409       return ReplaceInstUsesWith(I, Op0);
6410     else                                    // undef << X -> 0, undef >>u X -> 0
6411       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6412   }
6413   if (isa<UndefValue>(Op1)) {
6414     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6415       return ReplaceInstUsesWith(I, Op0);          
6416     else                                     // X << undef, X >>u undef -> 0
6417       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6418   }
6419
6420   // Try to fold constant and into select arguments.
6421   if (isa<Constant>(Op0))
6422     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6423       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6424         return R;
6425
6426   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6427     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6428       return Res;
6429   return 0;
6430 }
6431
6432 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6433                                                BinaryOperator &I) {
6434   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6435
6436   // See if we can simplify any instructions used by the instruction whose sole 
6437   // purpose is to compute bits we don't care about.
6438   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6439   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6440   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6441                            KnownZero, KnownOne))
6442     return &I;
6443   
6444   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6445   // of a signed value.
6446   //
6447   if (Op1->uge(TypeBits)) {
6448     if (I.getOpcode() != Instruction::AShr)
6449       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6450     else {
6451       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6452       return &I;
6453     }
6454   }
6455   
6456   // ((X*C1) << C2) == (X * (C1 << C2))
6457   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6458     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6459       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6460         return BinaryOperator::CreateMul(BO->getOperand(0),
6461                                          ConstantExpr::getShl(BOOp, Op1));
6462   
6463   // Try to fold constant and into select arguments.
6464   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6465     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6466       return R;
6467   if (isa<PHINode>(Op0))
6468     if (Instruction *NV = FoldOpIntoPhi(I))
6469       return NV;
6470   
6471   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6472   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6473     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6474     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6475     // place.  Don't try to do this transformation in this case.  Also, we
6476     // require that the input operand is a shift-by-constant so that we have
6477     // confidence that the shifts will get folded together.  We could do this
6478     // xform in more cases, but it is unlikely to be profitable.
6479     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6480         isa<ConstantInt>(TrOp->getOperand(1))) {
6481       // Okay, we'll do this xform.  Make the shift of shift.
6482       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6483       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6484                                                 I.getName());
6485       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6486
6487       // For logical shifts, the truncation has the effect of making the high
6488       // part of the register be zeros.  Emulate this by inserting an AND to
6489       // clear the top bits as needed.  This 'and' will usually be zapped by
6490       // other xforms later if dead.
6491       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6492       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6493       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6494       
6495       // The mask we constructed says what the trunc would do if occurring
6496       // between the shifts.  We want to know the effect *after* the second
6497       // shift.  We know that it is a logical shift by a constant, so adjust the
6498       // mask as appropriate.
6499       if (I.getOpcode() == Instruction::Shl)
6500         MaskV <<= Op1->getZExtValue();
6501       else {
6502         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6503         MaskV = MaskV.lshr(Op1->getZExtValue());
6504       }
6505
6506       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6507                                                    TI->getName());
6508       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6509
6510       // Return the value truncated to the interesting size.
6511       return new TruncInst(And, I.getType());
6512     }
6513   }
6514   
6515   if (Op0->hasOneUse()) {
6516     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6517       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6518       Value *V1, *V2;
6519       ConstantInt *CC;
6520       switch (Op0BO->getOpcode()) {
6521         default: break;
6522         case Instruction::Add:
6523         case Instruction::And:
6524         case Instruction::Or:
6525         case Instruction::Xor: {
6526           // These operators commute.
6527           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6528           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6529               match(Op0BO->getOperand(1),
6530                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6531             Instruction *YS = BinaryOperator::CreateShl(
6532                                             Op0BO->getOperand(0), Op1,
6533                                             Op0BO->getName());
6534             InsertNewInstBefore(YS, I); // (Y << C)
6535             Instruction *X = 
6536               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6537                                      Op0BO->getOperand(1)->getName());
6538             InsertNewInstBefore(X, I);  // (X + (Y << C))
6539             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6540             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6541                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6542           }
6543           
6544           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6545           Value *Op0BOOp1 = Op0BO->getOperand(1);
6546           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6547               match(Op0BOOp1, 
6548                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6549               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6550               V2 == Op1) {
6551             Instruction *YS = BinaryOperator::CreateShl(
6552                                                      Op0BO->getOperand(0), Op1,
6553                                                      Op0BO->getName());
6554             InsertNewInstBefore(YS, I); // (Y << C)
6555             Instruction *XM =
6556               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6557                                         V1->getName()+".mask");
6558             InsertNewInstBefore(XM, I); // X & (CC << C)
6559             
6560             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6561           }
6562         }
6563           
6564         // FALL THROUGH.
6565         case Instruction::Sub: {
6566           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6567           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6568               match(Op0BO->getOperand(0),
6569                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6570             Instruction *YS = BinaryOperator::CreateShl(
6571                                                      Op0BO->getOperand(1), Op1,
6572                                                      Op0BO->getName());
6573             InsertNewInstBefore(YS, I); // (Y << C)
6574             Instruction *X =
6575               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6576                                      Op0BO->getOperand(0)->getName());
6577             InsertNewInstBefore(X, I);  // (X + (Y << C))
6578             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6579             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6580                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6581           }
6582           
6583           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6584           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6585               match(Op0BO->getOperand(0),
6586                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6587                           m_ConstantInt(CC))) && V2 == Op1 &&
6588               cast<BinaryOperator>(Op0BO->getOperand(0))
6589                   ->getOperand(0)->hasOneUse()) {
6590             Instruction *YS = BinaryOperator::CreateShl(
6591                                                      Op0BO->getOperand(1), Op1,
6592                                                      Op0BO->getName());
6593             InsertNewInstBefore(YS, I); // (Y << C)
6594             Instruction *XM =
6595               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6596                                         V1->getName()+".mask");
6597             InsertNewInstBefore(XM, I); // X & (CC << C)
6598             
6599             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6600           }
6601           
6602           break;
6603         }
6604       }
6605       
6606       
6607       // If the operand is an bitwise operator with a constant RHS, and the
6608       // shift is the only use, we can pull it out of the shift.
6609       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6610         bool isValid = true;     // Valid only for And, Or, Xor
6611         bool highBitSet = false; // Transform if high bit of constant set?
6612         
6613         switch (Op0BO->getOpcode()) {
6614           default: isValid = false; break;   // Do not perform transform!
6615           case Instruction::Add:
6616             isValid = isLeftShift;
6617             break;
6618           case Instruction::Or:
6619           case Instruction::Xor:
6620             highBitSet = false;
6621             break;
6622           case Instruction::And:
6623             highBitSet = true;
6624             break;
6625         }
6626         
6627         // If this is a signed shift right, and the high bit is modified
6628         // by the logical operation, do not perform the transformation.
6629         // The highBitSet boolean indicates the value of the high bit of
6630         // the constant which would cause it to be modified for this
6631         // operation.
6632         //
6633         if (isValid && I.getOpcode() == Instruction::AShr)
6634           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6635         
6636         if (isValid) {
6637           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6638           
6639           Instruction *NewShift =
6640             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6641           InsertNewInstBefore(NewShift, I);
6642           NewShift->takeName(Op0BO);
6643           
6644           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6645                                         NewRHS);
6646         }
6647       }
6648     }
6649   }
6650   
6651   // Find out if this is a shift of a shift by a constant.
6652   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6653   if (ShiftOp && !ShiftOp->isShift())
6654     ShiftOp = 0;
6655   
6656   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6657     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6658     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6659     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6660     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6661     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6662     Value *X = ShiftOp->getOperand(0);
6663     
6664     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6665     if (AmtSum > TypeBits)
6666       AmtSum = TypeBits;
6667     
6668     const IntegerType *Ty = cast<IntegerType>(I.getType());
6669     
6670     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6671     if (I.getOpcode() == ShiftOp->getOpcode()) {
6672       return BinaryOperator::Create(I.getOpcode(), X,
6673                                     ConstantInt::get(Ty, AmtSum));
6674     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6675                I.getOpcode() == Instruction::AShr) {
6676       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6677       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6678     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6679                I.getOpcode() == Instruction::LShr) {
6680       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6681       Instruction *Shift =
6682         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6683       InsertNewInstBefore(Shift, I);
6684
6685       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6686       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6687     }
6688     
6689     // Okay, if we get here, one shift must be left, and the other shift must be
6690     // right.  See if the amounts are equal.
6691     if (ShiftAmt1 == ShiftAmt2) {
6692       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6693       if (I.getOpcode() == Instruction::Shl) {
6694         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6695         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6696       }
6697       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6698       if (I.getOpcode() == Instruction::LShr) {
6699         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6700         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6701       }
6702       // We can simplify ((X << C) >>s C) into a trunc + sext.
6703       // NOTE: we could do this for any C, but that would make 'unusual' integer
6704       // types.  For now, just stick to ones well-supported by the code
6705       // generators.
6706       const Type *SExtType = 0;
6707       switch (Ty->getBitWidth() - ShiftAmt1) {
6708       case 1  :
6709       case 8  :
6710       case 16 :
6711       case 32 :
6712       case 64 :
6713       case 128:
6714         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6715         break;
6716       default: break;
6717       }
6718       if (SExtType) {
6719         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6720         InsertNewInstBefore(NewTrunc, I);
6721         return new SExtInst(NewTrunc, Ty);
6722       }
6723       // Otherwise, we can't handle it yet.
6724     } else if (ShiftAmt1 < ShiftAmt2) {
6725       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6726       
6727       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6728       if (I.getOpcode() == Instruction::Shl) {
6729         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6730                ShiftOp->getOpcode() == Instruction::AShr);
6731         Instruction *Shift =
6732           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6733         InsertNewInstBefore(Shift, I);
6734         
6735         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6736         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6737       }
6738       
6739       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6740       if (I.getOpcode() == Instruction::LShr) {
6741         assert(ShiftOp->getOpcode() == Instruction::Shl);
6742         Instruction *Shift =
6743           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6744         InsertNewInstBefore(Shift, I);
6745         
6746         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6747         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6748       }
6749       
6750       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6751     } else {
6752       assert(ShiftAmt2 < ShiftAmt1);
6753       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6754
6755       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6756       if (I.getOpcode() == Instruction::Shl) {
6757         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6758                ShiftOp->getOpcode() == Instruction::AShr);
6759         Instruction *Shift =
6760           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6761                                  ConstantInt::get(Ty, ShiftDiff));
6762         InsertNewInstBefore(Shift, I);
6763         
6764         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6765         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6766       }
6767       
6768       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6769       if (I.getOpcode() == Instruction::LShr) {
6770         assert(ShiftOp->getOpcode() == Instruction::Shl);
6771         Instruction *Shift =
6772           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6773         InsertNewInstBefore(Shift, I);
6774         
6775         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6776         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6777       }
6778       
6779       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6780     }
6781   }
6782   return 0;
6783 }
6784
6785
6786 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6787 /// expression.  If so, decompose it, returning some value X, such that Val is
6788 /// X*Scale+Offset.
6789 ///
6790 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6791                                         int &Offset) {
6792   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6793   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6794     Offset = CI->getZExtValue();
6795     Scale  = 0;
6796     return ConstantInt::get(Type::Int32Ty, 0);
6797   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6798     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6799       if (I->getOpcode() == Instruction::Shl) {
6800         // This is a value scaled by '1 << the shift amt'.
6801         Scale = 1U << RHS->getZExtValue();
6802         Offset = 0;
6803         return I->getOperand(0);
6804       } else if (I->getOpcode() == Instruction::Mul) {
6805         // This value is scaled by 'RHS'.
6806         Scale = RHS->getZExtValue();
6807         Offset = 0;
6808         return I->getOperand(0);
6809       } else if (I->getOpcode() == Instruction::Add) {
6810         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6811         // where C1 is divisible by C2.
6812         unsigned SubScale;
6813         Value *SubVal = 
6814           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6815         Offset += RHS->getZExtValue();
6816         Scale = SubScale;
6817         return SubVal;
6818       }
6819     }
6820   }
6821
6822   // Otherwise, we can't look past this.
6823   Scale = 1;
6824   Offset = 0;
6825   return Val;
6826 }
6827
6828
6829 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6830 /// try to eliminate the cast by moving the type information into the alloc.
6831 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6832                                                    AllocationInst &AI) {
6833   const PointerType *PTy = cast<PointerType>(CI.getType());
6834   
6835   // Remove any uses of AI that are dead.
6836   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6837   
6838   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6839     Instruction *User = cast<Instruction>(*UI++);
6840     if (isInstructionTriviallyDead(User)) {
6841       while (UI != E && *UI == User)
6842         ++UI; // If this instruction uses AI more than once, don't break UI.
6843       
6844       ++NumDeadInst;
6845       DOUT << "IC: DCE: " << *User;
6846       EraseInstFromFunction(*User);
6847     }
6848   }
6849   
6850   // Get the type really allocated and the type casted to.
6851   const Type *AllocElTy = AI.getAllocatedType();
6852   const Type *CastElTy = PTy->getElementType();
6853   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6854
6855   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6856   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6857   if (CastElTyAlign < AllocElTyAlign) return 0;
6858
6859   // If the allocation has multiple uses, only promote it if we are strictly
6860   // increasing the alignment of the resultant allocation.  If we keep it the
6861   // same, we open the door to infinite loops of various kinds.
6862   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6863
6864   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6865   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6866   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6867
6868   // See if we can satisfy the modulus by pulling a scale out of the array
6869   // size argument.
6870   unsigned ArraySizeScale;
6871   int ArrayOffset;
6872   Value *NumElements = // See if the array size is a decomposable linear expr.
6873     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6874  
6875   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6876   // do the xform.
6877   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6878       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6879
6880   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6881   Value *Amt = 0;
6882   if (Scale == 1) {
6883     Amt = NumElements;
6884   } else {
6885     // If the allocation size is constant, form a constant mul expression
6886     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6887     if (isa<ConstantInt>(NumElements))
6888       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6889     // otherwise multiply the amount and the number of elements
6890     else if (Scale != 1) {
6891       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6892       Amt = InsertNewInstBefore(Tmp, AI);
6893     }
6894   }
6895   
6896   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6897     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6898     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6899     Amt = InsertNewInstBefore(Tmp, AI);
6900   }
6901   
6902   AllocationInst *New;
6903   if (isa<MallocInst>(AI))
6904     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6905   else
6906     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6907   InsertNewInstBefore(New, AI);
6908   New->takeName(&AI);
6909   
6910   // If the allocation has multiple uses, insert a cast and change all things
6911   // that used it to use the new cast.  This will also hack on CI, but it will
6912   // die soon.
6913   if (!AI.hasOneUse()) {
6914     AddUsesToWorkList(AI);
6915     // New is the allocation instruction, pointer typed. AI is the original
6916     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6917     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6918     InsertNewInstBefore(NewCast, AI);
6919     AI.replaceAllUsesWith(NewCast);
6920   }
6921   return ReplaceInstUsesWith(CI, New);
6922 }
6923
6924 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6925 /// and return it as type Ty without inserting any new casts and without
6926 /// changing the computed value.  This is used by code that tries to decide
6927 /// whether promoting or shrinking integer operations to wider or smaller types
6928 /// will allow us to eliminate a truncate or extend.
6929 ///
6930 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6931 /// extension operation if Ty is larger.
6932 ///
6933 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6934 /// should return true if trunc(V) can be computed by computing V in the smaller
6935 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6936 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6937 /// efficiently truncated.
6938 ///
6939 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6940 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6941 /// the final result.
6942 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6943                                               unsigned CastOpc,
6944                                               int &NumCastsRemoved) {
6945   // We can always evaluate constants in another type.
6946   if (isa<ConstantInt>(V))
6947     return true;
6948   
6949   Instruction *I = dyn_cast<Instruction>(V);
6950   if (!I) return false;
6951   
6952   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6953   
6954   // If this is an extension or truncate, we can often eliminate it.
6955   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6956     // If this is a cast from the destination type, we can trivially eliminate
6957     // it, and this will remove a cast overall.
6958     if (I->getOperand(0)->getType() == Ty) {
6959       // If the first operand is itself a cast, and is eliminable, do not count
6960       // this as an eliminable cast.  We would prefer to eliminate those two
6961       // casts first.
6962       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6963         ++NumCastsRemoved;
6964       return true;
6965     }
6966   }
6967
6968   // We can't extend or shrink something that has multiple uses: doing so would
6969   // require duplicating the instruction in general, which isn't profitable.
6970   if (!I->hasOneUse()) return false;
6971
6972   switch (I->getOpcode()) {
6973   case Instruction::Add:
6974   case Instruction::Sub:
6975   case Instruction::Mul:
6976   case Instruction::And:
6977   case Instruction::Or:
6978   case Instruction::Xor:
6979     // These operators can all arbitrarily be extended or truncated.
6980     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6981                                       NumCastsRemoved) &&
6982            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6983                                       NumCastsRemoved);
6984
6985   case Instruction::Shl:
6986     // If we are truncating the result of this SHL, and if it's a shift of a
6987     // constant amount, we can always perform a SHL in a smaller type.
6988     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6989       uint32_t BitWidth = Ty->getBitWidth();
6990       if (BitWidth < OrigTy->getBitWidth() && 
6991           CI->getLimitedValue(BitWidth) < BitWidth)
6992         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6993                                           NumCastsRemoved);
6994     }
6995     break;
6996   case Instruction::LShr:
6997     // If this is a truncate of a logical shr, we can truncate it to a smaller
6998     // lshr iff we know that the bits we would otherwise be shifting in are
6999     // already zeros.
7000     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7001       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7002       uint32_t BitWidth = Ty->getBitWidth();
7003       if (BitWidth < OrigBitWidth &&
7004           MaskedValueIsZero(I->getOperand(0),
7005             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7006           CI->getLimitedValue(BitWidth) < BitWidth) {
7007         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7008                                           NumCastsRemoved);
7009       }
7010     }
7011     break;
7012   case Instruction::ZExt:
7013   case Instruction::SExt:
7014   case Instruction::Trunc:
7015     // If this is the same kind of case as our original (e.g. zext+zext), we
7016     // can safely replace it.  Note that replacing it does not reduce the number
7017     // of casts in the input.
7018     if (I->getOpcode() == CastOpc)
7019       return true;
7020     break;
7021   case Instruction::Select: {
7022     SelectInst *SI = cast<SelectInst>(I);
7023     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7024                                       NumCastsRemoved) &&
7025            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7026                                       NumCastsRemoved);
7027   }
7028   case Instruction::PHI: {
7029     // We can change a phi if we can change all operands.
7030     PHINode *PN = cast<PHINode>(I);
7031     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7032       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7033                                       NumCastsRemoved))
7034         return false;
7035     return true;
7036   }
7037   default:
7038     // TODO: Can handle more cases here.
7039     break;
7040   }
7041   
7042   return false;
7043 }
7044
7045 /// EvaluateInDifferentType - Given an expression that 
7046 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7047 /// evaluate the expression.
7048 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7049                                              bool isSigned) {
7050   if (Constant *C = dyn_cast<Constant>(V))
7051     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7052
7053   // Otherwise, it must be an instruction.
7054   Instruction *I = cast<Instruction>(V);
7055   Instruction *Res = 0;
7056   switch (I->getOpcode()) {
7057   case Instruction::Add:
7058   case Instruction::Sub:
7059   case Instruction::Mul:
7060   case Instruction::And:
7061   case Instruction::Or:
7062   case Instruction::Xor:
7063   case Instruction::AShr:
7064   case Instruction::LShr:
7065   case Instruction::Shl: {
7066     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7067     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7068     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7069                                  LHS, RHS);
7070     break;
7071   }    
7072   case Instruction::Trunc:
7073   case Instruction::ZExt:
7074   case Instruction::SExt:
7075     // If the source type of the cast is the type we're trying for then we can
7076     // just return the source.  There's no need to insert it because it is not
7077     // new.
7078     if (I->getOperand(0)->getType() == Ty)
7079       return I->getOperand(0);
7080     
7081     // Otherwise, must be the same type of cast, so just reinsert a new one.
7082     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7083                            Ty);
7084     break;
7085   case Instruction::Select: {
7086     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7087     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7088     Res = SelectInst::Create(I->getOperand(0), True, False);
7089     break;
7090   }
7091   case Instruction::PHI: {
7092     PHINode *OPN = cast<PHINode>(I);
7093     PHINode *NPN = PHINode::Create(Ty);
7094     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7095       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7096       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7097     }
7098     Res = NPN;
7099     break;
7100   }
7101   default: 
7102     // TODO: Can handle more cases here.
7103     assert(0 && "Unreachable!");
7104     break;
7105   }
7106   
7107   Res->takeName(I);
7108   return InsertNewInstBefore(Res, *I);
7109 }
7110
7111 /// @brief Implement the transforms common to all CastInst visitors.
7112 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7113   Value *Src = CI.getOperand(0);
7114
7115   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7116   // eliminate it now.
7117   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7118     if (Instruction::CastOps opc = 
7119         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7120       // The first cast (CSrc) is eliminable so we need to fix up or replace
7121       // the second cast (CI). CSrc will then have a good chance of being dead.
7122       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7123     }
7124   }
7125
7126   // If we are casting a select then fold the cast into the select
7127   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7128     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7129       return NV;
7130
7131   // If we are casting a PHI then fold the cast into the PHI
7132   if (isa<PHINode>(Src))
7133     if (Instruction *NV = FoldOpIntoPhi(CI))
7134       return NV;
7135   
7136   return 0;
7137 }
7138
7139 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7140 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7141   Value *Src = CI.getOperand(0);
7142   
7143   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7144     // If casting the result of a getelementptr instruction with no offset, turn
7145     // this into a cast of the original pointer!
7146     if (GEP->hasAllZeroIndices()) {
7147       // Changing the cast operand is usually not a good idea but it is safe
7148       // here because the pointer operand is being replaced with another 
7149       // pointer operand so the opcode doesn't need to change.
7150       AddToWorkList(GEP);
7151       CI.setOperand(0, GEP->getOperand(0));
7152       return &CI;
7153     }
7154     
7155     // If the GEP has a single use, and the base pointer is a bitcast, and the
7156     // GEP computes a constant offset, see if we can convert these three
7157     // instructions into fewer.  This typically happens with unions and other
7158     // non-type-safe code.
7159     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7160       if (GEP->hasAllConstantIndices()) {
7161         // We are guaranteed to get a constant from EmitGEPOffset.
7162         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7163         int64_t Offset = OffsetV->getSExtValue();
7164         
7165         // Get the base pointer input of the bitcast, and the type it points to.
7166         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7167         const Type *GEPIdxTy =
7168           cast<PointerType>(OrigBase->getType())->getElementType();
7169         if (GEPIdxTy->isSized()) {
7170           SmallVector<Value*, 8> NewIndices;
7171           
7172           // Start with the index over the outer type.  Note that the type size
7173           // might be zero (even if the offset isn't zero) if the indexed type
7174           // is something like [0 x {int, int}]
7175           const Type *IntPtrTy = TD->getIntPtrType();
7176           int64_t FirstIdx = 0;
7177           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7178             FirstIdx = Offset/TySize;
7179             Offset %= TySize;
7180           
7181             // Handle silly modulus not returning values values [0..TySize).
7182             if (Offset < 0) {
7183               --FirstIdx;
7184               Offset += TySize;
7185               assert(Offset >= 0);
7186             }
7187             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7188           }
7189           
7190           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7191
7192           // Index into the types.  If we fail, set OrigBase to null.
7193           while (Offset) {
7194             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7195               const StructLayout *SL = TD->getStructLayout(STy);
7196               if (Offset < (int64_t)SL->getSizeInBytes()) {
7197                 unsigned Elt = SL->getElementContainingOffset(Offset);
7198                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7199               
7200                 Offset -= SL->getElementOffset(Elt);
7201                 GEPIdxTy = STy->getElementType(Elt);
7202               } else {
7203                 // Otherwise, we can't index into this, bail out.
7204                 Offset = 0;
7205                 OrigBase = 0;
7206               }
7207             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7208               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7209               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7210                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7211                 Offset %= EltSize;
7212               } else {
7213                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7214               }
7215               GEPIdxTy = STy->getElementType();
7216             } else {
7217               // Otherwise, we can't index into this, bail out.
7218               Offset = 0;
7219               OrigBase = 0;
7220             }
7221           }
7222           if (OrigBase) {
7223             // If we were able to index down into an element, create the GEP
7224             // and bitcast the result.  This eliminates one bitcast, potentially
7225             // two.
7226             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7227                                                           NewIndices.begin(),
7228                                                           NewIndices.end(), "");
7229             InsertNewInstBefore(NGEP, CI);
7230             NGEP->takeName(GEP);
7231             
7232             if (isa<BitCastInst>(CI))
7233               return new BitCastInst(NGEP, CI.getType());
7234             assert(isa<PtrToIntInst>(CI));
7235             return new PtrToIntInst(NGEP, CI.getType());
7236           }
7237         }
7238       }      
7239     }
7240   }
7241     
7242   return commonCastTransforms(CI);
7243 }
7244
7245
7246
7247 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7248 /// integer types. This function implements the common transforms for all those
7249 /// cases.
7250 /// @brief Implement the transforms common to CastInst with integer operands
7251 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7252   if (Instruction *Result = commonCastTransforms(CI))
7253     return Result;
7254
7255   Value *Src = CI.getOperand(0);
7256   const Type *SrcTy = Src->getType();
7257   const Type *DestTy = CI.getType();
7258   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7259   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7260
7261   // See if we can simplify any instructions used by the LHS whose sole 
7262   // purpose is to compute bits we don't care about.
7263   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7264   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7265                            KnownZero, KnownOne))
7266     return &CI;
7267
7268   // If the source isn't an instruction or has more than one use then we
7269   // can't do anything more. 
7270   Instruction *SrcI = dyn_cast<Instruction>(Src);
7271   if (!SrcI || !Src->hasOneUse())
7272     return 0;
7273
7274   // Attempt to propagate the cast into the instruction for int->int casts.
7275   int NumCastsRemoved = 0;
7276   if (!isa<BitCastInst>(CI) &&
7277       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7278                                  CI.getOpcode(), NumCastsRemoved)) {
7279     // If this cast is a truncate, evaluting in a different type always
7280     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7281     // we need to do an AND to maintain the clear top-part of the computation,
7282     // so we require that the input have eliminated at least one cast.  If this
7283     // is a sign extension, we insert two new casts (to do the extension) so we
7284     // require that two casts have been eliminated.
7285     bool DoXForm;
7286     switch (CI.getOpcode()) {
7287     default:
7288       // All the others use floating point so we shouldn't actually 
7289       // get here because of the check above.
7290       assert(0 && "Unknown cast type");
7291     case Instruction::Trunc:
7292       DoXForm = true;
7293       break;
7294     case Instruction::ZExt:
7295       DoXForm = NumCastsRemoved >= 1;
7296       break;
7297     case Instruction::SExt:
7298       DoXForm = NumCastsRemoved >= 2;
7299       break;
7300     }
7301     
7302     if (DoXForm) {
7303       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7304                                            CI.getOpcode() == Instruction::SExt);
7305       assert(Res->getType() == DestTy);
7306       switch (CI.getOpcode()) {
7307       default: assert(0 && "Unknown cast type!");
7308       case Instruction::Trunc:
7309       case Instruction::BitCast:
7310         // Just replace this cast with the result.
7311         return ReplaceInstUsesWith(CI, Res);
7312       case Instruction::ZExt: {
7313         // We need to emit an AND to clear the high bits.
7314         assert(SrcBitSize < DestBitSize && "Not a zext?");
7315         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7316                                                             SrcBitSize));
7317         return BinaryOperator::CreateAnd(Res, C);
7318       }
7319       case Instruction::SExt:
7320         // We need to emit a cast to truncate, then a cast to sext.
7321         return CastInst::Create(Instruction::SExt,
7322             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7323                              CI), DestTy);
7324       }
7325     }
7326   }
7327   
7328   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7329   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7330
7331   switch (SrcI->getOpcode()) {
7332   case Instruction::Add:
7333   case Instruction::Mul:
7334   case Instruction::And:
7335   case Instruction::Or:
7336   case Instruction::Xor:
7337     // If we are discarding information, rewrite.
7338     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7339       // Don't insert two casts if they cannot be eliminated.  We allow 
7340       // two casts to be inserted if the sizes are the same.  This could 
7341       // only be converting signedness, which is a noop.
7342       if (DestBitSize == SrcBitSize || 
7343           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7344           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7345         Instruction::CastOps opcode = CI.getOpcode();
7346         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7347         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7348         return BinaryOperator::Create(
7349             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7350       }
7351     }
7352
7353     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7354     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7355         SrcI->getOpcode() == Instruction::Xor &&
7356         Op1 == ConstantInt::getTrue() &&
7357         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7358       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7359       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7360     }
7361     break;
7362   case Instruction::SDiv:
7363   case Instruction::UDiv:
7364   case Instruction::SRem:
7365   case Instruction::URem:
7366     // If we are just changing the sign, rewrite.
7367     if (DestBitSize == SrcBitSize) {
7368       // Don't insert two casts if they cannot be eliminated.  We allow 
7369       // two casts to be inserted if the sizes are the same.  This could 
7370       // only be converting signedness, which is a noop.
7371       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7372           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7373         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7374                                               Op0, DestTy, SrcI);
7375         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7376                                               Op1, DestTy, SrcI);
7377         return BinaryOperator::Create(
7378           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7379       }
7380     }
7381     break;
7382
7383   case Instruction::Shl:
7384     // Allow changing the sign of the source operand.  Do not allow 
7385     // changing the size of the shift, UNLESS the shift amount is a 
7386     // constant.  We must not change variable sized shifts to a smaller 
7387     // size, because it is undefined to shift more bits out than exist 
7388     // in the value.
7389     if (DestBitSize == SrcBitSize ||
7390         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7391       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7392           Instruction::BitCast : Instruction::Trunc);
7393       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7394       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7395       return BinaryOperator::CreateShl(Op0c, Op1c);
7396     }
7397     break;
7398   case Instruction::AShr:
7399     // If this is a signed shr, and if all bits shifted in are about to be
7400     // truncated off, turn it into an unsigned shr to allow greater
7401     // simplifications.
7402     if (DestBitSize < SrcBitSize &&
7403         isa<ConstantInt>(Op1)) {
7404       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7405       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7406         // Insert the new logical shift right.
7407         return BinaryOperator::CreateLShr(Op0, Op1);
7408       }
7409     }
7410     break;
7411   }
7412   return 0;
7413 }
7414
7415 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7416   if (Instruction *Result = commonIntCastTransforms(CI))
7417     return Result;
7418   
7419   Value *Src = CI.getOperand(0);
7420   const Type *Ty = CI.getType();
7421   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7422   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7423   
7424   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7425     switch (SrcI->getOpcode()) {
7426     default: break;
7427     case Instruction::LShr:
7428       // We can shrink lshr to something smaller if we know the bits shifted in
7429       // are already zeros.
7430       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7431         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7432         
7433         // Get a mask for the bits shifting in.
7434         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7435         Value* SrcIOp0 = SrcI->getOperand(0);
7436         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7437           if (ShAmt >= DestBitWidth)        // All zeros.
7438             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7439
7440           // Okay, we can shrink this.  Truncate the input, then return a new
7441           // shift.
7442           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7443           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7444                                        Ty, CI);
7445           return BinaryOperator::CreateLShr(V1, V2);
7446         }
7447       } else {     // This is a variable shr.
7448         
7449         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7450         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7451         // loop-invariant and CSE'd.
7452         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7453           Value *One = ConstantInt::get(SrcI->getType(), 1);
7454
7455           Value *V = InsertNewInstBefore(
7456               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7457                                      "tmp"), CI);
7458           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7459                                                             SrcI->getOperand(0),
7460                                                             "tmp"), CI);
7461           Value *Zero = Constant::getNullValue(V->getType());
7462           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7463         }
7464       }
7465       break;
7466     }
7467   }
7468   
7469   return 0;
7470 }
7471
7472 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7473 /// in order to eliminate the icmp.
7474 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7475                                              bool DoXform) {
7476   // If we are just checking for a icmp eq of a single bit and zext'ing it
7477   // to an integer, then shift the bit to the appropriate place and then
7478   // cast to integer to avoid the comparison.
7479   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7480     const APInt &Op1CV = Op1C->getValue();
7481       
7482     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7483     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7484     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7485         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7486       if (!DoXform) return ICI;
7487
7488       Value *In = ICI->getOperand(0);
7489       Value *Sh = ConstantInt::get(In->getType(),
7490                                    In->getType()->getPrimitiveSizeInBits()-1);
7491       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7492                                                         In->getName()+".lobit"),
7493                                CI);
7494       if (In->getType() != CI.getType())
7495         In = CastInst::CreateIntegerCast(In, CI.getType(),
7496                                          false/*ZExt*/, "tmp", &CI);
7497
7498       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7499         Constant *One = ConstantInt::get(In->getType(), 1);
7500         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7501                                                          In->getName()+".not"),
7502                                  CI);
7503       }
7504
7505       return ReplaceInstUsesWith(CI, In);
7506     }
7507       
7508       
7509       
7510     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7511     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7512     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7513     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7514     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7515     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7516     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7517     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7518     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7519         // This only works for EQ and NE
7520         ICI->isEquality()) {
7521       // If Op1C some other power of two, convert:
7522       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7523       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7524       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7525       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7526         
7527       APInt KnownZeroMask(~KnownZero);
7528       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7529         if (!DoXform) return ICI;
7530
7531         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7532         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7533           // (X&4) == 2 --> false
7534           // (X&4) != 2 --> true
7535           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7536           Res = ConstantExpr::getZExt(Res, CI.getType());
7537           return ReplaceInstUsesWith(CI, Res);
7538         }
7539           
7540         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7541         Value *In = ICI->getOperand(0);
7542         if (ShiftAmt) {
7543           // Perform a logical shr by shiftamt.
7544           // Insert the shift to put the result in the low bit.
7545           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7546                                   ConstantInt::get(In->getType(), ShiftAmt),
7547                                                    In->getName()+".lobit"), CI);
7548         }
7549           
7550         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7551           Constant *One = ConstantInt::get(In->getType(), 1);
7552           In = BinaryOperator::CreateXor(In, One, "tmp");
7553           InsertNewInstBefore(cast<Instruction>(In), CI);
7554         }
7555           
7556         if (CI.getType() == In->getType())
7557           return ReplaceInstUsesWith(CI, In);
7558         else
7559           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7560       }
7561     }
7562   }
7563
7564   return 0;
7565 }
7566
7567 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7568   // If one of the common conversion will work ..
7569   if (Instruction *Result = commonIntCastTransforms(CI))
7570     return Result;
7571
7572   Value *Src = CI.getOperand(0);
7573
7574   // If this is a cast of a cast
7575   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7576     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7577     // types and if the sizes are just right we can convert this into a logical
7578     // 'and' which will be much cheaper than the pair of casts.
7579     if (isa<TruncInst>(CSrc)) {
7580       // Get the sizes of the types involved
7581       Value *A = CSrc->getOperand(0);
7582       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7583       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7584       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7585       // If we're actually extending zero bits and the trunc is a no-op
7586       if (MidSize < DstSize && SrcSize == DstSize) {
7587         // Replace both of the casts with an And of the type mask.
7588         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7589         Constant *AndConst = ConstantInt::get(AndValue);
7590         Instruction *And = 
7591           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7592         // Unfortunately, if the type changed, we need to cast it back.
7593         if (And->getType() != CI.getType()) {
7594           And->setName(CSrc->getName()+".mask");
7595           InsertNewInstBefore(And, CI);
7596           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7597         }
7598         return And;
7599       }
7600     }
7601   }
7602
7603   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7604     return transformZExtICmp(ICI, CI);
7605
7606   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7607   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7608     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7609     // of the (zext icmp) will be transformed.
7610     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7611     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7612     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7613         (transformZExtICmp(LHS, CI, false) ||
7614          transformZExtICmp(RHS, CI, false))) {
7615       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7616       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7617       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7618     }
7619   }
7620
7621   return 0;
7622 }
7623
7624 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7625   if (Instruction *I = commonIntCastTransforms(CI))
7626     return I;
7627   
7628   Value *Src = CI.getOperand(0);
7629   
7630   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7631   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7632   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7633     // If we are just checking for a icmp eq of a single bit and zext'ing it
7634     // to an integer, then shift the bit to the appropriate place and then
7635     // cast to integer to avoid the comparison.
7636     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7637       const APInt &Op1CV = Op1C->getValue();
7638       
7639       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7640       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7641       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7642           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7643         Value *In = ICI->getOperand(0);
7644         Value *Sh = ConstantInt::get(In->getType(),
7645                                      In->getType()->getPrimitiveSizeInBits()-1);
7646         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7647                                                         In->getName()+".lobit"),
7648                                  CI);
7649         if (In->getType() != CI.getType())
7650           In = CastInst::CreateIntegerCast(In, CI.getType(),
7651                                            true/*SExt*/, "tmp", &CI);
7652         
7653         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7654           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7655                                      In->getName()+".not"), CI);
7656         
7657         return ReplaceInstUsesWith(CI, In);
7658       }
7659     }
7660   }
7661
7662   // See if the value being truncated is already sign extended.  If so, just
7663   // eliminate the trunc/sext pair.
7664   if (getOpcode(Src) == Instruction::Trunc) {
7665     Value *Op = cast<User>(Src)->getOperand(0);
7666     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7667     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7668     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7669     unsigned NumSignBits = ComputeNumSignBits(Op);
7670
7671     if (OpBits == DestBits) {
7672       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7673       // bits, it is already ready.
7674       if (NumSignBits > DestBits-MidBits)
7675         return ReplaceInstUsesWith(CI, Op);
7676     } else if (OpBits < DestBits) {
7677       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7678       // bits, just sext from i32.
7679       if (NumSignBits > OpBits-MidBits)
7680         return new SExtInst(Op, CI.getType(), "tmp");
7681     } else {
7682       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7683       // bits, just truncate to i32.
7684       if (NumSignBits > OpBits-MidBits)
7685         return new TruncInst(Op, CI.getType(), "tmp");
7686     }
7687   }
7688       
7689   return 0;
7690 }
7691
7692 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7693 /// in the specified FP type without changing its value.
7694 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7695   APFloat F = CFP->getValueAPF();
7696   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7697     return ConstantFP::get(F);
7698   return 0;
7699 }
7700
7701 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7702 /// through it until we get the source value.
7703 static Value *LookThroughFPExtensions(Value *V) {
7704   if (Instruction *I = dyn_cast<Instruction>(V))
7705     if (I->getOpcode() == Instruction::FPExt)
7706       return LookThroughFPExtensions(I->getOperand(0));
7707   
7708   // If this value is a constant, return the constant in the smallest FP type
7709   // that can accurately represent it.  This allows us to turn
7710   // (float)((double)X+2.0) into x+2.0f.
7711   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7712     if (CFP->getType() == Type::PPC_FP128Ty)
7713       return V;  // No constant folding of this.
7714     // See if the value can be truncated to float and then reextended.
7715     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7716       return V;
7717     if (CFP->getType() == Type::DoubleTy)
7718       return V;  // Won't shrink.
7719     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7720       return V;
7721     // Don't try to shrink to various long double types.
7722   }
7723   
7724   return V;
7725 }
7726
7727 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7728   if (Instruction *I = commonCastTransforms(CI))
7729     return I;
7730   
7731   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7732   // smaller than the destination type, we can eliminate the truncate by doing
7733   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7734   // many builtins (sqrt, etc).
7735   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7736   if (OpI && OpI->hasOneUse()) {
7737     switch (OpI->getOpcode()) {
7738     default: break;
7739     case Instruction::Add:
7740     case Instruction::Sub:
7741     case Instruction::Mul:
7742     case Instruction::FDiv:
7743     case Instruction::FRem:
7744       const Type *SrcTy = OpI->getType();
7745       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7746       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7747       if (LHSTrunc->getType() != SrcTy && 
7748           RHSTrunc->getType() != SrcTy) {
7749         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7750         // If the source types were both smaller than the destination type of
7751         // the cast, do this xform.
7752         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7753             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7754           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7755                                       CI.getType(), CI);
7756           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7757                                       CI.getType(), CI);
7758           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7759         }
7760       }
7761       break;  
7762     }
7763   }
7764   return 0;
7765 }
7766
7767 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7768   return commonCastTransforms(CI);
7769 }
7770
7771 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7772   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7773   // mantissa to accurately represent all values of X.  For example, do not
7774   // do this with i64->float->i64.
7775   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7776     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7777         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7778                     SrcI->getType()->getFPMantissaWidth())
7779       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7780
7781   return commonCastTransforms(FI);
7782 }
7783
7784 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7785   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7786   // mantissa to accurately represent all values of X.  For example, do not
7787   // do this with i64->float->i64.
7788   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7789     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7790         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7791                     SrcI->getType()->getFPMantissaWidth())
7792       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7793   
7794   return commonCastTransforms(FI);
7795 }
7796
7797 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7798   return commonCastTransforms(CI);
7799 }
7800
7801 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7802   return commonCastTransforms(CI);
7803 }
7804
7805 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7806   return commonPointerCastTransforms(CI);
7807 }
7808
7809 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7810   if (Instruction *I = commonCastTransforms(CI))
7811     return I;
7812   
7813   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7814   if (!DestPointee->isSized()) return 0;
7815
7816   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7817   ConstantInt *Cst;
7818   Value *X;
7819   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7820                                     m_ConstantInt(Cst)))) {
7821     // If the source and destination operands have the same type, see if this
7822     // is a single-index GEP.
7823     if (X->getType() == CI.getType()) {
7824       // Get the size of the pointee type.
7825       uint64_t Size = TD->getABITypeSize(DestPointee);
7826
7827       // Convert the constant to intptr type.
7828       APInt Offset = Cst->getValue();
7829       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7830
7831       // If Offset is evenly divisible by Size, we can do this xform.
7832       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7833         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7834         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7835       }
7836     }
7837     // TODO: Could handle other cases, e.g. where add is indexing into field of
7838     // struct etc.
7839   } else if (CI.getOperand(0)->hasOneUse() &&
7840              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7841     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7842     // "inttoptr+GEP" instead of "add+intptr".
7843     
7844     // Get the size of the pointee type.
7845     uint64_t Size = TD->getABITypeSize(DestPointee);
7846     
7847     // Convert the constant to intptr type.
7848     APInt Offset = Cst->getValue();
7849     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7850     
7851     // If Offset is evenly divisible by Size, we can do this xform.
7852     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7853       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7854       
7855       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7856                                                             "tmp"), CI);
7857       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7858     }
7859   }
7860   return 0;
7861 }
7862
7863 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7864   // If the operands are integer typed then apply the integer transforms,
7865   // otherwise just apply the common ones.
7866   Value *Src = CI.getOperand(0);
7867   const Type *SrcTy = Src->getType();
7868   const Type *DestTy = CI.getType();
7869
7870   if (SrcTy->isInteger() && DestTy->isInteger()) {
7871     if (Instruction *Result = commonIntCastTransforms(CI))
7872       return Result;
7873   } else if (isa<PointerType>(SrcTy)) {
7874     if (Instruction *I = commonPointerCastTransforms(CI))
7875       return I;
7876   } else {
7877     if (Instruction *Result = commonCastTransforms(CI))
7878       return Result;
7879   }
7880
7881
7882   // Get rid of casts from one type to the same type. These are useless and can
7883   // be replaced by the operand.
7884   if (DestTy == Src->getType())
7885     return ReplaceInstUsesWith(CI, Src);
7886
7887   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7888     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7889     const Type *DstElTy = DstPTy->getElementType();
7890     const Type *SrcElTy = SrcPTy->getElementType();
7891     
7892     // If the address spaces don't match, don't eliminate the bitcast, which is
7893     // required for changing types.
7894     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7895       return 0;
7896     
7897     // If we are casting a malloc or alloca to a pointer to a type of the same
7898     // size, rewrite the allocation instruction to allocate the "right" type.
7899     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7900       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7901         return V;
7902     
7903     // If the source and destination are pointers, and this cast is equivalent
7904     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7905     // This can enhance SROA and other transforms that want type-safe pointers.
7906     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7907     unsigned NumZeros = 0;
7908     while (SrcElTy != DstElTy && 
7909            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7910            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7911       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7912       ++NumZeros;
7913     }
7914
7915     // If we found a path from the src to dest, create the getelementptr now.
7916     if (SrcElTy == DstElTy) {
7917       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7918       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7919                                        ((Instruction*) NULL));
7920     }
7921   }
7922
7923   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7924     if (SVI->hasOneUse()) {
7925       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7926       // a bitconvert to a vector with the same # elts.
7927       if (isa<VectorType>(DestTy) && 
7928           cast<VectorType>(DestTy)->getNumElements() == 
7929                 SVI->getType()->getNumElements()) {
7930         CastInst *Tmp;
7931         // If either of the operands is a cast from CI.getType(), then
7932         // evaluating the shuffle in the casted destination's type will allow
7933         // us to eliminate at least one cast.
7934         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7935              Tmp->getOperand(0)->getType() == DestTy) ||
7936             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7937              Tmp->getOperand(0)->getType() == DestTy)) {
7938           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7939                                                SVI->getOperand(0), DestTy, &CI);
7940           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7941                                                SVI->getOperand(1), DestTy, &CI);
7942           // Return a new shuffle vector.  Use the same element ID's, as we
7943           // know the vector types match #elts.
7944           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7945         }
7946       }
7947     }
7948   }
7949   return 0;
7950 }
7951
7952 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7953 ///   %C = or %A, %B
7954 ///   %D = select %cond, %C, %A
7955 /// into:
7956 ///   %C = select %cond, %B, 0
7957 ///   %D = or %A, %C
7958 ///
7959 /// Assuming that the specified instruction is an operand to the select, return
7960 /// a bitmask indicating which operands of this instruction are foldable if they
7961 /// equal the other incoming value of the select.
7962 ///
7963 static unsigned GetSelectFoldableOperands(Instruction *I) {
7964   switch (I->getOpcode()) {
7965   case Instruction::Add:
7966   case Instruction::Mul:
7967   case Instruction::And:
7968   case Instruction::Or:
7969   case Instruction::Xor:
7970     return 3;              // Can fold through either operand.
7971   case Instruction::Sub:   // Can only fold on the amount subtracted.
7972   case Instruction::Shl:   // Can only fold on the shift amount.
7973   case Instruction::LShr:
7974   case Instruction::AShr:
7975     return 1;
7976   default:
7977     return 0;              // Cannot fold
7978   }
7979 }
7980
7981 /// GetSelectFoldableConstant - For the same transformation as the previous
7982 /// function, return the identity constant that goes into the select.
7983 static Constant *GetSelectFoldableConstant(Instruction *I) {
7984   switch (I->getOpcode()) {
7985   default: assert(0 && "This cannot happen!"); abort();
7986   case Instruction::Add:
7987   case Instruction::Sub:
7988   case Instruction::Or:
7989   case Instruction::Xor:
7990   case Instruction::Shl:
7991   case Instruction::LShr:
7992   case Instruction::AShr:
7993     return Constant::getNullValue(I->getType());
7994   case Instruction::And:
7995     return Constant::getAllOnesValue(I->getType());
7996   case Instruction::Mul:
7997     return ConstantInt::get(I->getType(), 1);
7998   }
7999 }
8000
8001 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8002 /// have the same opcode and only one use each.  Try to simplify this.
8003 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8004                                           Instruction *FI) {
8005   if (TI->getNumOperands() == 1) {
8006     // If this is a non-volatile load or a cast from the same type,
8007     // merge.
8008     if (TI->isCast()) {
8009       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8010         return 0;
8011     } else {
8012       return 0;  // unknown unary op.
8013     }
8014
8015     // Fold this by inserting a select from the input values.
8016     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8017                                            FI->getOperand(0), SI.getName()+".v");
8018     InsertNewInstBefore(NewSI, SI);
8019     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8020                             TI->getType());
8021   }
8022
8023   // Only handle binary operators here.
8024   if (!isa<BinaryOperator>(TI))
8025     return 0;
8026
8027   // Figure out if the operations have any operands in common.
8028   Value *MatchOp, *OtherOpT, *OtherOpF;
8029   bool MatchIsOpZero;
8030   if (TI->getOperand(0) == FI->getOperand(0)) {
8031     MatchOp  = TI->getOperand(0);
8032     OtherOpT = TI->getOperand(1);
8033     OtherOpF = FI->getOperand(1);
8034     MatchIsOpZero = true;
8035   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8036     MatchOp  = TI->getOperand(1);
8037     OtherOpT = TI->getOperand(0);
8038     OtherOpF = FI->getOperand(0);
8039     MatchIsOpZero = false;
8040   } else if (!TI->isCommutative()) {
8041     return 0;
8042   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8043     MatchOp  = TI->getOperand(0);
8044     OtherOpT = TI->getOperand(1);
8045     OtherOpF = FI->getOperand(0);
8046     MatchIsOpZero = true;
8047   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8048     MatchOp  = TI->getOperand(1);
8049     OtherOpT = TI->getOperand(0);
8050     OtherOpF = FI->getOperand(1);
8051     MatchIsOpZero = true;
8052   } else {
8053     return 0;
8054   }
8055
8056   // If we reach here, they do have operations in common.
8057   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8058                                          OtherOpF, SI.getName()+".v");
8059   InsertNewInstBefore(NewSI, SI);
8060
8061   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8062     if (MatchIsOpZero)
8063       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8064     else
8065       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8066   }
8067   assert(0 && "Shouldn't get here");
8068   return 0;
8069 }
8070
8071 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8072   Value *CondVal = SI.getCondition();
8073   Value *TrueVal = SI.getTrueValue();
8074   Value *FalseVal = SI.getFalseValue();
8075
8076   // select true, X, Y  -> X
8077   // select false, X, Y -> Y
8078   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8079     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8080
8081   // select C, X, X -> X
8082   if (TrueVal == FalseVal)
8083     return ReplaceInstUsesWith(SI, TrueVal);
8084
8085   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8086     return ReplaceInstUsesWith(SI, FalseVal);
8087   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8088     return ReplaceInstUsesWith(SI, TrueVal);
8089   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8090     if (isa<Constant>(TrueVal))
8091       return ReplaceInstUsesWith(SI, TrueVal);
8092     else
8093       return ReplaceInstUsesWith(SI, FalseVal);
8094   }
8095
8096   if (SI.getType() == Type::Int1Ty) {
8097     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8098       if (C->getZExtValue()) {
8099         // Change: A = select B, true, C --> A = or B, C
8100         return BinaryOperator::CreateOr(CondVal, FalseVal);
8101       } else {
8102         // Change: A = select B, false, C --> A = and !B, C
8103         Value *NotCond =
8104           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8105                                              "not."+CondVal->getName()), SI);
8106         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8107       }
8108     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8109       if (C->getZExtValue() == false) {
8110         // Change: A = select B, C, false --> A = and B, C
8111         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8112       } else {
8113         // Change: A = select B, C, true --> A = or !B, C
8114         Value *NotCond =
8115           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8116                                              "not."+CondVal->getName()), SI);
8117         return BinaryOperator::CreateOr(NotCond, TrueVal);
8118       }
8119     }
8120     
8121     // select a, b, a  -> a&b
8122     // select a, a, b  -> a|b
8123     if (CondVal == TrueVal)
8124       return BinaryOperator::CreateOr(CondVal, FalseVal);
8125     else if (CondVal == FalseVal)
8126       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8127   }
8128
8129   // Selecting between two integer constants?
8130   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8131     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8132       // select C, 1, 0 -> zext C to int
8133       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8134         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8135       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8136         // select C, 0, 1 -> zext !C to int
8137         Value *NotCond =
8138           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8139                                                "not."+CondVal->getName()), SI);
8140         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8141       }
8142       
8143       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8144
8145       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8146
8147         // (x <s 0) ? -1 : 0 -> ashr x, 31
8148         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8149           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8150             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8151               // The comparison constant and the result are not neccessarily the
8152               // same width. Make an all-ones value by inserting a AShr.
8153               Value *X = IC->getOperand(0);
8154               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8155               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8156               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8157                                                         ShAmt, "ones");
8158               InsertNewInstBefore(SRA, SI);
8159               
8160               // Finally, convert to the type of the select RHS.  We figure out
8161               // if this requires a SExt, Trunc or BitCast based on the sizes.
8162               Instruction::CastOps opc = Instruction::BitCast;
8163               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8164               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8165               if (SRASize < SISize)
8166                 opc = Instruction::SExt;
8167               else if (SRASize > SISize)
8168                 opc = Instruction::Trunc;
8169               return CastInst::Create(opc, SRA, SI.getType());
8170             }
8171           }
8172
8173
8174         // If one of the constants is zero (we know they can't both be) and we
8175         // have an icmp instruction with zero, and we have an 'and' with the
8176         // non-constant value, eliminate this whole mess.  This corresponds to
8177         // cases like this: ((X & 27) ? 27 : 0)
8178         if (TrueValC->isZero() || FalseValC->isZero())
8179           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8180               cast<Constant>(IC->getOperand(1))->isNullValue())
8181             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8182               if (ICA->getOpcode() == Instruction::And &&
8183                   isa<ConstantInt>(ICA->getOperand(1)) &&
8184                   (ICA->getOperand(1) == TrueValC ||
8185                    ICA->getOperand(1) == FalseValC) &&
8186                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8187                 // Okay, now we know that everything is set up, we just don't
8188                 // know whether we have a icmp_ne or icmp_eq and whether the 
8189                 // true or false val is the zero.
8190                 bool ShouldNotVal = !TrueValC->isZero();
8191                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8192                 Value *V = ICA;
8193                 if (ShouldNotVal)
8194                   V = InsertNewInstBefore(BinaryOperator::Create(
8195                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8196                 return ReplaceInstUsesWith(SI, V);
8197               }
8198       }
8199     }
8200
8201   // See if we are selecting two values based on a comparison of the two values.
8202   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8203     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8204       // Transform (X == Y) ? X : Y  -> Y
8205       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8206         // This is not safe in general for floating point:  
8207         // consider X== -0, Y== +0.
8208         // It becomes safe if either operand is a nonzero constant.
8209         ConstantFP *CFPt, *CFPf;
8210         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8211               !CFPt->getValueAPF().isZero()) ||
8212             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8213              !CFPf->getValueAPF().isZero()))
8214         return ReplaceInstUsesWith(SI, FalseVal);
8215       }
8216       // Transform (X != Y) ? X : Y  -> X
8217       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8218         return ReplaceInstUsesWith(SI, TrueVal);
8219       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8220
8221     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8222       // Transform (X == Y) ? Y : X  -> X
8223       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8224         // This is not safe in general for floating point:  
8225         // consider X== -0, Y== +0.
8226         // It becomes safe if either operand is a nonzero constant.
8227         ConstantFP *CFPt, *CFPf;
8228         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8229               !CFPt->getValueAPF().isZero()) ||
8230             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8231              !CFPf->getValueAPF().isZero()))
8232           return ReplaceInstUsesWith(SI, FalseVal);
8233       }
8234       // Transform (X != Y) ? Y : X  -> Y
8235       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8236         return ReplaceInstUsesWith(SI, TrueVal);
8237       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8238     }
8239   }
8240
8241   // See if we are selecting two values based on a comparison of the two values.
8242   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8243     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8244       // Transform (X == Y) ? X : Y  -> Y
8245       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8246         return ReplaceInstUsesWith(SI, FalseVal);
8247       // Transform (X != Y) ? X : Y  -> X
8248       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8249         return ReplaceInstUsesWith(SI, TrueVal);
8250       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8251
8252     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8253       // Transform (X == Y) ? Y : X  -> X
8254       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8255         return ReplaceInstUsesWith(SI, FalseVal);
8256       // Transform (X != Y) ? Y : X  -> Y
8257       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8258         return ReplaceInstUsesWith(SI, TrueVal);
8259       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8260     }
8261   }
8262
8263   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8264     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8265       if (TI->hasOneUse() && FI->hasOneUse()) {
8266         Instruction *AddOp = 0, *SubOp = 0;
8267
8268         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8269         if (TI->getOpcode() == FI->getOpcode())
8270           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8271             return IV;
8272
8273         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8274         // even legal for FP.
8275         if (TI->getOpcode() == Instruction::Sub &&
8276             FI->getOpcode() == Instruction::Add) {
8277           AddOp = FI; SubOp = TI;
8278         } else if (FI->getOpcode() == Instruction::Sub &&
8279                    TI->getOpcode() == Instruction::Add) {
8280           AddOp = TI; SubOp = FI;
8281         }
8282
8283         if (AddOp) {
8284           Value *OtherAddOp = 0;
8285           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8286             OtherAddOp = AddOp->getOperand(1);
8287           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8288             OtherAddOp = AddOp->getOperand(0);
8289           }
8290
8291           if (OtherAddOp) {
8292             // So at this point we know we have (Y -> OtherAddOp):
8293             //        select C, (add X, Y), (sub X, Z)
8294             Value *NegVal;  // Compute -Z
8295             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8296               NegVal = ConstantExpr::getNeg(C);
8297             } else {
8298               NegVal = InsertNewInstBefore(
8299                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8300             }
8301
8302             Value *NewTrueOp = OtherAddOp;
8303             Value *NewFalseOp = NegVal;
8304             if (AddOp != TI)
8305               std::swap(NewTrueOp, NewFalseOp);
8306             Instruction *NewSel =
8307               SelectInst::Create(CondVal, NewTrueOp,
8308                                  NewFalseOp, SI.getName() + ".p");
8309
8310             NewSel = InsertNewInstBefore(NewSel, SI);
8311             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8312           }
8313         }
8314       }
8315
8316   // See if we can fold the select into one of our operands.
8317   if (SI.getType()->isInteger()) {
8318     // See the comment above GetSelectFoldableOperands for a description of the
8319     // transformation we are doing here.
8320     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8321       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8322           !isa<Constant>(FalseVal))
8323         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8324           unsigned OpToFold = 0;
8325           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8326             OpToFold = 1;
8327           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8328             OpToFold = 2;
8329           }
8330
8331           if (OpToFold) {
8332             Constant *C = GetSelectFoldableConstant(TVI);
8333             Instruction *NewSel =
8334               SelectInst::Create(SI.getCondition(),
8335                                  TVI->getOperand(2-OpToFold), C);
8336             InsertNewInstBefore(NewSel, SI);
8337             NewSel->takeName(TVI);
8338             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8339               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8340             else {
8341               assert(0 && "Unknown instruction!!");
8342             }
8343           }
8344         }
8345
8346     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8347       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8348           !isa<Constant>(TrueVal))
8349         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8350           unsigned OpToFold = 0;
8351           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8352             OpToFold = 1;
8353           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8354             OpToFold = 2;
8355           }
8356
8357           if (OpToFold) {
8358             Constant *C = GetSelectFoldableConstant(FVI);
8359             Instruction *NewSel =
8360               SelectInst::Create(SI.getCondition(), C,
8361                                  FVI->getOperand(2-OpToFold));
8362             InsertNewInstBefore(NewSel, SI);
8363             NewSel->takeName(FVI);
8364             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8365               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8366             else
8367               assert(0 && "Unknown instruction!!");
8368           }
8369         }
8370   }
8371
8372   if (BinaryOperator::isNot(CondVal)) {
8373     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8374     SI.setOperand(1, FalseVal);
8375     SI.setOperand(2, TrueVal);
8376     return &SI;
8377   }
8378
8379   return 0;
8380 }
8381
8382 /// EnforceKnownAlignment - If the specified pointer points to an object that
8383 /// we control, modify the object's alignment to PrefAlign. This isn't
8384 /// often possible though. If alignment is important, a more reliable approach
8385 /// is to simply align all global variables and allocation instructions to
8386 /// their preferred alignment from the beginning.
8387 ///
8388 static unsigned EnforceKnownAlignment(Value *V,
8389                                       unsigned Align, unsigned PrefAlign) {
8390
8391   User *U = dyn_cast<User>(V);
8392   if (!U) return Align;
8393
8394   switch (getOpcode(U)) {
8395   default: break;
8396   case Instruction::BitCast:
8397     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8398   case Instruction::GetElementPtr: {
8399     // If all indexes are zero, it is just the alignment of the base pointer.
8400     bool AllZeroOperands = true;
8401     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8402       if (!isa<Constant>(*i) ||
8403           !cast<Constant>(*i)->isNullValue()) {
8404         AllZeroOperands = false;
8405         break;
8406       }
8407
8408     if (AllZeroOperands) {
8409       // Treat this like a bitcast.
8410       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8411     }
8412     break;
8413   }
8414   }
8415
8416   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8417     // If there is a large requested alignment and we can, bump up the alignment
8418     // of the global.
8419     if (!GV->isDeclaration()) {
8420       GV->setAlignment(PrefAlign);
8421       Align = PrefAlign;
8422     }
8423   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8424     // If there is a requested alignment and if this is an alloca, round up.  We
8425     // don't do this for malloc, because some systems can't respect the request.
8426     if (isa<AllocaInst>(AI)) {
8427       AI->setAlignment(PrefAlign);
8428       Align = PrefAlign;
8429     }
8430   }
8431
8432   return Align;
8433 }
8434
8435 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8436 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8437 /// and it is more than the alignment of the ultimate object, see if we can
8438 /// increase the alignment of the ultimate object, making this check succeed.
8439 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8440                                                   unsigned PrefAlign) {
8441   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8442                       sizeof(PrefAlign) * CHAR_BIT;
8443   APInt Mask = APInt::getAllOnesValue(BitWidth);
8444   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8445   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8446   unsigned TrailZ = KnownZero.countTrailingOnes();
8447   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8448
8449   if (PrefAlign > Align)
8450     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8451   
8452     // We don't need to make any adjustment.
8453   return Align;
8454 }
8455
8456 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8457   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8458   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8459   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8460   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8461
8462   if (CopyAlign < MinAlign) {
8463     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8464     return MI;
8465   }
8466   
8467   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8468   // load/store.
8469   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8470   if (MemOpLength == 0) return 0;
8471   
8472   // Source and destination pointer types are always "i8*" for intrinsic.  See
8473   // if the size is something we can handle with a single primitive load/store.
8474   // A single load+store correctly handles overlapping memory in the memmove
8475   // case.
8476   unsigned Size = MemOpLength->getZExtValue();
8477   if (Size == 0) return MI;  // Delete this mem transfer.
8478   
8479   if (Size > 8 || (Size&(Size-1)))
8480     return 0;  // If not 1/2/4/8 bytes, exit.
8481   
8482   // Use an integer load+store unless we can find something better.
8483   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8484   
8485   // Memcpy forces the use of i8* for the source and destination.  That means
8486   // that if you're using memcpy to move one double around, you'll get a cast
8487   // from double* to i8*.  We'd much rather use a double load+store rather than
8488   // an i64 load+store, here because this improves the odds that the source or
8489   // dest address will be promotable.  See if we can find a better type than the
8490   // integer datatype.
8491   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8492     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8493     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8494       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8495       // down through these levels if so.
8496       while (!SrcETy->isSingleValueType()) {
8497         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8498           if (STy->getNumElements() == 1)
8499             SrcETy = STy->getElementType(0);
8500           else
8501             break;
8502         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8503           if (ATy->getNumElements() == 1)
8504             SrcETy = ATy->getElementType();
8505           else
8506             break;
8507         } else
8508           break;
8509       }
8510       
8511       if (SrcETy->isSingleValueType())
8512         NewPtrTy = PointerType::getUnqual(SrcETy);
8513     }
8514   }
8515   
8516   
8517   // If the memcpy/memmove provides better alignment info than we can
8518   // infer, use it.
8519   SrcAlign = std::max(SrcAlign, CopyAlign);
8520   DstAlign = std::max(DstAlign, CopyAlign);
8521   
8522   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8523   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8524   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8525   InsertNewInstBefore(L, *MI);
8526   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8527
8528   // Set the size of the copy to 0, it will be deleted on the next iteration.
8529   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8530   return MI;
8531 }
8532
8533 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8534   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8535   if (MI->getAlignment()->getZExtValue() < Alignment) {
8536     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8537     return MI;
8538   }
8539   
8540   // Extract the length and alignment and fill if they are constant.
8541   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8542   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8543   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8544     return 0;
8545   uint64_t Len = LenC->getZExtValue();
8546   Alignment = MI->getAlignment()->getZExtValue();
8547   
8548   // If the length is zero, this is a no-op
8549   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8550   
8551   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8552   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8553     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8554     
8555     Value *Dest = MI->getDest();
8556     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8557
8558     // Alignment 0 is identity for alignment 1 for memset, but not store.
8559     if (Alignment == 0) Alignment = 1;
8560     
8561     // Extract the fill value and store.
8562     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8563     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8564                                       Alignment), *MI);
8565     
8566     // Set the size of the copy to 0, it will be deleted on the next iteration.
8567     MI->setLength(Constant::getNullValue(LenC->getType()));
8568     return MI;
8569   }
8570
8571   return 0;
8572 }
8573
8574
8575 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8576 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8577 /// the heavy lifting.
8578 ///
8579 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8580   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8581   if (!II) return visitCallSite(&CI);
8582   
8583   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8584   // visitCallSite.
8585   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8586     bool Changed = false;
8587
8588     // memmove/cpy/set of zero bytes is a noop.
8589     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8590       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8591
8592       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8593         if (CI->getZExtValue() == 1) {
8594           // Replace the instruction with just byte operations.  We would
8595           // transform other cases to loads/stores, but we don't know if
8596           // alignment is sufficient.
8597         }
8598     }
8599
8600     // If we have a memmove and the source operation is a constant global,
8601     // then the source and dest pointers can't alias, so we can change this
8602     // into a call to memcpy.
8603     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8604       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8605         if (GVSrc->isConstant()) {
8606           Module *M = CI.getParent()->getParent()->getParent();
8607           Intrinsic::ID MemCpyID;
8608           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8609             MemCpyID = Intrinsic::memcpy_i32;
8610           else
8611             MemCpyID = Intrinsic::memcpy_i64;
8612           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8613           Changed = true;
8614         }
8615
8616       // memmove(x,x,size) -> noop.
8617       if (MMI->getSource() == MMI->getDest())
8618         return EraseInstFromFunction(CI);
8619     }
8620
8621     // If we can determine a pointer alignment that is bigger than currently
8622     // set, update the alignment.
8623     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8624       if (Instruction *I = SimplifyMemTransfer(MI))
8625         return I;
8626     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8627       if (Instruction *I = SimplifyMemSet(MSI))
8628         return I;
8629     }
8630           
8631     if (Changed) return II;
8632   }
8633   
8634   switch (II->getIntrinsicID()) {
8635   default: break;
8636   case Intrinsic::bswap:
8637     // bswap(bswap(x)) -> x
8638     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8639       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8640         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8641     break;
8642   case Intrinsic::ppc_altivec_lvx:
8643   case Intrinsic::ppc_altivec_lvxl:
8644   case Intrinsic::x86_sse_loadu_ps:
8645   case Intrinsic::x86_sse2_loadu_pd:
8646   case Intrinsic::x86_sse2_loadu_dq:
8647     // Turn PPC lvx     -> load if the pointer is known aligned.
8648     // Turn X86 loadups -> load if the pointer is known aligned.
8649     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8650       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8651                                        PointerType::getUnqual(II->getType()),
8652                                        CI);
8653       return new LoadInst(Ptr);
8654     }
8655     break;
8656   case Intrinsic::ppc_altivec_stvx:
8657   case Intrinsic::ppc_altivec_stvxl:
8658     // Turn stvx -> store if the pointer is known aligned.
8659     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8660       const Type *OpPtrTy = 
8661         PointerType::getUnqual(II->getOperand(1)->getType());
8662       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8663       return new StoreInst(II->getOperand(1), Ptr);
8664     }
8665     break;
8666   case Intrinsic::x86_sse_storeu_ps:
8667   case Intrinsic::x86_sse2_storeu_pd:
8668   case Intrinsic::x86_sse2_storeu_dq:
8669   case Intrinsic::x86_sse2_storel_dq:
8670     // Turn X86 storeu -> store if the pointer is known aligned.
8671     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8672       const Type *OpPtrTy = 
8673         PointerType::getUnqual(II->getOperand(2)->getType());
8674       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8675       return new StoreInst(II->getOperand(2), Ptr);
8676     }
8677     break;
8678     
8679   case Intrinsic::x86_sse_cvttss2si: {
8680     // These intrinsics only demands the 0th element of its input vector.  If
8681     // we can simplify the input based on that, do so now.
8682     uint64_t UndefElts;
8683     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8684                                               UndefElts)) {
8685       II->setOperand(1, V);
8686       return II;
8687     }
8688     break;
8689   }
8690     
8691   case Intrinsic::ppc_altivec_vperm:
8692     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8693     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8694       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8695       
8696       // Check that all of the elements are integer constants or undefs.
8697       bool AllEltsOk = true;
8698       for (unsigned i = 0; i != 16; ++i) {
8699         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8700             !isa<UndefValue>(Mask->getOperand(i))) {
8701           AllEltsOk = false;
8702           break;
8703         }
8704       }
8705       
8706       if (AllEltsOk) {
8707         // Cast the input vectors to byte vectors.
8708         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8709         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8710         Value *Result = UndefValue::get(Op0->getType());
8711         
8712         // Only extract each element once.
8713         Value *ExtractedElts[32];
8714         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8715         
8716         for (unsigned i = 0; i != 16; ++i) {
8717           if (isa<UndefValue>(Mask->getOperand(i)))
8718             continue;
8719           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8720           Idx &= 31;  // Match the hardware behavior.
8721           
8722           if (ExtractedElts[Idx] == 0) {
8723             Instruction *Elt = 
8724               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8725             InsertNewInstBefore(Elt, CI);
8726             ExtractedElts[Idx] = Elt;
8727           }
8728         
8729           // Insert this value into the result vector.
8730           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8731                                              i, "tmp");
8732           InsertNewInstBefore(cast<Instruction>(Result), CI);
8733         }
8734         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8735       }
8736     }
8737     break;
8738
8739   case Intrinsic::stackrestore: {
8740     // If the save is right next to the restore, remove the restore.  This can
8741     // happen when variable allocas are DCE'd.
8742     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8743       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8744         BasicBlock::iterator BI = SS;
8745         if (&*++BI == II)
8746           return EraseInstFromFunction(CI);
8747       }
8748     }
8749     
8750     // Scan down this block to see if there is another stack restore in the
8751     // same block without an intervening call/alloca.
8752     BasicBlock::iterator BI = II;
8753     TerminatorInst *TI = II->getParent()->getTerminator();
8754     bool CannotRemove = false;
8755     for (++BI; &*BI != TI; ++BI) {
8756       if (isa<AllocaInst>(BI)) {
8757         CannotRemove = true;
8758         break;
8759       }
8760       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8761         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8762           // If there is a stackrestore below this one, remove this one.
8763           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8764             return EraseInstFromFunction(CI);
8765           // Otherwise, ignore the intrinsic.
8766         } else {
8767           // If we found a non-intrinsic call, we can't remove the stack
8768           // restore.
8769           CannotRemove = true;
8770           break;
8771         }
8772       }
8773     }
8774     
8775     // If the stack restore is in a return/unwind block and if there are no
8776     // allocas or calls between the restore and the return, nuke the restore.
8777     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8778       return EraseInstFromFunction(CI);
8779     break;
8780   }
8781   }
8782
8783   return visitCallSite(II);
8784 }
8785
8786 // InvokeInst simplification
8787 //
8788 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8789   return visitCallSite(&II);
8790 }
8791
8792 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8793 /// passed through the varargs area, we can eliminate the use of the cast.
8794 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8795                                          const CastInst * const CI,
8796                                          const TargetData * const TD,
8797                                          const int ix) {
8798   if (!CI->isLosslessCast())
8799     return false;
8800
8801   // The size of ByVal arguments is derived from the type, so we
8802   // can't change to a type with a different size.  If the size were
8803   // passed explicitly we could avoid this check.
8804   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8805     return true;
8806
8807   const Type* SrcTy = 
8808             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8809   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8810   if (!SrcTy->isSized() || !DstTy->isSized())
8811     return false;
8812   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8813     return false;
8814   return true;
8815 }
8816
8817 // visitCallSite - Improvements for call and invoke instructions.
8818 //
8819 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8820   bool Changed = false;
8821
8822   // If the callee is a constexpr cast of a function, attempt to move the cast
8823   // to the arguments of the call/invoke.
8824   if (transformConstExprCastCall(CS)) return 0;
8825
8826   Value *Callee = CS.getCalledValue();
8827
8828   if (Function *CalleeF = dyn_cast<Function>(Callee))
8829     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8830       Instruction *OldCall = CS.getInstruction();
8831       // If the call and callee calling conventions don't match, this call must
8832       // be unreachable, as the call is undefined.
8833       new StoreInst(ConstantInt::getTrue(),
8834                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8835                                     OldCall);
8836       if (!OldCall->use_empty())
8837         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8838       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8839         return EraseInstFromFunction(*OldCall);
8840       return 0;
8841     }
8842
8843   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8844     // This instruction is not reachable, just remove it.  We insert a store to
8845     // undef so that we know that this code is not reachable, despite the fact
8846     // that we can't modify the CFG here.
8847     new StoreInst(ConstantInt::getTrue(),
8848                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8849                   CS.getInstruction());
8850
8851     if (!CS.getInstruction()->use_empty())
8852       CS.getInstruction()->
8853         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8854
8855     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8856       // Don't break the CFG, insert a dummy cond branch.
8857       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8858                          ConstantInt::getTrue(), II);
8859     }
8860     return EraseInstFromFunction(*CS.getInstruction());
8861   }
8862
8863   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8864     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8865       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8866         return transformCallThroughTrampoline(CS);
8867
8868   const PointerType *PTy = cast<PointerType>(Callee->getType());
8869   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8870   if (FTy->isVarArg()) {
8871     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8872     // See if we can optimize any arguments passed through the varargs area of
8873     // the call.
8874     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8875            E = CS.arg_end(); I != E; ++I, ++ix) {
8876       CastInst *CI = dyn_cast<CastInst>(*I);
8877       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8878         *I = CI->getOperand(0);
8879         Changed = true;
8880       }
8881     }
8882   }
8883
8884   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8885     // Inline asm calls cannot throw - mark them 'nounwind'.
8886     CS.setDoesNotThrow();
8887     Changed = true;
8888   }
8889
8890   return Changed ? CS.getInstruction() : 0;
8891 }
8892
8893 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8894 // attempt to move the cast to the arguments of the call/invoke.
8895 //
8896 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8897   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8898   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8899   if (CE->getOpcode() != Instruction::BitCast || 
8900       !isa<Function>(CE->getOperand(0)))
8901     return false;
8902   Function *Callee = cast<Function>(CE->getOperand(0));
8903   Instruction *Caller = CS.getInstruction();
8904   const PAListPtr &CallerPAL = CS.getParamAttrs();
8905
8906   // Okay, this is a cast from a function to a different type.  Unless doing so
8907   // would cause a type conversion of one of our arguments, change this call to
8908   // be a direct call with arguments casted to the appropriate types.
8909   //
8910   const FunctionType *FT = Callee->getFunctionType();
8911   const Type *OldRetTy = Caller->getType();
8912   const Type *NewRetTy = FT->getReturnType();
8913
8914   if (isa<StructType>(NewRetTy))
8915     return false; // TODO: Handle multiple return values.
8916
8917   // Check to see if we are changing the return type...
8918   if (OldRetTy != NewRetTy) {
8919     if (Callee->isDeclaration() &&
8920         // Conversion is ok if changing from one pointer type to another or from
8921         // a pointer to an integer of the same size.
8922         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8923           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8924       return false;   // Cannot transform this return value.
8925
8926     if (!Caller->use_empty() &&
8927         // void -> non-void is handled specially
8928         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8929       return false;   // Cannot transform this return value.
8930
8931     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8932       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8933       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8934         return false;   // Attribute not compatible with transformed value.
8935     }
8936
8937     // If the callsite is an invoke instruction, and the return value is used by
8938     // a PHI node in a successor, we cannot change the return type of the call
8939     // because there is no place to put the cast instruction (without breaking
8940     // the critical edge).  Bail out in this case.
8941     if (!Caller->use_empty())
8942       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8943         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8944              UI != E; ++UI)
8945           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8946             if (PN->getParent() == II->getNormalDest() ||
8947                 PN->getParent() == II->getUnwindDest())
8948               return false;
8949   }
8950
8951   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8952   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8953
8954   CallSite::arg_iterator AI = CS.arg_begin();
8955   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8956     const Type *ParamTy = FT->getParamType(i);
8957     const Type *ActTy = (*AI)->getType();
8958
8959     if (!CastInst::isCastable(ActTy, ParamTy))
8960       return false;   // Cannot transform this parameter value.
8961
8962     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8963       return false;   // Attribute not compatible with transformed value.
8964
8965     // Converting from one pointer type to another or between a pointer and an
8966     // integer of the same size is safe even if we do not have a body.
8967     bool isConvertible = ActTy == ParamTy ||
8968       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8969        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8970     if (Callee->isDeclaration() && !isConvertible) return false;
8971   }
8972
8973   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8974       Callee->isDeclaration())
8975     return false;   // Do not delete arguments unless we have a function body.
8976
8977   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8978       !CallerPAL.isEmpty())
8979     // In this case we have more arguments than the new function type, but we
8980     // won't be dropping them.  Check that these extra arguments have attributes
8981     // that are compatible with being a vararg call argument.
8982     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8983       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8984         break;
8985       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8986       if (PAttrs & ParamAttr::VarArgsIncompatible)
8987         return false;
8988     }
8989
8990   // Okay, we decided that this is a safe thing to do: go ahead and start
8991   // inserting cast instructions as necessary...
8992   std::vector<Value*> Args;
8993   Args.reserve(NumActualArgs);
8994   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8995   attrVec.reserve(NumCommonArgs);
8996
8997   // Get any return attributes.
8998   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8999
9000   // If the return value is not being used, the type may not be compatible
9001   // with the existing attributes.  Wipe out any problematic attributes.
9002   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
9003
9004   // Add the new return attributes.
9005   if (RAttrs)
9006     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9007
9008   AI = CS.arg_begin();
9009   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9010     const Type *ParamTy = FT->getParamType(i);
9011     if ((*AI)->getType() == ParamTy) {
9012       Args.push_back(*AI);
9013     } else {
9014       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9015           false, ParamTy, false);
9016       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9017       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9018     }
9019
9020     // Add any parameter attributes.
9021     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9022       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9023   }
9024
9025   // If the function takes more arguments than the call was taking, add them
9026   // now...
9027   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9028     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9029
9030   // If we are removing arguments to the function, emit an obnoxious warning...
9031   if (FT->getNumParams() < NumActualArgs) {
9032     if (!FT->isVarArg()) {
9033       cerr << "WARNING: While resolving call to function '"
9034            << Callee->getName() << "' arguments were dropped!\n";
9035     } else {
9036       // Add all of the arguments in their promoted form to the arg list...
9037       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9038         const Type *PTy = getPromotedType((*AI)->getType());
9039         if (PTy != (*AI)->getType()) {
9040           // Must promote to pass through va_arg area!
9041           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9042                                                                 PTy, false);
9043           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9044           InsertNewInstBefore(Cast, *Caller);
9045           Args.push_back(Cast);
9046         } else {
9047           Args.push_back(*AI);
9048         }
9049
9050         // Add any parameter attributes.
9051         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9052           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9053       }
9054     }
9055   }
9056
9057   if (NewRetTy == Type::VoidTy)
9058     Caller->setName("");   // Void type should not have a name.
9059
9060   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9061
9062   Instruction *NC;
9063   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9064     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9065                             Args.begin(), Args.end(),
9066                             Caller->getName(), Caller);
9067     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9068     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9069   } else {
9070     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9071                           Caller->getName(), Caller);
9072     CallInst *CI = cast<CallInst>(Caller);
9073     if (CI->isTailCall())
9074       cast<CallInst>(NC)->setTailCall();
9075     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9076     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9077   }
9078
9079   // Insert a cast of the return type as necessary.
9080   Value *NV = NC;
9081   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9082     if (NV->getType() != Type::VoidTy) {
9083       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9084                                                             OldRetTy, false);
9085       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9086
9087       // If this is an invoke instruction, we should insert it after the first
9088       // non-phi, instruction in the normal successor block.
9089       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9090         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9091         InsertNewInstBefore(NC, *I);
9092       } else {
9093         // Otherwise, it's a call, just insert cast right after the call instr
9094         InsertNewInstBefore(NC, *Caller);
9095       }
9096       AddUsersToWorkList(*Caller);
9097     } else {
9098       NV = UndefValue::get(Caller->getType());
9099     }
9100   }
9101
9102   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9103     Caller->replaceAllUsesWith(NV);
9104   Caller->eraseFromParent();
9105   RemoveFromWorkList(Caller);
9106   return true;
9107 }
9108
9109 // transformCallThroughTrampoline - Turn a call to a function created by the
9110 // init_trampoline intrinsic into a direct call to the underlying function.
9111 //
9112 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9113   Value *Callee = CS.getCalledValue();
9114   const PointerType *PTy = cast<PointerType>(Callee->getType());
9115   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9116   const PAListPtr &Attrs = CS.getParamAttrs();
9117
9118   // If the call already has the 'nest' attribute somewhere then give up -
9119   // otherwise 'nest' would occur twice after splicing in the chain.
9120   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9121     return 0;
9122
9123   IntrinsicInst *Tramp =
9124     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9125
9126   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9127   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9128   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9129
9130   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9131   if (!NestAttrs.isEmpty()) {
9132     unsigned NestIdx = 1;
9133     const Type *NestTy = 0;
9134     ParameterAttributes NestAttr = ParamAttr::None;
9135
9136     // Look for a parameter marked with the 'nest' attribute.
9137     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9138          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9139       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9140         // Record the parameter type and any other attributes.
9141         NestTy = *I;
9142         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9143         break;
9144       }
9145
9146     if (NestTy) {
9147       Instruction *Caller = CS.getInstruction();
9148       std::vector<Value*> NewArgs;
9149       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9150
9151       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9152       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9153
9154       // Insert the nest argument into the call argument list, which may
9155       // mean appending it.  Likewise for attributes.
9156
9157       // Add any function result attributes.
9158       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9159         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9160
9161       {
9162         unsigned Idx = 1;
9163         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9164         do {
9165           if (Idx == NestIdx) {
9166             // Add the chain argument and attributes.
9167             Value *NestVal = Tramp->getOperand(3);
9168             if (NestVal->getType() != NestTy)
9169               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9170             NewArgs.push_back(NestVal);
9171             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9172           }
9173
9174           if (I == E)
9175             break;
9176
9177           // Add the original argument and attributes.
9178           NewArgs.push_back(*I);
9179           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9180             NewAttrs.push_back
9181               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9182
9183           ++Idx, ++I;
9184         } while (1);
9185       }
9186
9187       // The trampoline may have been bitcast to a bogus type (FTy).
9188       // Handle this by synthesizing a new function type, equal to FTy
9189       // with the chain parameter inserted.
9190
9191       std::vector<const Type*> NewTypes;
9192       NewTypes.reserve(FTy->getNumParams()+1);
9193
9194       // Insert the chain's type into the list of parameter types, which may
9195       // mean appending it.
9196       {
9197         unsigned Idx = 1;
9198         FunctionType::param_iterator I = FTy->param_begin(),
9199           E = FTy->param_end();
9200
9201         do {
9202           if (Idx == NestIdx)
9203             // Add the chain's type.
9204             NewTypes.push_back(NestTy);
9205
9206           if (I == E)
9207             break;
9208
9209           // Add the original type.
9210           NewTypes.push_back(*I);
9211
9212           ++Idx, ++I;
9213         } while (1);
9214       }
9215
9216       // Replace the trampoline call with a direct call.  Let the generic
9217       // code sort out any function type mismatches.
9218       FunctionType *NewFTy =
9219         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9220       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9221         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9222       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9223
9224       Instruction *NewCaller;
9225       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9226         NewCaller = InvokeInst::Create(NewCallee,
9227                                        II->getNormalDest(), II->getUnwindDest(),
9228                                        NewArgs.begin(), NewArgs.end(),
9229                                        Caller->getName(), Caller);
9230         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9231         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9232       } else {
9233         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9234                                      Caller->getName(), Caller);
9235         if (cast<CallInst>(Caller)->isTailCall())
9236           cast<CallInst>(NewCaller)->setTailCall();
9237         cast<CallInst>(NewCaller)->
9238           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9239         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9240       }
9241       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9242         Caller->replaceAllUsesWith(NewCaller);
9243       Caller->eraseFromParent();
9244       RemoveFromWorkList(Caller);
9245       return 0;
9246     }
9247   }
9248
9249   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9250   // parameter, there is no need to adjust the argument list.  Let the generic
9251   // code sort out any function type mismatches.
9252   Constant *NewCallee =
9253     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9254   CS.setCalledFunction(NewCallee);
9255   return CS.getInstruction();
9256 }
9257
9258 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9259 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9260 /// and a single binop.
9261 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9262   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9263   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9264          isa<CmpInst>(FirstInst));
9265   unsigned Opc = FirstInst->getOpcode();
9266   Value *LHSVal = FirstInst->getOperand(0);
9267   Value *RHSVal = FirstInst->getOperand(1);
9268     
9269   const Type *LHSType = LHSVal->getType();
9270   const Type *RHSType = RHSVal->getType();
9271   
9272   // Scan to see if all operands are the same opcode, all have one use, and all
9273   // kill their operands (i.e. the operands have one use).
9274   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9275     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9276     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9277         // Verify type of the LHS matches so we don't fold cmp's of different
9278         // types or GEP's with different index types.
9279         I->getOperand(0)->getType() != LHSType ||
9280         I->getOperand(1)->getType() != RHSType)
9281       return 0;
9282
9283     // If they are CmpInst instructions, check their predicates
9284     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9285       if (cast<CmpInst>(I)->getPredicate() !=
9286           cast<CmpInst>(FirstInst)->getPredicate())
9287         return 0;
9288     
9289     // Keep track of which operand needs a phi node.
9290     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9291     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9292   }
9293   
9294   // Otherwise, this is safe to transform, determine if it is profitable.
9295
9296   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9297   // Indexes are often folded into load/store instructions, so we don't want to
9298   // hide them behind a phi.
9299   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9300     return 0;
9301   
9302   Value *InLHS = FirstInst->getOperand(0);
9303   Value *InRHS = FirstInst->getOperand(1);
9304   PHINode *NewLHS = 0, *NewRHS = 0;
9305   if (LHSVal == 0) {
9306     NewLHS = PHINode::Create(LHSType,
9307                              FirstInst->getOperand(0)->getName() + ".pn");
9308     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9309     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9310     InsertNewInstBefore(NewLHS, PN);
9311     LHSVal = NewLHS;
9312   }
9313   
9314   if (RHSVal == 0) {
9315     NewRHS = PHINode::Create(RHSType,
9316                              FirstInst->getOperand(1)->getName() + ".pn");
9317     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9318     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9319     InsertNewInstBefore(NewRHS, PN);
9320     RHSVal = NewRHS;
9321   }
9322   
9323   // Add all operands to the new PHIs.
9324   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9325     if (NewLHS) {
9326       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9327       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9328     }
9329     if (NewRHS) {
9330       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9331       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9332     }
9333   }
9334     
9335   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9336     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9337   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9338     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9339                            RHSVal);
9340   else {
9341     assert(isa<GetElementPtrInst>(FirstInst));
9342     return GetElementPtrInst::Create(LHSVal, RHSVal);
9343   }
9344 }
9345
9346 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9347 /// of the block that defines it.  This means that it must be obvious the value
9348 /// of the load is not changed from the point of the load to the end of the
9349 /// block it is in.
9350 ///
9351 /// Finally, it is safe, but not profitable, to sink a load targetting a
9352 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9353 /// to a register.
9354 static bool isSafeToSinkLoad(LoadInst *L) {
9355   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9356   
9357   for (++BBI; BBI != E; ++BBI)
9358     if (BBI->mayWriteToMemory())
9359       return false;
9360   
9361   // Check for non-address taken alloca.  If not address-taken already, it isn't
9362   // profitable to do this xform.
9363   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9364     bool isAddressTaken = false;
9365     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9366          UI != E; ++UI) {
9367       if (isa<LoadInst>(UI)) continue;
9368       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9369         // If storing TO the alloca, then the address isn't taken.
9370         if (SI->getOperand(1) == AI) continue;
9371       }
9372       isAddressTaken = true;
9373       break;
9374     }
9375     
9376     if (!isAddressTaken)
9377       return false;
9378   }
9379   
9380   return true;
9381 }
9382
9383
9384 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9385 // operator and they all are only used by the PHI, PHI together their
9386 // inputs, and do the operation once, to the result of the PHI.
9387 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9388   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9389
9390   // Scan the instruction, looking for input operations that can be folded away.
9391   // If all input operands to the phi are the same instruction (e.g. a cast from
9392   // the same type or "+42") we can pull the operation through the PHI, reducing
9393   // code size and simplifying code.
9394   Constant *ConstantOp = 0;
9395   const Type *CastSrcTy = 0;
9396   bool isVolatile = false;
9397   if (isa<CastInst>(FirstInst)) {
9398     CastSrcTy = FirstInst->getOperand(0)->getType();
9399   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9400     // Can fold binop, compare or shift here if the RHS is a constant, 
9401     // otherwise call FoldPHIArgBinOpIntoPHI.
9402     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9403     if (ConstantOp == 0)
9404       return FoldPHIArgBinOpIntoPHI(PN);
9405   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9406     isVolatile = LI->isVolatile();
9407     // We can't sink the load if the loaded value could be modified between the
9408     // load and the PHI.
9409     if (LI->getParent() != PN.getIncomingBlock(0) ||
9410         !isSafeToSinkLoad(LI))
9411       return 0;
9412     
9413     // If the PHI is of volatile loads and the load block has multiple
9414     // successors, sinking it would remove a load of the volatile value from
9415     // the path through the other successor.
9416     if (isVolatile &&
9417         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9418       return 0;
9419     
9420   } else if (isa<GetElementPtrInst>(FirstInst)) {
9421     if (FirstInst->getNumOperands() == 2)
9422       return FoldPHIArgBinOpIntoPHI(PN);
9423     // Can't handle general GEPs yet.
9424     return 0;
9425   } else {
9426     return 0;  // Cannot fold this operation.
9427   }
9428
9429   // Check to see if all arguments are the same operation.
9430   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9431     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9432     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9433     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9434       return 0;
9435     if (CastSrcTy) {
9436       if (I->getOperand(0)->getType() != CastSrcTy)
9437         return 0;  // Cast operation must match.
9438     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9439       // We can't sink the load if the loaded value could be modified between 
9440       // the load and the PHI.
9441       if (LI->isVolatile() != isVolatile ||
9442           LI->getParent() != PN.getIncomingBlock(i) ||
9443           !isSafeToSinkLoad(LI))
9444         return 0;
9445       
9446       // If the PHI is of volatile loads and the load block has multiple
9447       // successors, sinking it would remove a load of the volatile value from
9448       // the path through the other successor.
9449       if (isVolatile &&
9450           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9451         return 0;
9452
9453       
9454     } else if (I->getOperand(1) != ConstantOp) {
9455       return 0;
9456     }
9457   }
9458
9459   // Okay, they are all the same operation.  Create a new PHI node of the
9460   // correct type, and PHI together all of the LHS's of the instructions.
9461   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9462                                    PN.getName()+".in");
9463   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9464
9465   Value *InVal = FirstInst->getOperand(0);
9466   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9467
9468   // Add all operands to the new PHI.
9469   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9470     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9471     if (NewInVal != InVal)
9472       InVal = 0;
9473     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9474   }
9475
9476   Value *PhiVal;
9477   if (InVal) {
9478     // The new PHI unions all of the same values together.  This is really
9479     // common, so we handle it intelligently here for compile-time speed.
9480     PhiVal = InVal;
9481     delete NewPN;
9482   } else {
9483     InsertNewInstBefore(NewPN, PN);
9484     PhiVal = NewPN;
9485   }
9486
9487   // Insert and return the new operation.
9488   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9489     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9490   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9491     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9492   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9493     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9494                            PhiVal, ConstantOp);
9495   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9496   
9497   // If this was a volatile load that we are merging, make sure to loop through
9498   // and mark all the input loads as non-volatile.  If we don't do this, we will
9499   // insert a new volatile load and the old ones will not be deletable.
9500   if (isVolatile)
9501     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9502       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9503   
9504   return new LoadInst(PhiVal, "", isVolatile);
9505 }
9506
9507 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9508 /// that is dead.
9509 static bool DeadPHICycle(PHINode *PN,
9510                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9511   if (PN->use_empty()) return true;
9512   if (!PN->hasOneUse()) return false;
9513
9514   // Remember this node, and if we find the cycle, return.
9515   if (!PotentiallyDeadPHIs.insert(PN))
9516     return true;
9517   
9518   // Don't scan crazily complex things.
9519   if (PotentiallyDeadPHIs.size() == 16)
9520     return false;
9521
9522   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9523     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9524
9525   return false;
9526 }
9527
9528 /// PHIsEqualValue - Return true if this phi node is always equal to
9529 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9530 ///   z = some value; x = phi (y, z); y = phi (x, z)
9531 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9532                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9533   // See if we already saw this PHI node.
9534   if (!ValueEqualPHIs.insert(PN))
9535     return true;
9536   
9537   // Don't scan crazily complex things.
9538   if (ValueEqualPHIs.size() == 16)
9539     return false;
9540  
9541   // Scan the operands to see if they are either phi nodes or are equal to
9542   // the value.
9543   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9544     Value *Op = PN->getIncomingValue(i);
9545     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9546       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9547         return false;
9548     } else if (Op != NonPhiInVal)
9549       return false;
9550   }
9551   
9552   return true;
9553 }
9554
9555
9556 // PHINode simplification
9557 //
9558 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9559   // If LCSSA is around, don't mess with Phi nodes
9560   if (MustPreserveLCSSA) return 0;
9561   
9562   if (Value *V = PN.hasConstantValue())
9563     return ReplaceInstUsesWith(PN, V);
9564
9565   // If all PHI operands are the same operation, pull them through the PHI,
9566   // reducing code size.
9567   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9568       PN.getIncomingValue(0)->hasOneUse())
9569     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9570       return Result;
9571
9572   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9573   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9574   // PHI)... break the cycle.
9575   if (PN.hasOneUse()) {
9576     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9577     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9578       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9579       PotentiallyDeadPHIs.insert(&PN);
9580       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9581         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9582     }
9583    
9584     // If this phi has a single use, and if that use just computes a value for
9585     // the next iteration of a loop, delete the phi.  This occurs with unused
9586     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9587     // common case here is good because the only other things that catch this
9588     // are induction variable analysis (sometimes) and ADCE, which is only run
9589     // late.
9590     if (PHIUser->hasOneUse() &&
9591         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9592         PHIUser->use_back() == &PN) {
9593       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9594     }
9595   }
9596
9597   // We sometimes end up with phi cycles that non-obviously end up being the
9598   // same value, for example:
9599   //   z = some value; x = phi (y, z); y = phi (x, z)
9600   // where the phi nodes don't necessarily need to be in the same block.  Do a
9601   // quick check to see if the PHI node only contains a single non-phi value, if
9602   // so, scan to see if the phi cycle is actually equal to that value.
9603   {
9604     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9605     // Scan for the first non-phi operand.
9606     while (InValNo != NumOperandVals && 
9607            isa<PHINode>(PN.getIncomingValue(InValNo)))
9608       ++InValNo;
9609
9610     if (InValNo != NumOperandVals) {
9611       Value *NonPhiInVal = PN.getOperand(InValNo);
9612       
9613       // Scan the rest of the operands to see if there are any conflicts, if so
9614       // there is no need to recursively scan other phis.
9615       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9616         Value *OpVal = PN.getIncomingValue(InValNo);
9617         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9618           break;
9619       }
9620       
9621       // If we scanned over all operands, then we have one unique value plus
9622       // phi values.  Scan PHI nodes to see if they all merge in each other or
9623       // the value.
9624       if (InValNo == NumOperandVals) {
9625         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9626         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9627           return ReplaceInstUsesWith(PN, NonPhiInVal);
9628       }
9629     }
9630   }
9631   return 0;
9632 }
9633
9634 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9635                                    Instruction *InsertPoint,
9636                                    InstCombiner *IC) {
9637   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9638   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9639   // We must cast correctly to the pointer type. Ensure that we
9640   // sign extend the integer value if it is smaller as this is
9641   // used for address computation.
9642   Instruction::CastOps opcode = 
9643      (VTySize < PtrSize ? Instruction::SExt :
9644       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9645   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9646 }
9647
9648
9649 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9650   Value *PtrOp = GEP.getOperand(0);
9651   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9652   // If so, eliminate the noop.
9653   if (GEP.getNumOperands() == 1)
9654     return ReplaceInstUsesWith(GEP, PtrOp);
9655
9656   if (isa<UndefValue>(GEP.getOperand(0)))
9657     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9658
9659   bool HasZeroPointerIndex = false;
9660   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9661     HasZeroPointerIndex = C->isNullValue();
9662
9663   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9664     return ReplaceInstUsesWith(GEP, PtrOp);
9665
9666   // Eliminate unneeded casts for indices.
9667   bool MadeChange = false;
9668   
9669   gep_type_iterator GTI = gep_type_begin(GEP);
9670   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9671        i != e; ++i, ++GTI) {
9672     if (isa<SequentialType>(*GTI)) {
9673       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9674         if (CI->getOpcode() == Instruction::ZExt ||
9675             CI->getOpcode() == Instruction::SExt) {
9676           const Type *SrcTy = CI->getOperand(0)->getType();
9677           // We can eliminate a cast from i32 to i64 iff the target 
9678           // is a 32-bit pointer target.
9679           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9680             MadeChange = true;
9681             *i = CI->getOperand(0);
9682           }
9683         }
9684       }
9685       // If we are using a wider index than needed for this platform, shrink it
9686       // to what we need.  If the incoming value needs a cast instruction,
9687       // insert it.  This explicit cast can make subsequent optimizations more
9688       // obvious.
9689       Value *Op = *i;
9690       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9691         if (Constant *C = dyn_cast<Constant>(Op)) {
9692           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9693           MadeChange = true;
9694         } else {
9695           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9696                                 GEP);
9697           *i = Op;
9698           MadeChange = true;
9699         }
9700       }
9701     }
9702   }
9703   if (MadeChange) return &GEP;
9704
9705   // If this GEP instruction doesn't move the pointer, and if the input operand
9706   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9707   // real input to the dest type.
9708   if (GEP.hasAllZeroIndices()) {
9709     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9710       // If the bitcast is of an allocation, and the allocation will be
9711       // converted to match the type of the cast, don't touch this.
9712       if (isa<AllocationInst>(BCI->getOperand(0))) {
9713         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9714         if (Instruction *I = visitBitCast(*BCI)) {
9715           if (I != BCI) {
9716             I->takeName(BCI);
9717             BCI->getParent()->getInstList().insert(BCI, I);
9718             ReplaceInstUsesWith(*BCI, I);
9719           }
9720           return &GEP;
9721         }
9722       }
9723       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9724     }
9725   }
9726   
9727   // Combine Indices - If the source pointer to this getelementptr instruction
9728   // is a getelementptr instruction, combine the indices of the two
9729   // getelementptr instructions into a single instruction.
9730   //
9731   SmallVector<Value*, 8> SrcGEPOperands;
9732   if (User *Src = dyn_castGetElementPtr(PtrOp))
9733     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9734
9735   if (!SrcGEPOperands.empty()) {
9736     // Note that if our source is a gep chain itself that we wait for that
9737     // chain to be resolved before we perform this transformation.  This
9738     // avoids us creating a TON of code in some cases.
9739     //
9740     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9741         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9742       return 0;   // Wait until our source is folded to completion.
9743
9744     SmallVector<Value*, 8> Indices;
9745
9746     // Find out whether the last index in the source GEP is a sequential idx.
9747     bool EndsWithSequential = false;
9748     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9749            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9750       EndsWithSequential = !isa<StructType>(*I);
9751
9752     // Can we combine the two pointer arithmetics offsets?
9753     if (EndsWithSequential) {
9754       // Replace: gep (gep %P, long B), long A, ...
9755       // With:    T = long A+B; gep %P, T, ...
9756       //
9757       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9758       if (SO1 == Constant::getNullValue(SO1->getType())) {
9759         Sum = GO1;
9760       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9761         Sum = SO1;
9762       } else {
9763         // If they aren't the same type, convert both to an integer of the
9764         // target's pointer size.
9765         if (SO1->getType() != GO1->getType()) {
9766           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9767             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9768           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9769             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9770           } else {
9771             unsigned PS = TD->getPointerSizeInBits();
9772             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9773               // Convert GO1 to SO1's type.
9774               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9775
9776             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9777               // Convert SO1 to GO1's type.
9778               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9779             } else {
9780               const Type *PT = TD->getIntPtrType();
9781               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9782               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9783             }
9784           }
9785         }
9786         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9787           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9788         else {
9789           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9790           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9791         }
9792       }
9793
9794       // Recycle the GEP we already have if possible.
9795       if (SrcGEPOperands.size() == 2) {
9796         GEP.setOperand(0, SrcGEPOperands[0]);
9797         GEP.setOperand(1, Sum);
9798         return &GEP;
9799       } else {
9800         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9801                        SrcGEPOperands.end()-1);
9802         Indices.push_back(Sum);
9803         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9804       }
9805     } else if (isa<Constant>(*GEP.idx_begin()) &&
9806                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9807                SrcGEPOperands.size() != 1) {
9808       // Otherwise we can do the fold if the first index of the GEP is a zero
9809       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9810                      SrcGEPOperands.end());
9811       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9812     }
9813
9814     if (!Indices.empty())
9815       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9816                                        Indices.end(), GEP.getName());
9817
9818   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9819     // GEP of global variable.  If all of the indices for this GEP are
9820     // constants, we can promote this to a constexpr instead of an instruction.
9821
9822     // Scan for nonconstants...
9823     SmallVector<Constant*, 8> Indices;
9824     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9825     for (; I != E && isa<Constant>(*I); ++I)
9826       Indices.push_back(cast<Constant>(*I));
9827
9828     if (I == E) {  // If they are all constants...
9829       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9830                                                     &Indices[0],Indices.size());
9831
9832       // Replace all uses of the GEP with the new constexpr...
9833       return ReplaceInstUsesWith(GEP, CE);
9834     }
9835   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9836     if (!isa<PointerType>(X->getType())) {
9837       // Not interesting.  Source pointer must be a cast from pointer.
9838     } else if (HasZeroPointerIndex) {
9839       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9840       // into     : GEP [10 x i8]* X, i32 0, ...
9841       //
9842       // This occurs when the program declares an array extern like "int X[];"
9843       //
9844       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9845       const PointerType *XTy = cast<PointerType>(X->getType());
9846       if (const ArrayType *XATy =
9847           dyn_cast<ArrayType>(XTy->getElementType()))
9848         if (const ArrayType *CATy =
9849             dyn_cast<ArrayType>(CPTy->getElementType()))
9850           if (CATy->getElementType() == XATy->getElementType()) {
9851             // At this point, we know that the cast source type is a pointer
9852             // to an array of the same type as the destination pointer
9853             // array.  Because the array type is never stepped over (there
9854             // is a leading zero) we can fold the cast into this GEP.
9855             GEP.setOperand(0, X);
9856             return &GEP;
9857           }
9858     } else if (GEP.getNumOperands() == 2) {
9859       // Transform things like:
9860       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9861       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9862       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9863       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9864       if (isa<ArrayType>(SrcElTy) &&
9865           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9866           TD->getABITypeSize(ResElTy)) {
9867         Value *Idx[2];
9868         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9869         Idx[1] = GEP.getOperand(1);
9870         Value *V = InsertNewInstBefore(
9871                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9872         // V and GEP are both pointer types --> BitCast
9873         return new BitCastInst(V, GEP.getType());
9874       }
9875       
9876       // Transform things like:
9877       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9878       //   (where tmp = 8*tmp2) into:
9879       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9880       
9881       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9882         uint64_t ArrayEltSize =
9883             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9884         
9885         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9886         // allow either a mul, shift, or constant here.
9887         Value *NewIdx = 0;
9888         ConstantInt *Scale = 0;
9889         if (ArrayEltSize == 1) {
9890           NewIdx = GEP.getOperand(1);
9891           Scale = ConstantInt::get(NewIdx->getType(), 1);
9892         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9893           NewIdx = ConstantInt::get(CI->getType(), 1);
9894           Scale = CI;
9895         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9896           if (Inst->getOpcode() == Instruction::Shl &&
9897               isa<ConstantInt>(Inst->getOperand(1))) {
9898             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9899             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9900             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9901             NewIdx = Inst->getOperand(0);
9902           } else if (Inst->getOpcode() == Instruction::Mul &&
9903                      isa<ConstantInt>(Inst->getOperand(1))) {
9904             Scale = cast<ConstantInt>(Inst->getOperand(1));
9905             NewIdx = Inst->getOperand(0);
9906           }
9907         }
9908         
9909         // If the index will be to exactly the right offset with the scale taken
9910         // out, perform the transformation. Note, we don't know whether Scale is
9911         // signed or not. We'll use unsigned version of division/modulo
9912         // operation after making sure Scale doesn't have the sign bit set.
9913         if (Scale && Scale->getSExtValue() >= 0LL &&
9914             Scale->getZExtValue() % ArrayEltSize == 0) {
9915           Scale = ConstantInt::get(Scale->getType(),
9916                                    Scale->getZExtValue() / ArrayEltSize);
9917           if (Scale->getZExtValue() != 1) {
9918             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9919                                                        false /*ZExt*/);
9920             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9921             NewIdx = InsertNewInstBefore(Sc, GEP);
9922           }
9923
9924           // Insert the new GEP instruction.
9925           Value *Idx[2];
9926           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9927           Idx[1] = NewIdx;
9928           Instruction *NewGEP =
9929             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9930           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9931           // The NewGEP must be pointer typed, so must the old one -> BitCast
9932           return new BitCastInst(NewGEP, GEP.getType());
9933         }
9934       }
9935     }
9936   }
9937
9938   return 0;
9939 }
9940
9941 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9942   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9943   if (AI.isArrayAllocation()) {  // Check C != 1
9944     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9945       const Type *NewTy = 
9946         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9947       AllocationInst *New = 0;
9948
9949       // Create and insert the replacement instruction...
9950       if (isa<MallocInst>(AI))
9951         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9952       else {
9953         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9954         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9955       }
9956
9957       InsertNewInstBefore(New, AI);
9958
9959       // Scan to the end of the allocation instructions, to skip over a block of
9960       // allocas if possible...
9961       //
9962       BasicBlock::iterator It = New;
9963       while (isa<AllocationInst>(*It)) ++It;
9964
9965       // Now that I is pointing to the first non-allocation-inst in the block,
9966       // insert our getelementptr instruction...
9967       //
9968       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9969       Value *Idx[2];
9970       Idx[0] = NullIdx;
9971       Idx[1] = NullIdx;
9972       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9973                                            New->getName()+".sub", It);
9974
9975       // Now make everything use the getelementptr instead of the original
9976       // allocation.
9977       return ReplaceInstUsesWith(AI, V);
9978     } else if (isa<UndefValue>(AI.getArraySize())) {
9979       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9980     }
9981   }
9982
9983   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9984   // Note that we only do this for alloca's, because malloc should allocate and
9985   // return a unique pointer, even for a zero byte allocation.
9986   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9987       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9988     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9989
9990   return 0;
9991 }
9992
9993 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9994   Value *Op = FI.getOperand(0);
9995
9996   // free undef -> unreachable.
9997   if (isa<UndefValue>(Op)) {
9998     // Insert a new store to null because we cannot modify the CFG here.
9999     new StoreInst(ConstantInt::getTrue(),
10000                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10001     return EraseInstFromFunction(FI);
10002   }
10003   
10004   // If we have 'free null' delete the instruction.  This can happen in stl code
10005   // when lots of inlining happens.
10006   if (isa<ConstantPointerNull>(Op))
10007     return EraseInstFromFunction(FI);
10008   
10009   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10010   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10011     FI.setOperand(0, CI->getOperand(0));
10012     return &FI;
10013   }
10014   
10015   // Change free (gep X, 0,0,0,0) into free(X)
10016   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10017     if (GEPI->hasAllZeroIndices()) {
10018       AddToWorkList(GEPI);
10019       FI.setOperand(0, GEPI->getOperand(0));
10020       return &FI;
10021     }
10022   }
10023   
10024   // Change free(malloc) into nothing, if the malloc has a single use.
10025   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10026     if (MI->hasOneUse()) {
10027       EraseInstFromFunction(FI);
10028       return EraseInstFromFunction(*MI);
10029     }
10030
10031   return 0;
10032 }
10033
10034
10035 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10036 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10037                                         const TargetData *TD) {
10038   User *CI = cast<User>(LI.getOperand(0));
10039   Value *CastOp = CI->getOperand(0);
10040
10041   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10042     // Instead of loading constant c string, use corresponding integer value
10043     // directly if string length is small enough.
10044     std::string Str;
10045     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10046       unsigned len = Str.length();
10047       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10048       unsigned numBits = Ty->getPrimitiveSizeInBits();
10049       // Replace LI with immediate integer store.
10050       if ((numBits >> 3) == len + 1) {
10051         APInt StrVal(numBits, 0);
10052         APInt SingleChar(numBits, 0);
10053         if (TD->isLittleEndian()) {
10054           for (signed i = len-1; i >= 0; i--) {
10055             SingleChar = (uint64_t) Str[i];
10056             StrVal = (StrVal << 8) | SingleChar;
10057           }
10058         } else {
10059           for (unsigned i = 0; i < len; i++) {
10060             SingleChar = (uint64_t) Str[i];
10061             StrVal = (StrVal << 8) | SingleChar;
10062           }
10063           // Append NULL at the end.
10064           SingleChar = 0;
10065           StrVal = (StrVal << 8) | SingleChar;
10066         }
10067         Value *NL = ConstantInt::get(StrVal);
10068         return IC.ReplaceInstUsesWith(LI, NL);
10069       }
10070     }
10071   }
10072
10073   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10074   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10075     const Type *SrcPTy = SrcTy->getElementType();
10076
10077     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10078          isa<VectorType>(DestPTy)) {
10079       // If the source is an array, the code below will not succeed.  Check to
10080       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10081       // constants.
10082       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10083         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10084           if (ASrcTy->getNumElements() != 0) {
10085             Value *Idxs[2];
10086             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10087             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10088             SrcTy = cast<PointerType>(CastOp->getType());
10089             SrcPTy = SrcTy->getElementType();
10090           }
10091
10092       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10093             isa<VectorType>(SrcPTy)) &&
10094           // Do not allow turning this into a load of an integer, which is then
10095           // casted to a pointer, this pessimizes pointer analysis a lot.
10096           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10097           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10098                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10099
10100         // Okay, we are casting from one integer or pointer type to another of
10101         // the same size.  Instead of casting the pointer before the load, cast
10102         // the result of the loaded value.
10103         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10104                                                              CI->getName(),
10105                                                          LI.isVolatile()),LI);
10106         // Now cast the result of the load.
10107         return new BitCastInst(NewLoad, LI.getType());
10108       }
10109     }
10110   }
10111   return 0;
10112 }
10113
10114 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10115 /// from this value cannot trap.  If it is not obviously safe to load from the
10116 /// specified pointer, we do a quick local scan of the basic block containing
10117 /// ScanFrom, to determine if the address is already accessed.
10118 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10119   // If it is an alloca it is always safe to load from.
10120   if (isa<AllocaInst>(V)) return true;
10121
10122   // If it is a global variable it is mostly safe to load from.
10123   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10124     // Don't try to evaluate aliases.  External weak GV can be null.
10125     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10126
10127   // Otherwise, be a little bit agressive by scanning the local block where we
10128   // want to check to see if the pointer is already being loaded or stored
10129   // from/to.  If so, the previous load or store would have already trapped,
10130   // so there is no harm doing an extra load (also, CSE will later eliminate
10131   // the load entirely).
10132   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10133
10134   while (BBI != E) {
10135     --BBI;
10136
10137     // If we see a free or a call (which might do a free) the pointer could be
10138     // marked invalid.
10139     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10140       return false;
10141     
10142     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10143       if (LI->getOperand(0) == V) return true;
10144     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10145       if (SI->getOperand(1) == V) return true;
10146     }
10147
10148   }
10149   return false;
10150 }
10151
10152 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10153 /// until we find the underlying object a pointer is referring to or something
10154 /// we don't understand.  Note that the returned pointer may be offset from the
10155 /// input, because we ignore GEP indices.
10156 static Value *GetUnderlyingObject(Value *Ptr) {
10157   while (1) {
10158     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10159       if (CE->getOpcode() == Instruction::BitCast ||
10160           CE->getOpcode() == Instruction::GetElementPtr)
10161         Ptr = CE->getOperand(0);
10162       else
10163         return Ptr;
10164     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10165       Ptr = BCI->getOperand(0);
10166     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10167       Ptr = GEP->getOperand(0);
10168     } else {
10169       return Ptr;
10170     }
10171   }
10172 }
10173
10174 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10175   Value *Op = LI.getOperand(0);
10176
10177   // Attempt to improve the alignment.
10178   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10179   if (KnownAlign >
10180       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10181                                 LI.getAlignment()))
10182     LI.setAlignment(KnownAlign);
10183
10184   // load (cast X) --> cast (load X) iff safe
10185   if (isa<CastInst>(Op))
10186     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10187       return Res;
10188
10189   // None of the following transforms are legal for volatile loads.
10190   if (LI.isVolatile()) return 0;
10191   
10192   if (&LI.getParent()->front() != &LI) {
10193     BasicBlock::iterator BBI = &LI; --BBI;
10194     // If the instruction immediately before this is a store to the same
10195     // address, do a simple form of store->load forwarding.
10196     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10197       if (SI->getOperand(1) == LI.getOperand(0))
10198         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10199     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10200       if (LIB->getOperand(0) == LI.getOperand(0))
10201         return ReplaceInstUsesWith(LI, LIB);
10202   }
10203
10204   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10205     const Value *GEPI0 = GEPI->getOperand(0);
10206     // TODO: Consider a target hook for valid address spaces for this xform.
10207     if (isa<ConstantPointerNull>(GEPI0) &&
10208         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10209       // Insert a new store to null instruction before the load to indicate
10210       // that this code is not reachable.  We do this instead of inserting
10211       // an unreachable instruction directly because we cannot modify the
10212       // CFG.
10213       new StoreInst(UndefValue::get(LI.getType()),
10214                     Constant::getNullValue(Op->getType()), &LI);
10215       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10216     }
10217   } 
10218
10219   if (Constant *C = dyn_cast<Constant>(Op)) {
10220     // load null/undef -> undef
10221     // TODO: Consider a target hook for valid address spaces for this xform.
10222     if (isa<UndefValue>(C) || (C->isNullValue() && 
10223         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10224       // Insert a new store to null instruction before the load to indicate that
10225       // this code is not reachable.  We do this instead of inserting an
10226       // unreachable instruction directly because we cannot modify the CFG.
10227       new StoreInst(UndefValue::get(LI.getType()),
10228                     Constant::getNullValue(Op->getType()), &LI);
10229       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10230     }
10231
10232     // Instcombine load (constant global) into the value loaded.
10233     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10234       if (GV->isConstant() && !GV->isDeclaration())
10235         return ReplaceInstUsesWith(LI, GV->getInitializer());
10236
10237     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10238     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10239       if (CE->getOpcode() == Instruction::GetElementPtr) {
10240         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10241           if (GV->isConstant() && !GV->isDeclaration())
10242             if (Constant *V = 
10243                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10244               return ReplaceInstUsesWith(LI, V);
10245         if (CE->getOperand(0)->isNullValue()) {
10246           // Insert a new store to null instruction before the load to indicate
10247           // that this code is not reachable.  We do this instead of inserting
10248           // an unreachable instruction directly because we cannot modify the
10249           // CFG.
10250           new StoreInst(UndefValue::get(LI.getType()),
10251                         Constant::getNullValue(Op->getType()), &LI);
10252           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10253         }
10254
10255       } else if (CE->isCast()) {
10256         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10257           return Res;
10258       }
10259     }
10260   }
10261     
10262   // If this load comes from anywhere in a constant global, and if the global
10263   // is all undef or zero, we know what it loads.
10264   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10265     if (GV->isConstant() && GV->hasInitializer()) {
10266       if (GV->getInitializer()->isNullValue())
10267         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10268       else if (isa<UndefValue>(GV->getInitializer()))
10269         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10270     }
10271   }
10272
10273   if (Op->hasOneUse()) {
10274     // Change select and PHI nodes to select values instead of addresses: this
10275     // helps alias analysis out a lot, allows many others simplifications, and
10276     // exposes redundancy in the code.
10277     //
10278     // Note that we cannot do the transformation unless we know that the
10279     // introduced loads cannot trap!  Something like this is valid as long as
10280     // the condition is always false: load (select bool %C, int* null, int* %G),
10281     // but it would not be valid if we transformed it to load from null
10282     // unconditionally.
10283     //
10284     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10285       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10286       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10287           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10288         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10289                                      SI->getOperand(1)->getName()+".val"), LI);
10290         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10291                                      SI->getOperand(2)->getName()+".val"), LI);
10292         return SelectInst::Create(SI->getCondition(), V1, V2);
10293       }
10294
10295       // load (select (cond, null, P)) -> load P
10296       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10297         if (C->isNullValue()) {
10298           LI.setOperand(0, SI->getOperand(2));
10299           return &LI;
10300         }
10301
10302       // load (select (cond, P, null)) -> load P
10303       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10304         if (C->isNullValue()) {
10305           LI.setOperand(0, SI->getOperand(1));
10306           return &LI;
10307         }
10308     }
10309   }
10310   return 0;
10311 }
10312
10313 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10314 /// when possible.
10315 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10316   User *CI = cast<User>(SI.getOperand(1));
10317   Value *CastOp = CI->getOperand(0);
10318
10319   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10320   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10321     const Type *SrcPTy = SrcTy->getElementType();
10322
10323     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10324       // If the source is an array, the code below will not succeed.  Check to
10325       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10326       // constants.
10327       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10328         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10329           if (ASrcTy->getNumElements() != 0) {
10330             Value* Idxs[2];
10331             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10332             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10333             SrcTy = cast<PointerType>(CastOp->getType());
10334             SrcPTy = SrcTy->getElementType();
10335           }
10336
10337       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10338           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10339                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10340
10341         // Okay, we are casting from one integer or pointer type to another of
10342         // the same size.  Instead of casting the pointer before 
10343         // the store, cast the value to be stored.
10344         Value *NewCast;
10345         Value *SIOp0 = SI.getOperand(0);
10346         Instruction::CastOps opcode = Instruction::BitCast;
10347         const Type* CastSrcTy = SIOp0->getType();
10348         const Type* CastDstTy = SrcPTy;
10349         if (isa<PointerType>(CastDstTy)) {
10350           if (CastSrcTy->isInteger())
10351             opcode = Instruction::IntToPtr;
10352         } else if (isa<IntegerType>(CastDstTy)) {
10353           if (isa<PointerType>(SIOp0->getType()))
10354             opcode = Instruction::PtrToInt;
10355         }
10356         if (Constant *C = dyn_cast<Constant>(SIOp0))
10357           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10358         else
10359           NewCast = IC.InsertNewInstBefore(
10360             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10361             SI);
10362         return new StoreInst(NewCast, CastOp);
10363       }
10364     }
10365   }
10366   return 0;
10367 }
10368
10369 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10370   Value *Val = SI.getOperand(0);
10371   Value *Ptr = SI.getOperand(1);
10372
10373   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10374     EraseInstFromFunction(SI);
10375     ++NumCombined;
10376     return 0;
10377   }
10378   
10379   // If the RHS is an alloca with a single use, zapify the store, making the
10380   // alloca dead.
10381   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10382     if (isa<AllocaInst>(Ptr)) {
10383       EraseInstFromFunction(SI);
10384       ++NumCombined;
10385       return 0;
10386     }
10387     
10388     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10389       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10390           GEP->getOperand(0)->hasOneUse()) {
10391         EraseInstFromFunction(SI);
10392         ++NumCombined;
10393         return 0;
10394       }
10395   }
10396
10397   // Attempt to improve the alignment.
10398   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10399   if (KnownAlign >
10400       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10401                                 SI.getAlignment()))
10402     SI.setAlignment(KnownAlign);
10403
10404   // Do really simple DSE, to catch cases where there are several consequtive
10405   // stores to the same location, separated by a few arithmetic operations. This
10406   // situation often occurs with bitfield accesses.
10407   BasicBlock::iterator BBI = &SI;
10408   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10409        --ScanInsts) {
10410     --BBI;
10411     
10412     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10413       // Prev store isn't volatile, and stores to the same location?
10414       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10415         ++NumDeadStore;
10416         ++BBI;
10417         EraseInstFromFunction(*PrevSI);
10418         continue;
10419       }
10420       break;
10421     }
10422     
10423     // If this is a load, we have to stop.  However, if the loaded value is from
10424     // the pointer we're loading and is producing the pointer we're storing,
10425     // then *this* store is dead (X = load P; store X -> P).
10426     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10427       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10428         EraseInstFromFunction(SI);
10429         ++NumCombined;
10430         return 0;
10431       }
10432       // Otherwise, this is a load from some other location.  Stores before it
10433       // may not be dead.
10434       break;
10435     }
10436     
10437     // Don't skip over loads or things that can modify memory.
10438     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10439       break;
10440   }
10441   
10442   
10443   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10444
10445   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10446   if (isa<ConstantPointerNull>(Ptr)) {
10447     if (!isa<UndefValue>(Val)) {
10448       SI.setOperand(0, UndefValue::get(Val->getType()));
10449       if (Instruction *U = dyn_cast<Instruction>(Val))
10450         AddToWorkList(U);  // Dropped a use.
10451       ++NumCombined;
10452     }
10453     return 0;  // Do not modify these!
10454   }
10455
10456   // store undef, Ptr -> noop
10457   if (isa<UndefValue>(Val)) {
10458     EraseInstFromFunction(SI);
10459     ++NumCombined;
10460     return 0;
10461   }
10462
10463   // If the pointer destination is a cast, see if we can fold the cast into the
10464   // source instead.
10465   if (isa<CastInst>(Ptr))
10466     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10467       return Res;
10468   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10469     if (CE->isCast())
10470       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10471         return Res;
10472
10473   
10474   // If this store is the last instruction in the basic block, and if the block
10475   // ends with an unconditional branch, try to move it to the successor block.
10476   BBI = &SI; ++BBI;
10477   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10478     if (BI->isUnconditional())
10479       if (SimplifyStoreAtEndOfBlock(SI))
10480         return 0;  // xform done!
10481   
10482   return 0;
10483 }
10484
10485 /// SimplifyStoreAtEndOfBlock - Turn things like:
10486 ///   if () { *P = v1; } else { *P = v2 }
10487 /// into a phi node with a store in the successor.
10488 ///
10489 /// Simplify things like:
10490 ///   *P = v1; if () { *P = v2; }
10491 /// into a phi node with a store in the successor.
10492 ///
10493 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10494   BasicBlock *StoreBB = SI.getParent();
10495   
10496   // Check to see if the successor block has exactly two incoming edges.  If
10497   // so, see if the other predecessor contains a store to the same location.
10498   // if so, insert a PHI node (if needed) and move the stores down.
10499   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10500   
10501   // Determine whether Dest has exactly two predecessors and, if so, compute
10502   // the other predecessor.
10503   pred_iterator PI = pred_begin(DestBB);
10504   BasicBlock *OtherBB = 0;
10505   if (*PI != StoreBB)
10506     OtherBB = *PI;
10507   ++PI;
10508   if (PI == pred_end(DestBB))
10509     return false;
10510   
10511   if (*PI != StoreBB) {
10512     if (OtherBB)
10513       return false;
10514     OtherBB = *PI;
10515   }
10516   if (++PI != pred_end(DestBB))
10517     return false;
10518
10519   // Bail out if all the relevant blocks aren't distinct (this can happen,
10520   // for example, if SI is in an infinite loop)
10521   if (StoreBB == DestBB || OtherBB == DestBB)
10522     return false;
10523
10524   // Verify that the other block ends in a branch and is not otherwise empty.
10525   BasicBlock::iterator BBI = OtherBB->getTerminator();
10526   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10527   if (!OtherBr || BBI == OtherBB->begin())
10528     return false;
10529   
10530   // If the other block ends in an unconditional branch, check for the 'if then
10531   // else' case.  there is an instruction before the branch.
10532   StoreInst *OtherStore = 0;
10533   if (OtherBr->isUnconditional()) {
10534     // If this isn't a store, or isn't a store to the same location, bail out.
10535     --BBI;
10536     OtherStore = dyn_cast<StoreInst>(BBI);
10537     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10538       return false;
10539   } else {
10540     // Otherwise, the other block ended with a conditional branch. If one of the
10541     // destinations is StoreBB, then we have the if/then case.
10542     if (OtherBr->getSuccessor(0) != StoreBB && 
10543         OtherBr->getSuccessor(1) != StoreBB)
10544       return false;
10545     
10546     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10547     // if/then triangle.  See if there is a store to the same ptr as SI that
10548     // lives in OtherBB.
10549     for (;; --BBI) {
10550       // Check to see if we find the matching store.
10551       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10552         if (OtherStore->getOperand(1) != SI.getOperand(1))
10553           return false;
10554         break;
10555       }
10556       // If we find something that may be using or overwriting the stored
10557       // value, or if we run out of instructions, we can't do the xform.
10558       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10559           BBI == OtherBB->begin())
10560         return false;
10561     }
10562     
10563     // In order to eliminate the store in OtherBr, we have to
10564     // make sure nothing reads or overwrites the stored value in
10565     // StoreBB.
10566     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10567       // FIXME: This should really be AA driven.
10568       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10569         return false;
10570     }
10571   }
10572   
10573   // Insert a PHI node now if we need it.
10574   Value *MergedVal = OtherStore->getOperand(0);
10575   if (MergedVal != SI.getOperand(0)) {
10576     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10577     PN->reserveOperandSpace(2);
10578     PN->addIncoming(SI.getOperand(0), SI.getParent());
10579     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10580     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10581   }
10582   
10583   // Advance to a place where it is safe to insert the new store and
10584   // insert it.
10585   BBI = DestBB->getFirstNonPHI();
10586   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10587                                     OtherStore->isVolatile()), *BBI);
10588   
10589   // Nuke the old stores.
10590   EraseInstFromFunction(SI);
10591   EraseInstFromFunction(*OtherStore);
10592   ++NumCombined;
10593   return true;
10594 }
10595
10596
10597 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10598   // Change br (not X), label True, label False to: br X, label False, True
10599   Value *X = 0;
10600   BasicBlock *TrueDest;
10601   BasicBlock *FalseDest;
10602   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10603       !isa<Constant>(X)) {
10604     // Swap Destinations and condition...
10605     BI.setCondition(X);
10606     BI.setSuccessor(0, FalseDest);
10607     BI.setSuccessor(1, TrueDest);
10608     return &BI;
10609   }
10610
10611   // Cannonicalize fcmp_one -> fcmp_oeq
10612   FCmpInst::Predicate FPred; Value *Y;
10613   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10614                              TrueDest, FalseDest)))
10615     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10616          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10617       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10618       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10619       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10620       NewSCC->takeName(I);
10621       // Swap Destinations and condition...
10622       BI.setCondition(NewSCC);
10623       BI.setSuccessor(0, FalseDest);
10624       BI.setSuccessor(1, TrueDest);
10625       RemoveFromWorkList(I);
10626       I->eraseFromParent();
10627       AddToWorkList(NewSCC);
10628       return &BI;
10629     }
10630
10631   // Cannonicalize icmp_ne -> icmp_eq
10632   ICmpInst::Predicate IPred;
10633   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10634                       TrueDest, FalseDest)))
10635     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10636          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10637          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10638       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10639       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10640       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10641       NewSCC->takeName(I);
10642       // Swap Destinations and condition...
10643       BI.setCondition(NewSCC);
10644       BI.setSuccessor(0, FalseDest);
10645       BI.setSuccessor(1, TrueDest);
10646       RemoveFromWorkList(I);
10647       I->eraseFromParent();;
10648       AddToWorkList(NewSCC);
10649       return &BI;
10650     }
10651
10652   return 0;
10653 }
10654
10655 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10656   Value *Cond = SI.getCondition();
10657   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10658     if (I->getOpcode() == Instruction::Add)
10659       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10660         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10661         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10662           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10663                                                 AddRHS));
10664         SI.setOperand(0, I->getOperand(0));
10665         AddToWorkList(I);
10666         return &SI;
10667       }
10668   }
10669   return 0;
10670 }
10671
10672 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10673   // See if we are trying to extract a known value. If so, use that instead.
10674   if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10675                                      EV.idx_end(), &EV))
10676     return ReplaceInstUsesWith(EV, Elt);
10677
10678   // No changes
10679   return 0;
10680 }
10681
10682 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10683 /// is to leave as a vector operation.
10684 static bool CheapToScalarize(Value *V, bool isConstant) {
10685   if (isa<ConstantAggregateZero>(V)) 
10686     return true;
10687   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10688     if (isConstant) return true;
10689     // If all elts are the same, we can extract.
10690     Constant *Op0 = C->getOperand(0);
10691     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10692       if (C->getOperand(i) != Op0)
10693         return false;
10694     return true;
10695   }
10696   Instruction *I = dyn_cast<Instruction>(V);
10697   if (!I) return false;
10698   
10699   // Insert element gets simplified to the inserted element or is deleted if
10700   // this is constant idx extract element and its a constant idx insertelt.
10701   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10702       isa<ConstantInt>(I->getOperand(2)))
10703     return true;
10704   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10705     return true;
10706   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10707     if (BO->hasOneUse() &&
10708         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10709          CheapToScalarize(BO->getOperand(1), isConstant)))
10710       return true;
10711   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10712     if (CI->hasOneUse() &&
10713         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10714          CheapToScalarize(CI->getOperand(1), isConstant)))
10715       return true;
10716   
10717   return false;
10718 }
10719
10720 /// Read and decode a shufflevector mask.
10721 ///
10722 /// It turns undef elements into values that are larger than the number of
10723 /// elements in the input.
10724 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10725   unsigned NElts = SVI->getType()->getNumElements();
10726   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10727     return std::vector<unsigned>(NElts, 0);
10728   if (isa<UndefValue>(SVI->getOperand(2)))
10729     return std::vector<unsigned>(NElts, 2*NElts);
10730
10731   std::vector<unsigned> Result;
10732   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10733   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10734     if (isa<UndefValue>(*i))
10735       Result.push_back(NElts*2);  // undef -> 8
10736     else
10737       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10738   return Result;
10739 }
10740
10741 /// FindScalarElement - Given a vector and an element number, see if the scalar
10742 /// value is already around as a register, for example if it were inserted then
10743 /// extracted from the vector.
10744 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10745   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10746   const VectorType *PTy = cast<VectorType>(V->getType());
10747   unsigned Width = PTy->getNumElements();
10748   if (EltNo >= Width)  // Out of range access.
10749     return UndefValue::get(PTy->getElementType());
10750   
10751   if (isa<UndefValue>(V))
10752     return UndefValue::get(PTy->getElementType());
10753   else if (isa<ConstantAggregateZero>(V))
10754     return Constant::getNullValue(PTy->getElementType());
10755   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10756     return CP->getOperand(EltNo);
10757   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10758     // If this is an insert to a variable element, we don't know what it is.
10759     if (!isa<ConstantInt>(III->getOperand(2))) 
10760       return 0;
10761     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10762     
10763     // If this is an insert to the element we are looking for, return the
10764     // inserted value.
10765     if (EltNo == IIElt) 
10766       return III->getOperand(1);
10767     
10768     // Otherwise, the insertelement doesn't modify the value, recurse on its
10769     // vector input.
10770     return FindScalarElement(III->getOperand(0), EltNo);
10771   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10772     unsigned InEl = getShuffleMask(SVI)[EltNo];
10773     if (InEl < Width)
10774       return FindScalarElement(SVI->getOperand(0), InEl);
10775     else if (InEl < Width*2)
10776       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10777     else
10778       return UndefValue::get(PTy->getElementType());
10779   }
10780   
10781   // Otherwise, we don't know.
10782   return 0;
10783 }
10784
10785 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10786   // If vector val is undef, replace extract with scalar undef.
10787   if (isa<UndefValue>(EI.getOperand(0)))
10788     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10789
10790   // If vector val is constant 0, replace extract with scalar 0.
10791   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10792     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10793   
10794   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10795     // If vector val is constant with all elements the same, replace EI with
10796     // that element. When the elements are not identical, we cannot replace yet
10797     // (we do that below, but only when the index is constant).
10798     Constant *op0 = C->getOperand(0);
10799     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10800       if (C->getOperand(i) != op0) {
10801         op0 = 0; 
10802         break;
10803       }
10804     if (op0)
10805       return ReplaceInstUsesWith(EI, op0);
10806   }
10807   
10808   // If extracting a specified index from the vector, see if we can recursively
10809   // find a previously computed scalar that was inserted into the vector.
10810   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10811     unsigned IndexVal = IdxC->getZExtValue();
10812     unsigned VectorWidth = 
10813       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10814       
10815     // If this is extracting an invalid index, turn this into undef, to avoid
10816     // crashing the code below.
10817     if (IndexVal >= VectorWidth)
10818       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10819     
10820     // This instruction only demands the single element from the input vector.
10821     // If the input vector has a single use, simplify it based on this use
10822     // property.
10823     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10824       uint64_t UndefElts;
10825       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10826                                                 1 << IndexVal,
10827                                                 UndefElts)) {
10828         EI.setOperand(0, V);
10829         return &EI;
10830       }
10831     }
10832     
10833     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10834       return ReplaceInstUsesWith(EI, Elt);
10835     
10836     // If the this extractelement is directly using a bitcast from a vector of
10837     // the same number of elements, see if we can find the source element from
10838     // it.  In this case, we will end up needing to bitcast the scalars.
10839     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10840       if (const VectorType *VT = 
10841               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10842         if (VT->getNumElements() == VectorWidth)
10843           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10844             return new BitCastInst(Elt, EI.getType());
10845     }
10846   }
10847   
10848   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10849     if (I->hasOneUse()) {
10850       // Push extractelement into predecessor operation if legal and
10851       // profitable to do so
10852       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10853         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10854         if (CheapToScalarize(BO, isConstantElt)) {
10855           ExtractElementInst *newEI0 = 
10856             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10857                                    EI.getName()+".lhs");
10858           ExtractElementInst *newEI1 =
10859             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10860                                    EI.getName()+".rhs");
10861           InsertNewInstBefore(newEI0, EI);
10862           InsertNewInstBefore(newEI1, EI);
10863           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10864         }
10865       } else if (isa<LoadInst>(I)) {
10866         unsigned AS = 
10867           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10868         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10869                                          PointerType::get(EI.getType(), AS),EI);
10870         GetElementPtrInst *GEP =
10871           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10872         InsertNewInstBefore(GEP, EI);
10873         return new LoadInst(GEP);
10874       }
10875     }
10876     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10877       // Extracting the inserted element?
10878       if (IE->getOperand(2) == EI.getOperand(1))
10879         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10880       // If the inserted and extracted elements are constants, they must not
10881       // be the same value, extract from the pre-inserted value instead.
10882       if (isa<Constant>(IE->getOperand(2)) &&
10883           isa<Constant>(EI.getOperand(1))) {
10884         AddUsesToWorkList(EI);
10885         EI.setOperand(0, IE->getOperand(0));
10886         return &EI;
10887       }
10888     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10889       // If this is extracting an element from a shufflevector, figure out where
10890       // it came from and extract from the appropriate input element instead.
10891       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10892         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10893         Value *Src;
10894         if (SrcIdx < SVI->getType()->getNumElements())
10895           Src = SVI->getOperand(0);
10896         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10897           SrcIdx -= SVI->getType()->getNumElements();
10898           Src = SVI->getOperand(1);
10899         } else {
10900           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10901         }
10902         return new ExtractElementInst(Src, SrcIdx);
10903       }
10904     }
10905   }
10906   return 0;
10907 }
10908
10909 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10910 /// elements from either LHS or RHS, return the shuffle mask and true. 
10911 /// Otherwise, return false.
10912 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10913                                          std::vector<Constant*> &Mask) {
10914   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10915          "Invalid CollectSingleShuffleElements");
10916   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10917
10918   if (isa<UndefValue>(V)) {
10919     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10920     return true;
10921   } else if (V == LHS) {
10922     for (unsigned i = 0; i != NumElts; ++i)
10923       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10924     return true;
10925   } else if (V == RHS) {
10926     for (unsigned i = 0; i != NumElts; ++i)
10927       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10928     return true;
10929   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10930     // If this is an insert of an extract from some other vector, include it.
10931     Value *VecOp    = IEI->getOperand(0);
10932     Value *ScalarOp = IEI->getOperand(1);
10933     Value *IdxOp    = IEI->getOperand(2);
10934     
10935     if (!isa<ConstantInt>(IdxOp))
10936       return false;
10937     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10938     
10939     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10940       // Okay, we can handle this if the vector we are insertinting into is
10941       // transitively ok.
10942       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10943         // If so, update the mask to reflect the inserted undef.
10944         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10945         return true;
10946       }      
10947     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10948       if (isa<ConstantInt>(EI->getOperand(1)) &&
10949           EI->getOperand(0)->getType() == V->getType()) {
10950         unsigned ExtractedIdx =
10951           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10952         
10953         // This must be extracting from either LHS or RHS.
10954         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10955           // Okay, we can handle this if the vector we are insertinting into is
10956           // transitively ok.
10957           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10958             // If so, update the mask to reflect the inserted value.
10959             if (EI->getOperand(0) == LHS) {
10960               Mask[InsertedIdx & (NumElts-1)] = 
10961                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10962             } else {
10963               assert(EI->getOperand(0) == RHS);
10964               Mask[InsertedIdx & (NumElts-1)] = 
10965                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10966               
10967             }
10968             return true;
10969           }
10970         }
10971       }
10972     }
10973   }
10974   // TODO: Handle shufflevector here!
10975   
10976   return false;
10977 }
10978
10979 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10980 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10981 /// that computes V and the LHS value of the shuffle.
10982 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10983                                      Value *&RHS) {
10984   assert(isa<VectorType>(V->getType()) && 
10985          (RHS == 0 || V->getType() == RHS->getType()) &&
10986          "Invalid shuffle!");
10987   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10988
10989   if (isa<UndefValue>(V)) {
10990     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10991     return V;
10992   } else if (isa<ConstantAggregateZero>(V)) {
10993     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10994     return V;
10995   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10996     // If this is an insert of an extract from some other vector, include it.
10997     Value *VecOp    = IEI->getOperand(0);
10998     Value *ScalarOp = IEI->getOperand(1);
10999     Value *IdxOp    = IEI->getOperand(2);
11000     
11001     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11002       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11003           EI->getOperand(0)->getType() == V->getType()) {
11004         unsigned ExtractedIdx =
11005           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11006         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11007         
11008         // Either the extracted from or inserted into vector must be RHSVec,
11009         // otherwise we'd end up with a shuffle of three inputs.
11010         if (EI->getOperand(0) == RHS || RHS == 0) {
11011           RHS = EI->getOperand(0);
11012           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11013           Mask[InsertedIdx & (NumElts-1)] = 
11014             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11015           return V;
11016         }
11017         
11018         if (VecOp == RHS) {
11019           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11020           // Everything but the extracted element is replaced with the RHS.
11021           for (unsigned i = 0; i != NumElts; ++i) {
11022             if (i != InsertedIdx)
11023               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11024           }
11025           return V;
11026         }
11027         
11028         // If this insertelement is a chain that comes from exactly these two
11029         // vectors, return the vector and the effective shuffle.
11030         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11031           return EI->getOperand(0);
11032         
11033       }
11034     }
11035   }
11036   // TODO: Handle shufflevector here!
11037   
11038   // Otherwise, can't do anything fancy.  Return an identity vector.
11039   for (unsigned i = 0; i != NumElts; ++i)
11040     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11041   return V;
11042 }
11043
11044 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11045   Value *VecOp    = IE.getOperand(0);
11046   Value *ScalarOp = IE.getOperand(1);
11047   Value *IdxOp    = IE.getOperand(2);
11048   
11049   // Inserting an undef or into an undefined place, remove this.
11050   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11051     ReplaceInstUsesWith(IE, VecOp);
11052   
11053   // If the inserted element was extracted from some other vector, and if the 
11054   // indexes are constant, try to turn this into a shufflevector operation.
11055   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11056     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11057         EI->getOperand(0)->getType() == IE.getType()) {
11058       unsigned NumVectorElts = IE.getType()->getNumElements();
11059       unsigned ExtractedIdx =
11060         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11061       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11062       
11063       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11064         return ReplaceInstUsesWith(IE, VecOp);
11065       
11066       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11067         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11068       
11069       // If we are extracting a value from a vector, then inserting it right
11070       // back into the same place, just use the input vector.
11071       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11072         return ReplaceInstUsesWith(IE, VecOp);      
11073       
11074       // We could theoretically do this for ANY input.  However, doing so could
11075       // turn chains of insertelement instructions into a chain of shufflevector
11076       // instructions, and right now we do not merge shufflevectors.  As such,
11077       // only do this in a situation where it is clear that there is benefit.
11078       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11079         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11080         // the values of VecOp, except then one read from EIOp0.
11081         // Build a new shuffle mask.
11082         std::vector<Constant*> Mask;
11083         if (isa<UndefValue>(VecOp))
11084           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11085         else {
11086           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11087           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11088                                                        NumVectorElts));
11089         } 
11090         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11091         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11092                                      ConstantVector::get(Mask));
11093       }
11094       
11095       // If this insertelement isn't used by some other insertelement, turn it
11096       // (and any insertelements it points to), into one big shuffle.
11097       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11098         std::vector<Constant*> Mask;
11099         Value *RHS = 0;
11100         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11101         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11102         // We now have a shuffle of LHS, RHS, Mask.
11103         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11104       }
11105     }
11106   }
11107
11108   return 0;
11109 }
11110
11111
11112 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11113   Value *LHS = SVI.getOperand(0);
11114   Value *RHS = SVI.getOperand(1);
11115   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11116
11117   bool MadeChange = false;
11118   
11119   // Undefined shuffle mask -> undefined value.
11120   if (isa<UndefValue>(SVI.getOperand(2)))
11121     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11122   
11123   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11124   // the undef, change them to undefs.
11125   if (isa<UndefValue>(SVI.getOperand(1))) {
11126     // Scan to see if there are any references to the RHS.  If so, replace them
11127     // with undef element refs and set MadeChange to true.
11128     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11129       if (Mask[i] >= e && Mask[i] != 2*e) {
11130         Mask[i] = 2*e;
11131         MadeChange = true;
11132       }
11133     }
11134     
11135     if (MadeChange) {
11136       // Remap any references to RHS to use LHS.
11137       std::vector<Constant*> Elts;
11138       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11139         if (Mask[i] == 2*e)
11140           Elts.push_back(UndefValue::get(Type::Int32Ty));
11141         else
11142           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11143       }
11144       SVI.setOperand(2, ConstantVector::get(Elts));
11145     }
11146   }
11147   
11148   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11149   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11150   if (LHS == RHS || isa<UndefValue>(LHS)) {
11151     if (isa<UndefValue>(LHS) && LHS == RHS) {
11152       // shuffle(undef,undef,mask) -> undef.
11153       return ReplaceInstUsesWith(SVI, LHS);
11154     }
11155     
11156     // Remap any references to RHS to use LHS.
11157     std::vector<Constant*> Elts;
11158     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11159       if (Mask[i] >= 2*e)
11160         Elts.push_back(UndefValue::get(Type::Int32Ty));
11161       else {
11162         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11163             (Mask[i] <  e && isa<UndefValue>(LHS)))
11164           Mask[i] = 2*e;     // Turn into undef.
11165         else
11166           Mask[i] &= (e-1);  // Force to LHS.
11167         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11168       }
11169     }
11170     SVI.setOperand(0, SVI.getOperand(1));
11171     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11172     SVI.setOperand(2, ConstantVector::get(Elts));
11173     LHS = SVI.getOperand(0);
11174     RHS = SVI.getOperand(1);
11175     MadeChange = true;
11176   }
11177   
11178   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11179   bool isLHSID = true, isRHSID = true;
11180     
11181   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11182     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11183     // Is this an identity shuffle of the LHS value?
11184     isLHSID &= (Mask[i] == i);
11185       
11186     // Is this an identity shuffle of the RHS value?
11187     isRHSID &= (Mask[i]-e == i);
11188   }
11189
11190   // Eliminate identity shuffles.
11191   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11192   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11193   
11194   // If the LHS is a shufflevector itself, see if we can combine it with this
11195   // one without producing an unusual shuffle.  Here we are really conservative:
11196   // we are absolutely afraid of producing a shuffle mask not in the input
11197   // program, because the code gen may not be smart enough to turn a merged
11198   // shuffle into two specific shuffles: it may produce worse code.  As such,
11199   // we only merge two shuffles if the result is one of the two input shuffle
11200   // masks.  In this case, merging the shuffles just removes one instruction,
11201   // which we know is safe.  This is good for things like turning:
11202   // (splat(splat)) -> splat.
11203   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11204     if (isa<UndefValue>(RHS)) {
11205       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11206
11207       std::vector<unsigned> NewMask;
11208       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11209         if (Mask[i] >= 2*e)
11210           NewMask.push_back(2*e);
11211         else
11212           NewMask.push_back(LHSMask[Mask[i]]);
11213       
11214       // If the result mask is equal to the src shuffle or this shuffle mask, do
11215       // the replacement.
11216       if (NewMask == LHSMask || NewMask == Mask) {
11217         std::vector<Constant*> Elts;
11218         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11219           if (NewMask[i] >= e*2) {
11220             Elts.push_back(UndefValue::get(Type::Int32Ty));
11221           } else {
11222             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11223           }
11224         }
11225         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11226                                      LHSSVI->getOperand(1),
11227                                      ConstantVector::get(Elts));
11228       }
11229     }
11230   }
11231
11232   return MadeChange ? &SVI : 0;
11233 }
11234
11235
11236
11237
11238 /// TryToSinkInstruction - Try to move the specified instruction from its
11239 /// current block into the beginning of DestBlock, which can only happen if it's
11240 /// safe to move the instruction past all of the instructions between it and the
11241 /// end of its block.
11242 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11243   assert(I->hasOneUse() && "Invariants didn't hold!");
11244
11245   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11246   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11247     return false;
11248
11249   // Do not sink alloca instructions out of the entry block.
11250   if (isa<AllocaInst>(I) && I->getParent() ==
11251         &DestBlock->getParent()->getEntryBlock())
11252     return false;
11253
11254   // We can only sink load instructions if there is nothing between the load and
11255   // the end of block that could change the value.
11256   if (I->mayReadFromMemory()) {
11257     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11258          Scan != E; ++Scan)
11259       if (Scan->mayWriteToMemory())
11260         return false;
11261   }
11262
11263   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11264
11265   I->moveBefore(InsertPos);
11266   ++NumSunkInst;
11267   return true;
11268 }
11269
11270
11271 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11272 /// all reachable code to the worklist.
11273 ///
11274 /// This has a couple of tricks to make the code faster and more powerful.  In
11275 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11276 /// them to the worklist (this significantly speeds up instcombine on code where
11277 /// many instructions are dead or constant).  Additionally, if we find a branch
11278 /// whose condition is a known constant, we only visit the reachable successors.
11279 ///
11280 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11281                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11282                                        InstCombiner &IC,
11283                                        const TargetData *TD) {
11284   std::vector<BasicBlock*> Worklist;
11285   Worklist.push_back(BB);
11286
11287   while (!Worklist.empty()) {
11288     BB = Worklist.back();
11289     Worklist.pop_back();
11290     
11291     // We have now visited this block!  If we've already been here, ignore it.
11292     if (!Visited.insert(BB)) continue;
11293     
11294     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11295       Instruction *Inst = BBI++;
11296       
11297       // DCE instruction if trivially dead.
11298       if (isInstructionTriviallyDead(Inst)) {
11299         ++NumDeadInst;
11300         DOUT << "IC: DCE: " << *Inst;
11301         Inst->eraseFromParent();
11302         continue;
11303       }
11304       
11305       // ConstantProp instruction if trivially constant.
11306       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11307         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11308         Inst->replaceAllUsesWith(C);
11309         ++NumConstProp;
11310         Inst->eraseFromParent();
11311         continue;
11312       }
11313      
11314       IC.AddToWorkList(Inst);
11315     }
11316
11317     // Recursively visit successors.  If this is a branch or switch on a
11318     // constant, only visit the reachable successor.
11319     TerminatorInst *TI = BB->getTerminator();
11320     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11321       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11322         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11323         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11324         Worklist.push_back(ReachableBB);
11325         continue;
11326       }
11327     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11328       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11329         // See if this is an explicit destination.
11330         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11331           if (SI->getCaseValue(i) == Cond) {
11332             BasicBlock *ReachableBB = SI->getSuccessor(i);
11333             Worklist.push_back(ReachableBB);
11334             continue;
11335           }
11336         
11337         // Otherwise it is the default destination.
11338         Worklist.push_back(SI->getSuccessor(0));
11339         continue;
11340       }
11341     }
11342     
11343     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11344       Worklist.push_back(TI->getSuccessor(i));
11345   }
11346 }
11347
11348 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11349   bool Changed = false;
11350   TD = &getAnalysis<TargetData>();
11351   
11352   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11353              << F.getNameStr() << "\n");
11354
11355   {
11356     // Do a depth-first traversal of the function, populate the worklist with
11357     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11358     // track of which blocks we visit.
11359     SmallPtrSet<BasicBlock*, 64> Visited;
11360     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11361
11362     // Do a quick scan over the function.  If we find any blocks that are
11363     // unreachable, remove any instructions inside of them.  This prevents
11364     // the instcombine code from having to deal with some bad special cases.
11365     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11366       if (!Visited.count(BB)) {
11367         Instruction *Term = BB->getTerminator();
11368         while (Term != BB->begin()) {   // Remove instrs bottom-up
11369           BasicBlock::iterator I = Term; --I;
11370
11371           DOUT << "IC: DCE: " << *I;
11372           ++NumDeadInst;
11373
11374           if (!I->use_empty())
11375             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11376           I->eraseFromParent();
11377         }
11378       }
11379   }
11380
11381   while (!Worklist.empty()) {
11382     Instruction *I = RemoveOneFromWorkList();
11383     if (I == 0) continue;  // skip null values.
11384
11385     // Check to see if we can DCE the instruction.
11386     if (isInstructionTriviallyDead(I)) {
11387       // Add operands to the worklist.
11388       if (I->getNumOperands() < 4)
11389         AddUsesToWorkList(*I);
11390       ++NumDeadInst;
11391
11392       DOUT << "IC: DCE: " << *I;
11393
11394       I->eraseFromParent();
11395       RemoveFromWorkList(I);
11396       continue;
11397     }
11398
11399     // Instruction isn't dead, see if we can constant propagate it.
11400     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11401       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11402
11403       // Add operands to the worklist.
11404       AddUsesToWorkList(*I);
11405       ReplaceInstUsesWith(*I, C);
11406
11407       ++NumConstProp;
11408       I->eraseFromParent();
11409       RemoveFromWorkList(I);
11410       continue;
11411     }
11412
11413     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11414       // See if we can constant fold its operands.
11415       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11416         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11417           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11418             i->set(NewC);
11419         }
11420       }
11421     }
11422
11423     // See if we can trivially sink this instruction to a successor basic block.
11424     // FIXME: Remove GetResultInst test when first class support for aggregates
11425     // is implemented.
11426     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11427       BasicBlock *BB = I->getParent();
11428       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11429       if (UserParent != BB) {
11430         bool UserIsSuccessor = false;
11431         // See if the user is one of our successors.
11432         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11433           if (*SI == UserParent) {
11434             UserIsSuccessor = true;
11435             break;
11436           }
11437
11438         // If the user is one of our immediate successors, and if that successor
11439         // only has us as a predecessors (we'd have to split the critical edge
11440         // otherwise), we can keep going.
11441         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11442             next(pred_begin(UserParent)) == pred_end(UserParent))
11443           // Okay, the CFG is simple enough, try to sink this instruction.
11444           Changed |= TryToSinkInstruction(I, UserParent);
11445       }
11446     }
11447
11448     // Now that we have an instruction, try combining it to simplify it...
11449 #ifndef NDEBUG
11450     std::string OrigI;
11451 #endif
11452     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11453     if (Instruction *Result = visit(*I)) {
11454       ++NumCombined;
11455       // Should we replace the old instruction with a new one?
11456       if (Result != I) {
11457         DOUT << "IC: Old = " << *I
11458              << "    New = " << *Result;
11459
11460         // Everything uses the new instruction now.
11461         I->replaceAllUsesWith(Result);
11462
11463         // Push the new instruction and any users onto the worklist.
11464         AddToWorkList(Result);
11465         AddUsersToWorkList(*Result);
11466
11467         // Move the name to the new instruction first.
11468         Result->takeName(I);
11469
11470         // Insert the new instruction into the basic block...
11471         BasicBlock *InstParent = I->getParent();
11472         BasicBlock::iterator InsertPos = I;
11473
11474         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11475           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11476             ++InsertPos;
11477
11478         InstParent->getInstList().insert(InsertPos, Result);
11479
11480         // Make sure that we reprocess all operands now that we reduced their
11481         // use counts.
11482         AddUsesToWorkList(*I);
11483
11484         // Instructions can end up on the worklist more than once.  Make sure
11485         // we do not process an instruction that has been deleted.
11486         RemoveFromWorkList(I);
11487
11488         // Erase the old instruction.
11489         InstParent->getInstList().erase(I);
11490       } else {
11491 #ifndef NDEBUG
11492         DOUT << "IC: Mod = " << OrigI
11493              << "    New = " << *I;
11494 #endif
11495
11496         // If the instruction was modified, it's possible that it is now dead.
11497         // if so, remove it.
11498         if (isInstructionTriviallyDead(I)) {
11499           // Make sure we process all operands now that we are reducing their
11500           // use counts.
11501           AddUsesToWorkList(*I);
11502
11503           // Instructions may end up in the worklist more than once.  Erase all
11504           // occurrences of this instruction.
11505           RemoveFromWorkList(I);
11506           I->eraseFromParent();
11507         } else {
11508           AddToWorkList(I);
11509           AddUsersToWorkList(*I);
11510         }
11511       }
11512       Changed = true;
11513     }
11514   }
11515
11516   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11517     
11518   // Do an explicit clear, this shrinks the map if needed.
11519   WorklistMap.clear();
11520   return Changed;
11521 }
11522
11523
11524 bool InstCombiner::runOnFunction(Function &F) {
11525   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11526   
11527   bool EverMadeChange = false;
11528
11529   // Iterate while there is work to do.
11530   unsigned Iteration = 0;
11531   while (DoOneIteration(F, Iteration++))
11532     EverMadeChange = true;
11533   return EverMadeChange;
11534 }
11535
11536 FunctionPass *llvm::createInstructionCombiningPass() {
11537   return new InstCombiner();
11538 }
11539