20580e30ab47d1b4aeb641f14dbb2566769afc00
[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         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1258           return UpdateValueUsesWith(I, I->getOperand(0));
1259
1260         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1261         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1262         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1263                                  LHSKnownZero, LHSKnownOne, Depth+1))
1264           return true;
1265
1266         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1267           LHSKnownZero |= ~LowBits;
1268         else if (LHSKnownOne[BitWidth-1])
1269           LHSKnownOne |= ~LowBits;
1270
1271         KnownZero |= LHSKnownZero & DemandedMask;
1272         KnownOne |= LHSKnownOne & DemandedMask;
1273
1274         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1275       }
1276     }
1277     break;
1278   case Instruction::URem: {
1279     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1280     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1281     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1282                              KnownZero2, KnownOne2, Depth+1))
1283       return true;
1284
1285     uint32_t Leaders = KnownZero2.countLeadingOnes();
1286     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1287                              KnownZero2, KnownOne2, Depth+1))
1288       return true;
1289
1290     Leaders = std::max(Leaders,
1291                        KnownZero2.countLeadingOnes());
1292     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1293     break;
1294   }
1295   case Instruction::Call:
1296     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1297       switch (II->getIntrinsicID()) {
1298       default: break;
1299       case Intrinsic::bswap: {
1300         // If the only bits demanded come from one byte of the bswap result,
1301         // just shift the input byte into position to eliminate the bswap.
1302         unsigned NLZ = DemandedMask.countLeadingZeros();
1303         unsigned NTZ = DemandedMask.countTrailingZeros();
1304           
1305         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1306         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1307         // have 14 leading zeros, round to 8.
1308         NLZ &= ~7;
1309         NTZ &= ~7;
1310         // If we need exactly one byte, we can do this transformation.
1311         if (BitWidth-NLZ-NTZ == 8) {
1312           unsigned ResultBit = NTZ;
1313           unsigned InputBit = BitWidth-NTZ-8;
1314           
1315           // Replace this with either a left or right shift to get the byte into
1316           // the right place.
1317           Instruction *NewVal;
1318           if (InputBit > ResultBit)
1319             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1320                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1321           else
1322             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1323                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1324           NewVal->takeName(I);
1325           InsertNewInstBefore(NewVal, *I);
1326           return UpdateValueUsesWith(I, NewVal);
1327         }
1328           
1329         // TODO: Could compute known zero/one bits based on the input.
1330         break;
1331       }
1332       }
1333     }
1334     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1335     break;
1336   }
1337   
1338   // If the client is only demanding bits that we know, return the known
1339   // constant.
1340   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1341     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1342   return false;
1343 }
1344
1345
1346 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1347 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1348 /// actually used by the caller.  This method analyzes which elements of the
1349 /// operand are undef and returns that information in UndefElts.
1350 ///
1351 /// If the information about demanded elements can be used to simplify the
1352 /// operation, the operation is simplified, then the resultant value is
1353 /// returned.  This returns null if no change was made.
1354 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1355                                                 uint64_t &UndefElts,
1356                                                 unsigned Depth) {
1357   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1358   assert(VWidth <= 64 && "Vector too wide to analyze!");
1359   uint64_t EltMask = ~0ULL >> (64-VWidth);
1360   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1361          "Invalid DemandedElts!");
1362
1363   if (isa<UndefValue>(V)) {
1364     // If the entire vector is undefined, just return this info.
1365     UndefElts = EltMask;
1366     return 0;
1367   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1368     UndefElts = EltMask;
1369     return UndefValue::get(V->getType());
1370   }
1371   
1372   UndefElts = 0;
1373   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1374     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1375     Constant *Undef = UndefValue::get(EltTy);
1376
1377     std::vector<Constant*> Elts;
1378     for (unsigned i = 0; i != VWidth; ++i)
1379       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1380         Elts.push_back(Undef);
1381         UndefElts |= (1ULL << i);
1382       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1383         Elts.push_back(Undef);
1384         UndefElts |= (1ULL << i);
1385       } else {                               // Otherwise, defined.
1386         Elts.push_back(CP->getOperand(i));
1387       }
1388         
1389     // If we changed the constant, return it.
1390     Constant *NewCP = ConstantVector::get(Elts);
1391     return NewCP != CP ? NewCP : 0;
1392   } else if (isa<ConstantAggregateZero>(V)) {
1393     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1394     // set to undef.
1395     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1396     Constant *Zero = Constant::getNullValue(EltTy);
1397     Constant *Undef = UndefValue::get(EltTy);
1398     std::vector<Constant*> Elts;
1399     for (unsigned i = 0; i != VWidth; ++i)
1400       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1401     UndefElts = DemandedElts ^ EltMask;
1402     return ConstantVector::get(Elts);
1403   }
1404   
1405   if (!V->hasOneUse()) {    // Other users may use these bits.
1406     if (Depth != 0) {       // Not at the root.
1407       // TODO: Just compute the UndefElts information recursively.
1408       return false;
1409     }
1410     return false;
1411   } else if (Depth == 10) {        // Limit search depth.
1412     return false;
1413   }
1414   
1415   Instruction *I = dyn_cast<Instruction>(V);
1416   if (!I) return false;        // Only analyze instructions.
1417   
1418   bool MadeChange = false;
1419   uint64_t UndefElts2;
1420   Value *TmpV;
1421   switch (I->getOpcode()) {
1422   default: break;
1423     
1424   case Instruction::InsertElement: {
1425     // If this is a variable index, we don't know which element it overwrites.
1426     // demand exactly the same input as we produce.
1427     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1428     if (Idx == 0) {
1429       // Note that we can't propagate undef elt info, because we don't know
1430       // which elt is getting updated.
1431       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1432                                         UndefElts2, Depth+1);
1433       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1434       break;
1435     }
1436     
1437     // If this is inserting an element that isn't demanded, remove this
1438     // insertelement.
1439     unsigned IdxNo = Idx->getZExtValue();
1440     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1441       return AddSoonDeadInstToWorklist(*I, 0);
1442     
1443     // Otherwise, the element inserted overwrites whatever was there, so the
1444     // input demanded set is simpler than the output set.
1445     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1446                                       DemandedElts & ~(1ULL << IdxNo),
1447                                       UndefElts, Depth+1);
1448     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1449
1450     // The inserted element is defined.
1451     UndefElts |= 1ULL << IdxNo;
1452     break;
1453   }
1454   case Instruction::BitCast: {
1455     // Vector->vector casts only.
1456     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1457     if (!VTy) break;
1458     unsigned InVWidth = VTy->getNumElements();
1459     uint64_t InputDemandedElts = 0;
1460     unsigned Ratio;
1461
1462     if (VWidth == InVWidth) {
1463       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1464       // elements as are demanded of us.
1465       Ratio = 1;
1466       InputDemandedElts = DemandedElts;
1467     } else if (VWidth > InVWidth) {
1468       // Untested so far.
1469       break;
1470       
1471       // If there are more elements in the result than there are in the source,
1472       // then an input element is live if any of the corresponding output
1473       // elements are live.
1474       Ratio = VWidth/InVWidth;
1475       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1476         if (DemandedElts & (1ULL << OutIdx))
1477           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1478       }
1479     } else {
1480       // Untested so far.
1481       break;
1482       
1483       // If there are more elements in the source than there are in the result,
1484       // then an input element is live if the corresponding output element is
1485       // live.
1486       Ratio = InVWidth/VWidth;
1487       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1488         if (DemandedElts & (1ULL << InIdx/Ratio))
1489           InputDemandedElts |= 1ULL << InIdx;
1490     }
1491     
1492     // div/rem demand all inputs, because they don't want divide by zero.
1493     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1494                                       UndefElts2, Depth+1);
1495     if (TmpV) {
1496       I->setOperand(0, TmpV);
1497       MadeChange = true;
1498     }
1499     
1500     UndefElts = UndefElts2;
1501     if (VWidth > InVWidth) {
1502       assert(0 && "Unimp");
1503       // If there are more elements in the result than there are in the source,
1504       // then an output element is undef if the corresponding input element is
1505       // undef.
1506       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1507         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1508           UndefElts |= 1ULL << OutIdx;
1509     } else if (VWidth < InVWidth) {
1510       assert(0 && "Unimp");
1511       // If there are more elements in the source than there are in the result,
1512       // then a result element is undef if all of the corresponding input
1513       // elements are undef.
1514       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1515       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1516         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1517           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1518     }
1519     break;
1520   }
1521   case Instruction::And:
1522   case Instruction::Or:
1523   case Instruction::Xor:
1524   case Instruction::Add:
1525   case Instruction::Sub:
1526   case Instruction::Mul:
1527     // div/rem demand all inputs, because they don't want divide by zero.
1528     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1529                                       UndefElts, Depth+1);
1530     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1531     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1532                                       UndefElts2, Depth+1);
1533     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1534       
1535     // Output elements are undefined if both are undefined.  Consider things
1536     // like undef&0.  The result is known zero, not undef.
1537     UndefElts &= UndefElts2;
1538     break;
1539     
1540   case Instruction::Call: {
1541     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1542     if (!II) break;
1543     switch (II->getIntrinsicID()) {
1544     default: break;
1545       
1546     // Binary vector operations that work column-wise.  A dest element is a
1547     // function of the corresponding input elements from the two inputs.
1548     case Intrinsic::x86_sse_sub_ss:
1549     case Intrinsic::x86_sse_mul_ss:
1550     case Intrinsic::x86_sse_min_ss:
1551     case Intrinsic::x86_sse_max_ss:
1552     case Intrinsic::x86_sse2_sub_sd:
1553     case Intrinsic::x86_sse2_mul_sd:
1554     case Intrinsic::x86_sse2_min_sd:
1555     case Intrinsic::x86_sse2_max_sd:
1556       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1557                                         UndefElts, Depth+1);
1558       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1559       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1560                                         UndefElts2, Depth+1);
1561       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1562
1563       // If only the low elt is demanded and this is a scalarizable intrinsic,
1564       // scalarize it now.
1565       if (DemandedElts == 1) {
1566         switch (II->getIntrinsicID()) {
1567         default: break;
1568         case Intrinsic::x86_sse_sub_ss:
1569         case Intrinsic::x86_sse_mul_ss:
1570         case Intrinsic::x86_sse2_sub_sd:
1571         case Intrinsic::x86_sse2_mul_sd:
1572           // TODO: Lower MIN/MAX/ABS/etc
1573           Value *LHS = II->getOperand(1);
1574           Value *RHS = II->getOperand(2);
1575           // Extract the element as scalars.
1576           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1577           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1578           
1579           switch (II->getIntrinsicID()) {
1580           default: assert(0 && "Case stmts out of sync!");
1581           case Intrinsic::x86_sse_sub_ss:
1582           case Intrinsic::x86_sse2_sub_sd:
1583             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1584                                                         II->getName()), *II);
1585             break;
1586           case Intrinsic::x86_sse_mul_ss:
1587           case Intrinsic::x86_sse2_mul_sd:
1588             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1589                                                          II->getName()), *II);
1590             break;
1591           }
1592           
1593           Instruction *New =
1594             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1595                                       II->getName());
1596           InsertNewInstBefore(New, *II);
1597           AddSoonDeadInstToWorklist(*II, 0);
1598           return New;
1599         }            
1600       }
1601         
1602       // Output elements are undefined if both are undefined.  Consider things
1603       // like undef&0.  The result is known zero, not undef.
1604       UndefElts &= UndefElts2;
1605       break;
1606     }
1607     break;
1608   }
1609   }
1610   return MadeChange ? I : 0;
1611 }
1612
1613
1614 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1615 /// function is designed to check a chain of associative operators for a
1616 /// potential to apply a certain optimization.  Since the optimization may be
1617 /// applicable if the expression was reassociated, this checks the chain, then
1618 /// reassociates the expression as necessary to expose the optimization
1619 /// opportunity.  This makes use of a special Functor, which must define
1620 /// 'shouldApply' and 'apply' methods.
1621 ///
1622 template<typename Functor>
1623 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1624   unsigned Opcode = Root.getOpcode();
1625   Value *LHS = Root.getOperand(0);
1626
1627   // Quick check, see if the immediate LHS matches...
1628   if (F.shouldApply(LHS))
1629     return F.apply(Root);
1630
1631   // Otherwise, if the LHS is not of the same opcode as the root, return.
1632   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1633   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1634     // Should we apply this transform to the RHS?
1635     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1636
1637     // If not to the RHS, check to see if we should apply to the LHS...
1638     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1639       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1640       ShouldApply = true;
1641     }
1642
1643     // If the functor wants to apply the optimization to the RHS of LHSI,
1644     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1645     if (ShouldApply) {
1646       // Now all of the instructions are in the current basic block, go ahead
1647       // and perform the reassociation.
1648       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1649
1650       // First move the selected RHS to the LHS of the root...
1651       Root.setOperand(0, LHSI->getOperand(1));
1652
1653       // Make what used to be the LHS of the root be the user of the root...
1654       Value *ExtraOperand = TmpLHSI->getOperand(1);
1655       if (&Root == TmpLHSI) {
1656         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1657         return 0;
1658       }
1659       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1660       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1661       BasicBlock::iterator ARI = &Root; ++ARI;
1662       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1663       ARI = Root;
1664
1665       // Now propagate the ExtraOperand down the chain of instructions until we
1666       // get to LHSI.
1667       while (TmpLHSI != LHSI) {
1668         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1669         // Move the instruction to immediately before the chain we are
1670         // constructing to avoid breaking dominance properties.
1671         NextLHSI->moveBefore(ARI);
1672         ARI = NextLHSI;
1673
1674         Value *NextOp = NextLHSI->getOperand(1);
1675         NextLHSI->setOperand(1, ExtraOperand);
1676         TmpLHSI = NextLHSI;
1677         ExtraOperand = NextOp;
1678       }
1679
1680       // Now that the instructions are reassociated, have the functor perform
1681       // the transformation...
1682       return F.apply(Root);
1683     }
1684
1685     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1686   }
1687   return 0;
1688 }
1689
1690 namespace {
1691
1692 // AddRHS - Implements: X + X --> X << 1
1693 struct AddRHS {
1694   Value *RHS;
1695   AddRHS(Value *rhs) : RHS(rhs) {}
1696   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1697   Instruction *apply(BinaryOperator &Add) const {
1698     return BinaryOperator::CreateShl(Add.getOperand(0),
1699                                      ConstantInt::get(Add.getType(), 1));
1700   }
1701 };
1702
1703 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1704 //                 iff C1&C2 == 0
1705 struct AddMaskingAnd {
1706   Constant *C2;
1707   AddMaskingAnd(Constant *c) : C2(c) {}
1708   bool shouldApply(Value *LHS) const {
1709     ConstantInt *C1;
1710     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1711            ConstantExpr::getAnd(C1, C2)->isNullValue();
1712   }
1713   Instruction *apply(BinaryOperator &Add) const {
1714     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1715   }
1716 };
1717
1718 }
1719
1720 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1721                                              InstCombiner *IC) {
1722   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1723     if (Constant *SOC = dyn_cast<Constant>(SO))
1724       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1725
1726     return IC->InsertNewInstBefore(CastInst::Create(
1727           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1728   }
1729
1730   // Figure out if the constant is the left or the right argument.
1731   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1732   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1733
1734   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1735     if (ConstIsRHS)
1736       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1737     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1738   }
1739
1740   Value *Op0 = SO, *Op1 = ConstOperand;
1741   if (!ConstIsRHS)
1742     std::swap(Op0, Op1);
1743   Instruction *New;
1744   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1745     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1746   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1747     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1748                           SO->getName()+".cmp");
1749   else {
1750     assert(0 && "Unknown binary instruction type!");
1751     abort();
1752   }
1753   return IC->InsertNewInstBefore(New, I);
1754 }
1755
1756 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1757 // constant as the other operand, try to fold the binary operator into the
1758 // select arguments.  This also works for Cast instructions, which obviously do
1759 // not have a second operand.
1760 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1761                                      InstCombiner *IC) {
1762   // Don't modify shared select instructions
1763   if (!SI->hasOneUse()) return 0;
1764   Value *TV = SI->getOperand(1);
1765   Value *FV = SI->getOperand(2);
1766
1767   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1768     // Bool selects with constant operands can be folded to logical ops.
1769     if (SI->getType() == Type::Int1Ty) return 0;
1770
1771     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1772     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1773
1774     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1775                               SelectFalseVal);
1776   }
1777   return 0;
1778 }
1779
1780
1781 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1782 /// node as operand #0, see if we can fold the instruction into the PHI (which
1783 /// is only possible if all operands to the PHI are constants).
1784 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1785   PHINode *PN = cast<PHINode>(I.getOperand(0));
1786   unsigned NumPHIValues = PN->getNumIncomingValues();
1787   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1788
1789   // Check to see if all of the operands of the PHI are constants.  If there is
1790   // one non-constant value, remember the BB it is.  If there is more than one
1791   // or if *it* is a PHI, bail out.
1792   BasicBlock *NonConstBB = 0;
1793   for (unsigned i = 0; i != NumPHIValues; ++i)
1794     if (!isa<Constant>(PN->getIncomingValue(i))) {
1795       if (NonConstBB) return 0;  // More than one non-const value.
1796       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1797       NonConstBB = PN->getIncomingBlock(i);
1798       
1799       // If the incoming non-constant value is in I's block, we have an infinite
1800       // loop.
1801       if (NonConstBB == I.getParent())
1802         return 0;
1803     }
1804   
1805   // If there is exactly one non-constant value, we can insert a copy of the
1806   // operation in that block.  However, if this is a critical edge, we would be
1807   // inserting the computation one some other paths (e.g. inside a loop).  Only
1808   // do this if the pred block is unconditionally branching into the phi block.
1809   if (NonConstBB) {
1810     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1811     if (!BI || !BI->isUnconditional()) return 0;
1812   }
1813
1814   // Okay, we can do the transformation: create the new PHI node.
1815   PHINode *NewPN = PHINode::Create(I.getType(), "");
1816   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1817   InsertNewInstBefore(NewPN, *PN);
1818   NewPN->takeName(PN);
1819
1820   // Next, add all of the operands to the PHI.
1821   if (I.getNumOperands() == 2) {
1822     Constant *C = cast<Constant>(I.getOperand(1));
1823     for (unsigned i = 0; i != NumPHIValues; ++i) {
1824       Value *InV = 0;
1825       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1826         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1827           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1828         else
1829           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1830       } else {
1831         assert(PN->getIncomingBlock(i) == NonConstBB);
1832         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1833           InV = BinaryOperator::Create(BO->getOpcode(),
1834                                        PN->getIncomingValue(i), C, "phitmp",
1835                                        NonConstBB->getTerminator());
1836         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1837           InV = CmpInst::Create(CI->getOpcode(), 
1838                                 CI->getPredicate(),
1839                                 PN->getIncomingValue(i), C, "phitmp",
1840                                 NonConstBB->getTerminator());
1841         else
1842           assert(0 && "Unknown binop!");
1843         
1844         AddToWorkList(cast<Instruction>(InV));
1845       }
1846       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1847     }
1848   } else { 
1849     CastInst *CI = cast<CastInst>(&I);
1850     const Type *RetTy = CI->getType();
1851     for (unsigned i = 0; i != NumPHIValues; ++i) {
1852       Value *InV;
1853       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1854         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1855       } else {
1856         assert(PN->getIncomingBlock(i) == NonConstBB);
1857         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1858                                I.getType(), "phitmp", 
1859                                NonConstBB->getTerminator());
1860         AddToWorkList(cast<Instruction>(InV));
1861       }
1862       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1863     }
1864   }
1865   return ReplaceInstUsesWith(I, NewPN);
1866 }
1867
1868
1869 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1870 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1871 /// This basically requires proving that the add in the original type would not
1872 /// overflow to change the sign bit or have a carry out.
1873 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1874   // There are different heuristics we can use for this.  Here are some simple
1875   // ones.
1876   
1877   // Add has the property that adding any two 2's complement numbers can only 
1878   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1879   // have at least two sign bits, we know that the addition of the two values will
1880   // sign extend fine.
1881   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1882     return true;
1883   
1884   
1885   // If one of the operands only has one non-zero bit, and if the other operand
1886   // has a known-zero bit in a more significant place than it (not including the
1887   // sign bit) the ripple may go up to and fill the zero, but won't change the
1888   // sign.  For example, (X & ~4) + 1.
1889   
1890   // TODO: Implement.
1891   
1892   return false;
1893 }
1894
1895
1896 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1897   bool Changed = SimplifyCommutative(I);
1898   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1899
1900   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1901     // X + undef -> undef
1902     if (isa<UndefValue>(RHS))
1903       return ReplaceInstUsesWith(I, RHS);
1904
1905     // X + 0 --> X
1906     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1907       if (RHSC->isNullValue())
1908         return ReplaceInstUsesWith(I, LHS);
1909     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1910       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1911                               (I.getType())->getValueAPF()))
1912         return ReplaceInstUsesWith(I, LHS);
1913     }
1914
1915     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1916       // X + (signbit) --> X ^ signbit
1917       const APInt& Val = CI->getValue();
1918       uint32_t BitWidth = Val.getBitWidth();
1919       if (Val == APInt::getSignBit(BitWidth))
1920         return BinaryOperator::CreateXor(LHS, RHS);
1921       
1922       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1923       // (X & 254)+1 -> (X&254)|1
1924       if (!isa<VectorType>(I.getType())) {
1925         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1926         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1927                                  KnownZero, KnownOne))
1928           return &I;
1929       }
1930     }
1931
1932     if (isa<PHINode>(LHS))
1933       if (Instruction *NV = FoldOpIntoPhi(I))
1934         return NV;
1935     
1936     ConstantInt *XorRHS = 0;
1937     Value *XorLHS = 0;
1938     if (isa<ConstantInt>(RHSC) &&
1939         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1940       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1941       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1942       
1943       uint32_t Size = TySizeBits / 2;
1944       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1945       APInt CFF80Val(-C0080Val);
1946       do {
1947         if (TySizeBits > Size) {
1948           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1949           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1950           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1951               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1952             // This is a sign extend if the top bits are known zero.
1953             if (!MaskedValueIsZero(XorLHS, 
1954                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1955               Size = 0;  // Not a sign ext, but can't be any others either.
1956             break;
1957           }
1958         }
1959         Size >>= 1;
1960         C0080Val = APIntOps::lshr(C0080Val, Size);
1961         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1962       } while (Size >= 1);
1963       
1964       // FIXME: This shouldn't be necessary. When the backends can handle types
1965       // with funny bit widths then this switch statement should be removed. It
1966       // is just here to get the size of the "middle" type back up to something
1967       // that the back ends can handle.
1968       const Type *MiddleType = 0;
1969       switch (Size) {
1970         default: break;
1971         case 32: MiddleType = Type::Int32Ty; break;
1972         case 16: MiddleType = Type::Int16Ty; break;
1973         case  8: MiddleType = Type::Int8Ty; break;
1974       }
1975       if (MiddleType) {
1976         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1977         InsertNewInstBefore(NewTrunc, I);
1978         return new SExtInst(NewTrunc, I.getType(), I.getName());
1979       }
1980     }
1981   }
1982
1983   if (I.getType() == Type::Int1Ty)
1984     return BinaryOperator::CreateXor(LHS, RHS);
1985
1986   // X + X --> X << 1
1987   if (I.getType()->isInteger()) {
1988     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1989
1990     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1991       if (RHSI->getOpcode() == Instruction::Sub)
1992         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1993           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1994     }
1995     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1996       if (LHSI->getOpcode() == Instruction::Sub)
1997         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1998           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1999     }
2000   }
2001
2002   // -A + B  -->  B - A
2003   // -A + -B  -->  -(A + B)
2004   if (Value *LHSV = dyn_castNegVal(LHS)) {
2005     if (LHS->getType()->isIntOrIntVector()) {
2006       if (Value *RHSV = dyn_castNegVal(RHS)) {
2007         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2008         InsertNewInstBefore(NewAdd, I);
2009         return BinaryOperator::CreateNeg(NewAdd);
2010       }
2011     }
2012     
2013     return BinaryOperator::CreateSub(RHS, LHSV);
2014   }
2015
2016   // A + -B  -->  A - B
2017   if (!isa<Constant>(RHS))
2018     if (Value *V = dyn_castNegVal(RHS))
2019       return BinaryOperator::CreateSub(LHS, V);
2020
2021
2022   ConstantInt *C2;
2023   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2024     if (X == RHS)   // X*C + X --> X * (C+1)
2025       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2026
2027     // X*C1 + X*C2 --> X * (C1+C2)
2028     ConstantInt *C1;
2029     if (X == dyn_castFoldableMul(RHS, C1))
2030       return BinaryOperator::CreateMul(X, Add(C1, C2));
2031   }
2032
2033   // X + X*C --> X * (C+1)
2034   if (dyn_castFoldableMul(RHS, C2) == LHS)
2035     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2036
2037   // X + ~X --> -1   since   ~X = -X-1
2038   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2039     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2040   
2041
2042   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2043   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2044     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2045       return R;
2046   
2047   // A+B --> A|B iff A and B have no bits set in common.
2048   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2049     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2050     APInt LHSKnownOne(IT->getBitWidth(), 0);
2051     APInt LHSKnownZero(IT->getBitWidth(), 0);
2052     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2053     if (LHSKnownZero != 0) {
2054       APInt RHSKnownOne(IT->getBitWidth(), 0);
2055       APInt RHSKnownZero(IT->getBitWidth(), 0);
2056       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2057       
2058       // No bits in common -> bitwise or.
2059       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2060         return BinaryOperator::CreateOr(LHS, RHS);
2061     }
2062   }
2063
2064   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2065   if (I.getType()->isIntOrIntVector()) {
2066     Value *W, *X, *Y, *Z;
2067     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2068         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2069       if (W != Y) {
2070         if (W == Z) {
2071           std::swap(Y, Z);
2072         } else if (Y == X) {
2073           std::swap(W, X);
2074         } else if (X == Z) {
2075           std::swap(Y, Z);
2076           std::swap(W, X);
2077         }
2078       }
2079
2080       if (W == Y) {
2081         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2082                                                             LHS->getName()), I);
2083         return BinaryOperator::CreateMul(W, NewAdd);
2084       }
2085     }
2086   }
2087
2088   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2089     Value *X = 0;
2090     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2091       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2092
2093     // (X & FF00) + xx00  -> (X+xx00) & FF00
2094     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2095       Constant *Anded = And(CRHS, C2);
2096       if (Anded == CRHS) {
2097         // See if all bits from the first bit set in the Add RHS up are included
2098         // in the mask.  First, get the rightmost bit.
2099         const APInt& AddRHSV = CRHS->getValue();
2100
2101         // Form a mask of all bits from the lowest bit added through the top.
2102         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2103
2104         // See if the and mask includes all of these bits.
2105         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2106
2107         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2108           // Okay, the xform is safe.  Insert the new add pronto.
2109           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2110                                                             LHS->getName()), I);
2111           return BinaryOperator::CreateAnd(NewAdd, C2);
2112         }
2113       }
2114     }
2115
2116     // Try to fold constant add into select arguments.
2117     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2118       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2119         return R;
2120   }
2121
2122   // add (cast *A to intptrtype) B -> 
2123   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2124   {
2125     CastInst *CI = dyn_cast<CastInst>(LHS);
2126     Value *Other = RHS;
2127     if (!CI) {
2128       CI = dyn_cast<CastInst>(RHS);
2129       Other = LHS;
2130     }
2131     if (CI && CI->getType()->isSized() && 
2132         (CI->getType()->getPrimitiveSizeInBits() == 
2133          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2134         && isa<PointerType>(CI->getOperand(0)->getType())) {
2135       unsigned AS =
2136         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2137       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2138                                       PointerType::get(Type::Int8Ty, AS), I);
2139       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2140       return new PtrToIntInst(I2, CI->getType());
2141     }
2142   }
2143   
2144   // add (select X 0 (sub n A)) A  -->  select X A n
2145   {
2146     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2147     Value *Other = RHS;
2148     if (!SI) {
2149       SI = dyn_cast<SelectInst>(RHS);
2150       Other = LHS;
2151     }
2152     if (SI && SI->hasOneUse()) {
2153       Value *TV = SI->getTrueValue();
2154       Value *FV = SI->getFalseValue();
2155       Value *A, *N;
2156
2157       // Can we fold the add into the argument of the select?
2158       // We check both true and false select arguments for a matching subtract.
2159       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2160           A == Other)  // Fold the add into the true select value.
2161         return SelectInst::Create(SI->getCondition(), N, A);
2162       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2163           A == Other)  // Fold the add into the false select value.
2164         return SelectInst::Create(SI->getCondition(), A, N);
2165     }
2166   }
2167   
2168   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2169   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2170     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2171       return ReplaceInstUsesWith(I, LHS);
2172
2173   // Check for (add (sext x), y), see if we can merge this into an
2174   // integer add followed by a sext.
2175   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2176     // (add (sext x), cst) --> (sext (add x, cst'))
2177     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2178       Constant *CI = 
2179         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2180       if (LHSConv->hasOneUse() &&
2181           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2182           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2183         // Insert the new, smaller add.
2184         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2185                                                         CI, "addconv");
2186         InsertNewInstBefore(NewAdd, I);
2187         return new SExtInst(NewAdd, I.getType());
2188       }
2189     }
2190     
2191     // (add (sext x), (sext y)) --> (sext (add int x, y))
2192     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2193       // Only do this if x/y have the same type, if at last one of them has a
2194       // single use (so we don't increase the number of sexts), and if the
2195       // integer add will not overflow.
2196       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2197           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2198           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2199                                    RHSConv->getOperand(0))) {
2200         // Insert the new integer add.
2201         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2202                                                         RHSConv->getOperand(0),
2203                                                         "addconv");
2204         InsertNewInstBefore(NewAdd, I);
2205         return new SExtInst(NewAdd, I.getType());
2206       }
2207     }
2208   }
2209   
2210   // Check for (add double (sitofp x), y), see if we can merge this into an
2211   // integer add followed by a promotion.
2212   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2213     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2214     // ... if the constant fits in the integer value.  This is useful for things
2215     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2216     // requires a constant pool load, and generally allows the add to be better
2217     // instcombined.
2218     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2219       Constant *CI = 
2220       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2221       if (LHSConv->hasOneUse() &&
2222           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2223           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2224         // Insert the new integer add.
2225         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2226                                                         CI, "addconv");
2227         InsertNewInstBefore(NewAdd, I);
2228         return new SIToFPInst(NewAdd, I.getType());
2229       }
2230     }
2231     
2232     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2233     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2234       // Only do this if x/y have the same type, if at last one of them has a
2235       // single use (so we don't increase the number of int->fp conversions),
2236       // and if the integer add will not overflow.
2237       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2238           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2239           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2240                                    RHSConv->getOperand(0))) {
2241         // Insert the new integer add.
2242         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2243                                                         RHSConv->getOperand(0),
2244                                                         "addconv");
2245         InsertNewInstBefore(NewAdd, I);
2246         return new SIToFPInst(NewAdd, I.getType());
2247       }
2248     }
2249   }
2250   
2251   return Changed ? &I : 0;
2252 }
2253
2254 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2255   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2256
2257   if (Op0 == Op1)         // sub X, X  -> 0
2258     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2259
2260   // If this is a 'B = x-(-A)', change to B = x+A...
2261   if (Value *V = dyn_castNegVal(Op1))
2262     return BinaryOperator::CreateAdd(Op0, V);
2263
2264   if (isa<UndefValue>(Op0))
2265     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2266   if (isa<UndefValue>(Op1))
2267     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2268
2269   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2270     // Replace (-1 - A) with (~A)...
2271     if (C->isAllOnesValue())
2272       return BinaryOperator::CreateNot(Op1);
2273
2274     // C - ~X == X + (1+C)
2275     Value *X = 0;
2276     if (match(Op1, m_Not(m_Value(X))))
2277       return BinaryOperator::CreateAdd(X, AddOne(C));
2278
2279     // -(X >>u 31) -> (X >>s 31)
2280     // -(X >>s 31) -> (X >>u 31)
2281     if (C->isZero()) {
2282       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2283         if (SI->getOpcode() == Instruction::LShr) {
2284           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2285             // Check to see if we are shifting out everything but the sign bit.
2286             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2287                 SI->getType()->getPrimitiveSizeInBits()-1) {
2288               // Ok, the transformation is safe.  Insert AShr.
2289               return BinaryOperator::Create(Instruction::AShr, 
2290                                           SI->getOperand(0), CU, SI->getName());
2291             }
2292           }
2293         }
2294         else if (SI->getOpcode() == Instruction::AShr) {
2295           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2296             // Check to see if we are shifting out everything but the sign bit.
2297             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2298                 SI->getType()->getPrimitiveSizeInBits()-1) {
2299               // Ok, the transformation is safe.  Insert LShr. 
2300               return BinaryOperator::CreateLShr(
2301                                           SI->getOperand(0), CU, SI->getName());
2302             }
2303           }
2304         }
2305       }
2306     }
2307
2308     // Try to fold constant sub into select arguments.
2309     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2310       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2311         return R;
2312
2313     if (isa<PHINode>(Op0))
2314       if (Instruction *NV = FoldOpIntoPhi(I))
2315         return NV;
2316   }
2317
2318   if (I.getType() == Type::Int1Ty)
2319     return BinaryOperator::CreateXor(Op0, Op1);
2320
2321   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2322     if (Op1I->getOpcode() == Instruction::Add &&
2323         !Op0->getType()->isFPOrFPVector()) {
2324       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2325         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2326       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2327         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2328       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2329         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2330           // C1-(X+C2) --> (C1-C2)-X
2331           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2332                                            Op1I->getOperand(0));
2333       }
2334     }
2335
2336     if (Op1I->hasOneUse()) {
2337       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2338       // is not used by anyone else...
2339       //
2340       if (Op1I->getOpcode() == Instruction::Sub &&
2341           !Op1I->getType()->isFPOrFPVector()) {
2342         // Swap the two operands of the subexpr...
2343         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2344         Op1I->setOperand(0, IIOp1);
2345         Op1I->setOperand(1, IIOp0);
2346
2347         // Create the new top level add instruction...
2348         return BinaryOperator::CreateAdd(Op0, Op1);
2349       }
2350
2351       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2352       //
2353       if (Op1I->getOpcode() == Instruction::And &&
2354           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2355         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2356
2357         Value *NewNot =
2358           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2359         return BinaryOperator::CreateAnd(Op0, NewNot);
2360       }
2361
2362       // 0 - (X sdiv C)  -> (X sdiv -C)
2363       if (Op1I->getOpcode() == Instruction::SDiv)
2364         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2365           if (CSI->isZero())
2366             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2367               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2368                                                ConstantExpr::getNeg(DivRHS));
2369
2370       // X - X*C --> X * (1-C)
2371       ConstantInt *C2 = 0;
2372       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2373         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2374         return BinaryOperator::CreateMul(Op0, CP1);
2375       }
2376
2377       // X - ((X / Y) * Y) --> X % Y
2378       if (Op1I->getOpcode() == Instruction::Mul)
2379         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2380           if (Op0 == I->getOperand(0) &&
2381               Op1I->getOperand(1) == I->getOperand(1)) {
2382             if (I->getOpcode() == Instruction::SDiv)
2383               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2384             if (I->getOpcode() == Instruction::UDiv)
2385               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2386           }
2387     }
2388   }
2389
2390   if (!Op0->getType()->isFPOrFPVector())
2391     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2392       if (Op0I->getOpcode() == Instruction::Add) {
2393         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2394           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2395         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2396           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2397       } else if (Op0I->getOpcode() == Instruction::Sub) {
2398         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2399           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2400       }
2401     }
2402
2403   ConstantInt *C1;
2404   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2405     if (X == Op1)  // X*C - X --> X * (C-1)
2406       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2407
2408     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2409     if (X == dyn_castFoldableMul(Op1, C2))
2410       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2411   }
2412   return 0;
2413 }
2414
2415 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2416 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2417 /// TrueIfSigned if the result of the comparison is true when the input value is
2418 /// signed.
2419 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2420                            bool &TrueIfSigned) {
2421   switch (pred) {
2422   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2423     TrueIfSigned = true;
2424     return RHS->isZero();
2425   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2426     TrueIfSigned = true;
2427     return RHS->isAllOnesValue();
2428   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2429     TrueIfSigned = false;
2430     return RHS->isAllOnesValue();
2431   case ICmpInst::ICMP_UGT:
2432     // True if LHS u> RHS and RHS == high-bit-mask - 1
2433     TrueIfSigned = true;
2434     return RHS->getValue() ==
2435       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2436   case ICmpInst::ICMP_UGE: 
2437     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2438     TrueIfSigned = true;
2439     return RHS->getValue().isSignBit();
2440   default:
2441     return false;
2442   }
2443 }
2444
2445 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2446   bool Changed = SimplifyCommutative(I);
2447   Value *Op0 = I.getOperand(0);
2448
2449   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2450     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2451
2452   // Simplify mul instructions with a constant RHS...
2453   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2454     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2455
2456       // ((X << C1)*C2) == (X * (C2 << C1))
2457       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2458         if (SI->getOpcode() == Instruction::Shl)
2459           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2460             return BinaryOperator::CreateMul(SI->getOperand(0),
2461                                              ConstantExpr::getShl(CI, ShOp));
2462
2463       if (CI->isZero())
2464         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2465       if (CI->equalsInt(1))                  // X * 1  == X
2466         return ReplaceInstUsesWith(I, Op0);
2467       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2468         return BinaryOperator::CreateNeg(Op0, I.getName());
2469
2470       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2471       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2472         return BinaryOperator::CreateShl(Op0,
2473                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2474       }
2475     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2476       if (Op1F->isNullValue())
2477         return ReplaceInstUsesWith(I, Op1);
2478
2479       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2480       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2481       // We need a better interface for long double here.
2482       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2483         if (Op1F->isExactlyValue(1.0))
2484           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2485     }
2486     
2487     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2488       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2489           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2490         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2491         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2492                                                      Op1, "tmp");
2493         InsertNewInstBefore(Add, I);
2494         Value *C1C2 = ConstantExpr::getMul(Op1, 
2495                                            cast<Constant>(Op0I->getOperand(1)));
2496         return BinaryOperator::CreateAdd(Add, C1C2);
2497         
2498       }
2499
2500     // Try to fold constant mul into select arguments.
2501     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2502       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2503         return R;
2504
2505     if (isa<PHINode>(Op0))
2506       if (Instruction *NV = FoldOpIntoPhi(I))
2507         return NV;
2508   }
2509
2510   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2511     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2512       return BinaryOperator::CreateMul(Op0v, Op1v);
2513
2514   if (I.getType() == Type::Int1Ty)
2515     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2516
2517   // If one of the operands of the multiply is a cast from a boolean value, then
2518   // we know the bool is either zero or one, so this is a 'masking' multiply.
2519   // See if we can simplify things based on how the boolean was originally
2520   // formed.
2521   CastInst *BoolCast = 0;
2522   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2523     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2524       BoolCast = CI;
2525   if (!BoolCast)
2526     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2527       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2528         BoolCast = CI;
2529   if (BoolCast) {
2530     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2531       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2532       const Type *SCOpTy = SCIOp0->getType();
2533       bool TIS = false;
2534       
2535       // If the icmp is true iff the sign bit of X is set, then convert this
2536       // multiply into a shift/and combination.
2537       if (isa<ConstantInt>(SCIOp1) &&
2538           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2539           TIS) {
2540         // Shift the X value right to turn it into "all signbits".
2541         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2542                                           SCOpTy->getPrimitiveSizeInBits()-1);
2543         Value *V =
2544           InsertNewInstBefore(
2545             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2546                                             BoolCast->getOperand(0)->getName()+
2547                                             ".mask"), I);
2548
2549         // If the multiply type is not the same as the source type, sign extend
2550         // or truncate to the multiply type.
2551         if (I.getType() != V->getType()) {
2552           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2553           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2554           Instruction::CastOps opcode = 
2555             (SrcBits == DstBits ? Instruction::BitCast : 
2556              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2557           V = InsertCastBefore(opcode, V, I.getType(), I);
2558         }
2559
2560         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2561         return BinaryOperator::CreateAnd(V, OtherOp);
2562       }
2563     }
2564   }
2565
2566   return Changed ? &I : 0;
2567 }
2568
2569 /// This function implements the transforms on div instructions that work
2570 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2571 /// used by the visitors to those instructions.
2572 /// @brief Transforms common to all three div instructions
2573 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2574   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2575
2576   // undef / X -> 0        for integer.
2577   // undef / X -> undef    for FP (the undef could be a snan).
2578   if (isa<UndefValue>(Op0)) {
2579     if (Op0->getType()->isFPOrFPVector())
2580       return ReplaceInstUsesWith(I, Op0);
2581     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2582   }
2583
2584   // X / undef -> undef
2585   if (isa<UndefValue>(Op1))
2586     return ReplaceInstUsesWith(I, Op1);
2587
2588   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2589   // This does not apply for fdiv.
2590   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2591     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2592     // the same basic block, then we replace the select with Y, and the
2593     // condition of the select with false (if the cond value is in the same BB).
2594     // If the select has uses other than the div, this allows them to be
2595     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2596     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2597       if (ST->isNullValue()) {
2598         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2599         if (CondI && CondI->getParent() == I.getParent())
2600           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2601         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2602           I.setOperand(1, SI->getOperand(2));
2603         else
2604           UpdateValueUsesWith(SI, SI->getOperand(2));
2605         return &I;
2606       }
2607
2608     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2609     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2610       if (ST->isNullValue()) {
2611         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2612         if (CondI && CondI->getParent() == I.getParent())
2613           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2614         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2615           I.setOperand(1, SI->getOperand(1));
2616         else
2617           UpdateValueUsesWith(SI, SI->getOperand(1));
2618         return &I;
2619       }
2620   }
2621
2622   return 0;
2623 }
2624
2625 /// This function implements the transforms common to both integer division
2626 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2627 /// division instructions.
2628 /// @brief Common integer divide transforms
2629 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2630   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2631
2632   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2633   if (Op0 == Op1) {
2634     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2635       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2636       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2637       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2638     }
2639
2640     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2641     return ReplaceInstUsesWith(I, CI);
2642   }
2643   
2644   if (Instruction *Common = commonDivTransforms(I))
2645     return Common;
2646
2647   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2648     // div X, 1 == X
2649     if (RHS->equalsInt(1))
2650       return ReplaceInstUsesWith(I, Op0);
2651
2652     // (X / C1) / C2  -> X / (C1*C2)
2653     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2654       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2655         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2656           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2657             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2658           else 
2659             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2660                                           Multiply(RHS, LHSRHS));
2661         }
2662
2663     if (!RHS->isZero()) { // avoid X udiv 0
2664       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2665         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2666           return R;
2667       if (isa<PHINode>(Op0))
2668         if (Instruction *NV = FoldOpIntoPhi(I))
2669           return NV;
2670     }
2671   }
2672
2673   // 0 / X == 0, we don't need to preserve faults!
2674   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2675     if (LHS->equalsInt(0))
2676       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2677
2678   // It can't be division by zero, hence it must be division by one.
2679   if (I.getType() == Type::Int1Ty)
2680     return ReplaceInstUsesWith(I, Op0);
2681
2682   return 0;
2683 }
2684
2685 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2686   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2687
2688   // Handle the integer div common cases
2689   if (Instruction *Common = commonIDivTransforms(I))
2690     return Common;
2691
2692   // X udiv C^2 -> X >> C
2693   // Check to see if this is an unsigned division with an exact power of 2,
2694   // if so, convert to a right shift.
2695   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2696     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2697       return BinaryOperator::CreateLShr(Op0, 
2698                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2699   }
2700
2701   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2702   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2703     if (RHSI->getOpcode() == Instruction::Shl &&
2704         isa<ConstantInt>(RHSI->getOperand(0))) {
2705       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2706       if (C1.isPowerOf2()) {
2707         Value *N = RHSI->getOperand(1);
2708         const Type *NTy = N->getType();
2709         if (uint32_t C2 = C1.logBase2()) {
2710           Constant *C2V = ConstantInt::get(NTy, C2);
2711           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2712         }
2713         return BinaryOperator::CreateLShr(Op0, N);
2714       }
2715     }
2716   }
2717   
2718   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2719   // where C1&C2 are powers of two.
2720   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2721     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2722       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2723         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2724         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2725           // Compute the shift amounts
2726           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2727           // Construct the "on true" case of the select
2728           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2729           Instruction *TSI = BinaryOperator::CreateLShr(
2730                                                  Op0, TC, SI->getName()+".t");
2731           TSI = InsertNewInstBefore(TSI, I);
2732   
2733           // Construct the "on false" case of the select
2734           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2735           Instruction *FSI = BinaryOperator::CreateLShr(
2736                                                  Op0, FC, SI->getName()+".f");
2737           FSI = InsertNewInstBefore(FSI, I);
2738
2739           // construct the select instruction and return it.
2740           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2741         }
2742       }
2743   return 0;
2744 }
2745
2746 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2747   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2748
2749   // Handle the integer div common cases
2750   if (Instruction *Common = commonIDivTransforms(I))
2751     return Common;
2752
2753   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2754     // sdiv X, -1 == -X
2755     if (RHS->isAllOnesValue())
2756       return BinaryOperator::CreateNeg(Op0);
2757
2758     // -X/C -> X/-C
2759     if (Value *LHSNeg = dyn_castNegVal(Op0))
2760       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2761   }
2762
2763   // If the sign bits of both operands are zero (i.e. we can prove they are
2764   // unsigned inputs), turn this into a udiv.
2765   if (I.getType()->isInteger()) {
2766     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2767     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2768       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2769       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2770     }
2771   }      
2772   
2773   return 0;
2774 }
2775
2776 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2777   return commonDivTransforms(I);
2778 }
2779
2780 /// This function implements the transforms on rem instructions that work
2781 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2782 /// is used by the visitors to those instructions.
2783 /// @brief Transforms common to all three rem instructions
2784 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2785   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2786
2787   // 0 % X == 0 for integer, we don't need to preserve faults!
2788   if (Constant *LHS = dyn_cast<Constant>(Op0))
2789     if (LHS->isNullValue())
2790       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2791
2792   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2793     if (I.getType()->isFPOrFPVector())
2794       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2795     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2796   }
2797   if (isa<UndefValue>(Op1))
2798     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2799
2800   // Handle cases involving: rem X, (select Cond, Y, Z)
2801   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2802     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2803     // the same basic block, then we replace the select with Y, and the
2804     // condition of the select with false (if the cond value is in the same
2805     // BB).  If the select has uses other than the div, this allows them to be
2806     // simplified also.
2807     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2808       if (ST->isNullValue()) {
2809         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2810         if (CondI && CondI->getParent() == I.getParent())
2811           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2812         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2813           I.setOperand(1, SI->getOperand(2));
2814         else
2815           UpdateValueUsesWith(SI, SI->getOperand(2));
2816         return &I;
2817       }
2818     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2819     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2820       if (ST->isNullValue()) {
2821         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2822         if (CondI && CondI->getParent() == I.getParent())
2823           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2824         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2825           I.setOperand(1, SI->getOperand(1));
2826         else
2827           UpdateValueUsesWith(SI, SI->getOperand(1));
2828         return &I;
2829       }
2830   }
2831
2832   return 0;
2833 }
2834
2835 /// This function implements the transforms common to both integer remainder
2836 /// instructions (urem and srem). It is called by the visitors to those integer
2837 /// remainder instructions.
2838 /// @brief Common integer remainder transforms
2839 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2840   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2841
2842   if (Instruction *common = commonRemTransforms(I))
2843     return common;
2844
2845   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2846     // X % 0 == undef, we don't need to preserve faults!
2847     if (RHS->equalsInt(0))
2848       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2849     
2850     if (RHS->equalsInt(1))  // X % 1 == 0
2851       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2852
2853     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2854       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2855         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2856           return R;
2857       } else if (isa<PHINode>(Op0I)) {
2858         if (Instruction *NV = FoldOpIntoPhi(I))
2859           return NV;
2860       }
2861
2862       // See if we can fold away this rem instruction.
2863       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2864       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2865       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2866                                KnownZero, KnownOne))
2867         return &I;
2868     }
2869   }
2870
2871   return 0;
2872 }
2873
2874 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2875   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2876
2877   if (Instruction *common = commonIRemTransforms(I))
2878     return common;
2879   
2880   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2881     // X urem C^2 -> X and C
2882     // Check to see if this is an unsigned remainder with an exact power of 2,
2883     // if so, convert to a bitwise and.
2884     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2885       if (C->getValue().isPowerOf2())
2886         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2887   }
2888
2889   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2890     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2891     if (RHSI->getOpcode() == Instruction::Shl &&
2892         isa<ConstantInt>(RHSI->getOperand(0))) {
2893       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2894         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2895         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2896                                                                    "tmp"), I);
2897         return BinaryOperator::CreateAnd(Op0, Add);
2898       }
2899     }
2900   }
2901
2902   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2903   // where C1&C2 are powers of two.
2904   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2905     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2906       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2907         // STO == 0 and SFO == 0 handled above.
2908         if ((STO->getValue().isPowerOf2()) && 
2909             (SFO->getValue().isPowerOf2())) {
2910           Value *TrueAnd = InsertNewInstBefore(
2911             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2912           Value *FalseAnd = InsertNewInstBefore(
2913             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2914           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2915         }
2916       }
2917   }
2918   
2919   return 0;
2920 }
2921
2922 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2923   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924
2925   // Handle the integer rem common cases
2926   if (Instruction *common = commonIRemTransforms(I))
2927     return common;
2928   
2929   if (Value *RHSNeg = dyn_castNegVal(Op1))
2930     if (!isa<ConstantInt>(RHSNeg) || 
2931         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2932       // X % -Y -> X % Y
2933       AddUsesToWorkList(I);
2934       I.setOperand(1, RHSNeg);
2935       return &I;
2936     }
2937  
2938   // If the sign bits of both operands are zero (i.e. we can prove they are
2939   // unsigned inputs), turn this into a urem.
2940   if (I.getType()->isInteger()) {
2941     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2942     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2943       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2944       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2945     }
2946   }
2947
2948   return 0;
2949 }
2950
2951 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2952   return commonRemTransforms(I);
2953 }
2954
2955 // isOneBitSet - Return true if there is exactly one bit set in the specified
2956 // constant.
2957 static bool isOneBitSet(const ConstantInt *CI) {
2958   return CI->getValue().isPowerOf2();
2959 }
2960
2961 // isHighOnes - Return true if the constant is of the form 1+0+.
2962 // This is the same as lowones(~X).
2963 static bool isHighOnes(const ConstantInt *CI) {
2964   return (~CI->getValue() + 1).isPowerOf2();
2965 }
2966
2967 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2968 /// are carefully arranged to allow folding of expressions such as:
2969 ///
2970 ///      (A < B) | (A > B) --> (A != B)
2971 ///
2972 /// Note that this is only valid if the first and second predicates have the
2973 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2974 ///
2975 /// Three bits are used to represent the condition, as follows:
2976 ///   0  A > B
2977 ///   1  A == B
2978 ///   2  A < B
2979 ///
2980 /// <=>  Value  Definition
2981 /// 000     0   Always false
2982 /// 001     1   A >  B
2983 /// 010     2   A == B
2984 /// 011     3   A >= B
2985 /// 100     4   A <  B
2986 /// 101     5   A != B
2987 /// 110     6   A <= B
2988 /// 111     7   Always true
2989 ///  
2990 static unsigned getICmpCode(const ICmpInst *ICI) {
2991   switch (ICI->getPredicate()) {
2992     // False -> 0
2993   case ICmpInst::ICMP_UGT: return 1;  // 001
2994   case ICmpInst::ICMP_SGT: return 1;  // 001
2995   case ICmpInst::ICMP_EQ:  return 2;  // 010
2996   case ICmpInst::ICMP_UGE: return 3;  // 011
2997   case ICmpInst::ICMP_SGE: return 3;  // 011
2998   case ICmpInst::ICMP_ULT: return 4;  // 100
2999   case ICmpInst::ICMP_SLT: return 4;  // 100
3000   case ICmpInst::ICMP_NE:  return 5;  // 101
3001   case ICmpInst::ICMP_ULE: return 6;  // 110
3002   case ICmpInst::ICMP_SLE: return 6;  // 110
3003     // True -> 7
3004   default:
3005     assert(0 && "Invalid ICmp predicate!");
3006     return 0;
3007   }
3008 }
3009
3010 /// getICmpValue - This is the complement of getICmpCode, which turns an
3011 /// opcode and two operands into either a constant true or false, or a brand 
3012 /// new ICmp instruction. The sign is passed in to determine which kind
3013 /// of predicate to use in new icmp instructions.
3014 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3015   switch (code) {
3016   default: assert(0 && "Illegal ICmp code!");
3017   case  0: return ConstantInt::getFalse();
3018   case  1: 
3019     if (sign)
3020       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3021     else
3022       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3023   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3024   case  3: 
3025     if (sign)
3026       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3027     else
3028       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3029   case  4: 
3030     if (sign)
3031       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3032     else
3033       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3034   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3035   case  6: 
3036     if (sign)
3037       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3038     else
3039       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3040   case  7: return ConstantInt::getTrue();
3041   }
3042 }
3043
3044 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3045   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3046     (ICmpInst::isSignedPredicate(p1) && 
3047      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3048     (ICmpInst::isSignedPredicate(p2) && 
3049      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3050 }
3051
3052 namespace { 
3053 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3054 struct FoldICmpLogical {
3055   InstCombiner &IC;
3056   Value *LHS, *RHS;
3057   ICmpInst::Predicate pred;
3058   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3059     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3060       pred(ICI->getPredicate()) {}
3061   bool shouldApply(Value *V) const {
3062     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3063       if (PredicatesFoldable(pred, ICI->getPredicate()))
3064         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3065                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3066     return false;
3067   }
3068   Instruction *apply(Instruction &Log) const {
3069     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3070     if (ICI->getOperand(0) != LHS) {
3071       assert(ICI->getOperand(1) == LHS);
3072       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3073     }
3074
3075     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3076     unsigned LHSCode = getICmpCode(ICI);
3077     unsigned RHSCode = getICmpCode(RHSICI);
3078     unsigned Code;
3079     switch (Log.getOpcode()) {
3080     case Instruction::And: Code = LHSCode & RHSCode; break;
3081     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3082     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3083     default: assert(0 && "Illegal logical opcode!"); return 0;
3084     }
3085
3086     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3087                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3088       
3089     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3090     if (Instruction *I = dyn_cast<Instruction>(RV))
3091       return I;
3092     // Otherwise, it's a constant boolean value...
3093     return IC.ReplaceInstUsesWith(Log, RV);
3094   }
3095 };
3096 } // end anonymous namespace
3097
3098 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3099 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3100 // guaranteed to be a binary operator.
3101 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3102                                     ConstantInt *OpRHS,
3103                                     ConstantInt *AndRHS,
3104                                     BinaryOperator &TheAnd) {
3105   Value *X = Op->getOperand(0);
3106   Constant *Together = 0;
3107   if (!Op->isShift())
3108     Together = And(AndRHS, OpRHS);
3109
3110   switch (Op->getOpcode()) {
3111   case Instruction::Xor:
3112     if (Op->hasOneUse()) {
3113       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3114       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3115       InsertNewInstBefore(And, TheAnd);
3116       And->takeName(Op);
3117       return BinaryOperator::CreateXor(And, Together);
3118     }
3119     break;
3120   case Instruction::Or:
3121     if (Together == AndRHS) // (X | C) & C --> C
3122       return ReplaceInstUsesWith(TheAnd, AndRHS);
3123
3124     if (Op->hasOneUse() && Together != OpRHS) {
3125       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3126       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3127       InsertNewInstBefore(Or, TheAnd);
3128       Or->takeName(Op);
3129       return BinaryOperator::CreateAnd(Or, AndRHS);
3130     }
3131     break;
3132   case Instruction::Add:
3133     if (Op->hasOneUse()) {
3134       // Adding a one to a single bit bit-field should be turned into an XOR
3135       // of the bit.  First thing to check is to see if this AND is with a
3136       // single bit constant.
3137       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3138
3139       // If there is only one bit set...
3140       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3141         // Ok, at this point, we know that we are masking the result of the
3142         // ADD down to exactly one bit.  If the constant we are adding has
3143         // no bits set below this bit, then we can eliminate the ADD.
3144         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3145
3146         // Check to see if any bits below the one bit set in AndRHSV are set.
3147         if ((AddRHS & (AndRHSV-1)) == 0) {
3148           // If not, the only thing that can effect the output of the AND is
3149           // the bit specified by AndRHSV.  If that bit is set, the effect of
3150           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3151           // no effect.
3152           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3153             TheAnd.setOperand(0, X);
3154             return &TheAnd;
3155           } else {
3156             // Pull the XOR out of the AND.
3157             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3158             InsertNewInstBefore(NewAnd, TheAnd);
3159             NewAnd->takeName(Op);
3160             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3161           }
3162         }
3163       }
3164     }
3165     break;
3166
3167   case Instruction::Shl: {
3168     // We know that the AND will not produce any of the bits shifted in, so if
3169     // the anded constant includes them, clear them now!
3170     //
3171     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3172     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3173     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3174     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3175
3176     if (CI->getValue() == ShlMask) { 
3177     // Masking out bits that the shift already masks
3178       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3179     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3180       TheAnd.setOperand(1, CI);
3181       return &TheAnd;
3182     }
3183     break;
3184   }
3185   case Instruction::LShr:
3186   {
3187     // We know that the AND will not produce any of the bits shifted in, so if
3188     // the anded constant includes them, clear them now!  This only applies to
3189     // unsigned shifts, because a signed shr may bring in set bits!
3190     //
3191     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3192     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3193     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3194     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3195
3196     if (CI->getValue() == ShrMask) {   
3197     // Masking out bits that the shift already masks.
3198       return ReplaceInstUsesWith(TheAnd, Op);
3199     } else if (CI != AndRHS) {
3200       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3201       return &TheAnd;
3202     }
3203     break;
3204   }
3205   case Instruction::AShr:
3206     // Signed shr.
3207     // See if this is shifting in some sign extension, then masking it out
3208     // with an and.
3209     if (Op->hasOneUse()) {
3210       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3211       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3212       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3213       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3214       if (C == AndRHS) {          // Masking out bits shifted in.
3215         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3216         // Make the argument unsigned.
3217         Value *ShVal = Op->getOperand(0);
3218         ShVal = InsertNewInstBefore(
3219             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3220                                    Op->getName()), TheAnd);
3221         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3222       }
3223     }
3224     break;
3225   }
3226   return 0;
3227 }
3228
3229
3230 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3231 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3232 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3233 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3234 /// insert new instructions.
3235 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3236                                            bool isSigned, bool Inside, 
3237                                            Instruction &IB) {
3238   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3239             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3240          "Lo is not <= Hi in range emission code!");
3241     
3242   if (Inside) {
3243     if (Lo == Hi)  // Trivially false.
3244       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3245
3246     // V >= Min && V < Hi --> V < Hi
3247     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3248       ICmpInst::Predicate pred = (isSigned ? 
3249         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3250       return new ICmpInst(pred, V, Hi);
3251     }
3252
3253     // Emit V-Lo <u Hi-Lo
3254     Constant *NegLo = ConstantExpr::getNeg(Lo);
3255     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3256     InsertNewInstBefore(Add, IB);
3257     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3258     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3259   }
3260
3261   if (Lo == Hi)  // Trivially true.
3262     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3263
3264   // V < Min || V >= Hi -> V > Hi-1
3265   Hi = SubOne(cast<ConstantInt>(Hi));
3266   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3267     ICmpInst::Predicate pred = (isSigned ? 
3268         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3269     return new ICmpInst(pred, V, Hi);
3270   }
3271
3272   // Emit V-Lo >u Hi-1-Lo
3273   // Note that Hi has already had one subtracted from it, above.
3274   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3275   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3276   InsertNewInstBefore(Add, IB);
3277   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3278   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3279 }
3280
3281 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3282 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3283 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3284 // not, since all 1s are not contiguous.
3285 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3286   const APInt& V = Val->getValue();
3287   uint32_t BitWidth = Val->getType()->getBitWidth();
3288   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3289
3290   // look for the first zero bit after the run of ones
3291   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3292   // look for the first non-zero bit
3293   ME = V.getActiveBits(); 
3294   return true;
3295 }
3296
3297 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3298 /// where isSub determines whether the operator is a sub.  If we can fold one of
3299 /// the following xforms:
3300 /// 
3301 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3302 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3303 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3304 ///
3305 /// return (A +/- B).
3306 ///
3307 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3308                                         ConstantInt *Mask, bool isSub,
3309                                         Instruction &I) {
3310   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3311   if (!LHSI || LHSI->getNumOperands() != 2 ||
3312       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3313
3314   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3315
3316   switch (LHSI->getOpcode()) {
3317   default: return 0;
3318   case Instruction::And:
3319     if (And(N, Mask) == Mask) {
3320       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3321       if ((Mask->getValue().countLeadingZeros() + 
3322            Mask->getValue().countPopulation()) == 
3323           Mask->getValue().getBitWidth())
3324         break;
3325
3326       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3327       // part, we don't need any explicit masks to take them out of A.  If that
3328       // is all N is, ignore it.
3329       uint32_t MB = 0, ME = 0;
3330       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3331         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3332         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3333         if (MaskedValueIsZero(RHS, Mask))
3334           break;
3335       }
3336     }
3337     return 0;
3338   case Instruction::Or:
3339   case Instruction::Xor:
3340     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3341     if ((Mask->getValue().countLeadingZeros() + 
3342          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3343         && And(N, Mask)->isZero())
3344       break;
3345     return 0;
3346   }
3347   
3348   Instruction *New;
3349   if (isSub)
3350     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3351   else
3352     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3353   return InsertNewInstBefore(New, I);
3354 }
3355
3356 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3357   bool Changed = SimplifyCommutative(I);
3358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3359
3360   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3361     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3362
3363   // and X, X = X
3364   if (Op0 == Op1)
3365     return ReplaceInstUsesWith(I, Op1);
3366
3367   // See if we can simplify any instructions used by the instruction whose sole 
3368   // purpose is to compute bits we don't care about.
3369   if (!isa<VectorType>(I.getType())) {
3370     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3371     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3372     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3373                              KnownZero, KnownOne))
3374       return &I;
3375   } else {
3376     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3377       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3378         return ReplaceInstUsesWith(I, I.getOperand(0));
3379     } else if (isa<ConstantAggregateZero>(Op1)) {
3380       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3381     }
3382   }
3383   
3384   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3385     const APInt& AndRHSMask = AndRHS->getValue();
3386     APInt NotAndRHS(~AndRHSMask);
3387
3388     // Optimize a variety of ((val OP C1) & C2) combinations...
3389     if (isa<BinaryOperator>(Op0)) {
3390       Instruction *Op0I = cast<Instruction>(Op0);
3391       Value *Op0LHS = Op0I->getOperand(0);
3392       Value *Op0RHS = Op0I->getOperand(1);
3393       switch (Op0I->getOpcode()) {
3394       case Instruction::Xor:
3395       case Instruction::Or:
3396         // If the mask is only needed on one incoming arm, push it up.
3397         if (Op0I->hasOneUse()) {
3398           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3399             // Not masking anything out for the LHS, move to RHS.
3400             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3401                                                    Op0RHS->getName()+".masked");
3402             InsertNewInstBefore(NewRHS, I);
3403             return BinaryOperator::Create(
3404                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3405           }
3406           if (!isa<Constant>(Op0RHS) &&
3407               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3408             // Not masking anything out for the RHS, move to LHS.
3409             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3410                                                    Op0LHS->getName()+".masked");
3411             InsertNewInstBefore(NewLHS, I);
3412             return BinaryOperator::Create(
3413                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3414           }
3415         }
3416
3417         break;
3418       case Instruction::Add:
3419         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3420         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3421         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3422         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3423           return BinaryOperator::CreateAnd(V, AndRHS);
3424         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3425           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3426         break;
3427
3428       case Instruction::Sub:
3429         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3430         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3431         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3432         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3433           return BinaryOperator::CreateAnd(V, AndRHS);
3434
3435         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3436         // has 1's for all bits that the subtraction with A might affect.
3437         if (Op0I->hasOneUse()) {
3438           uint32_t BitWidth = AndRHSMask.getBitWidth();
3439           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3440           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3441
3442           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3443           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3444               MaskedValueIsZero(Op0LHS, Mask)) {
3445             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3446             InsertNewInstBefore(NewNeg, I);
3447             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3448           }
3449         }
3450         break;
3451
3452       case Instruction::Shl:
3453       case Instruction::LShr:
3454         // (1 << x) & 1 --> zext(x == 0)
3455         // (1 >> x) & 1 --> zext(x == 0)
3456         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3457           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3458                                            Constant::getNullValue(I.getType()));
3459           InsertNewInstBefore(NewICmp, I);
3460           return new ZExtInst(NewICmp, I.getType());
3461         }
3462         break;
3463       }
3464
3465       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3466         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3467           return Res;
3468     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3469       // If this is an integer truncation or change from signed-to-unsigned, and
3470       // if the source is an and/or with immediate, transform it.  This
3471       // frequently occurs for bitfield accesses.
3472       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3473         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3474             CastOp->getNumOperands() == 2)
3475           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3476             if (CastOp->getOpcode() == Instruction::And) {
3477               // Change: and (cast (and X, C1) to T), C2
3478               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3479               // This will fold the two constants together, which may allow 
3480               // other simplifications.
3481               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3482                 CastOp->getOperand(0), I.getType(), 
3483                 CastOp->getName()+".shrunk");
3484               NewCast = InsertNewInstBefore(NewCast, I);
3485               // trunc_or_bitcast(C1)&C2
3486               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3487               C3 = ConstantExpr::getAnd(C3, AndRHS);
3488               return BinaryOperator::CreateAnd(NewCast, C3);
3489             } else if (CastOp->getOpcode() == Instruction::Or) {
3490               // Change: and (cast (or X, C1) to T), C2
3491               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3492               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3493               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3494                 return ReplaceInstUsesWith(I, AndRHS);
3495             }
3496           }
3497       }
3498     }
3499
3500     // Try to fold constant and into select arguments.
3501     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3502       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3503         return R;
3504     if (isa<PHINode>(Op0))
3505       if (Instruction *NV = FoldOpIntoPhi(I))
3506         return NV;
3507   }
3508
3509   Value *Op0NotVal = dyn_castNotVal(Op0);
3510   Value *Op1NotVal = dyn_castNotVal(Op1);
3511
3512   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3513     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3514
3515   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3516   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3517     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3518                                                I.getName()+".demorgan");
3519     InsertNewInstBefore(Or, I);
3520     return BinaryOperator::CreateNot(Or);
3521   }
3522   
3523   {
3524     Value *A = 0, *B = 0, *C = 0, *D = 0;
3525     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3526       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3527         return ReplaceInstUsesWith(I, Op1);
3528     
3529       // (A|B) & ~(A&B) -> A^B
3530       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3531         if ((A == C && B == D) || (A == D && B == C))
3532           return BinaryOperator::CreateXor(A, B);
3533       }
3534     }
3535     
3536     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3537       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3538         return ReplaceInstUsesWith(I, Op0);
3539
3540       // ~(A&B) & (A|B) -> A^B
3541       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3542         if ((A == C && B == D) || (A == D && B == C))
3543           return BinaryOperator::CreateXor(A, B);
3544       }
3545     }
3546     
3547     if (Op0->hasOneUse() &&
3548         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3549       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3550         I.swapOperands();     // Simplify below
3551         std::swap(Op0, Op1);
3552       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3553         cast<BinaryOperator>(Op0)->swapOperands();
3554         I.swapOperands();     // Simplify below
3555         std::swap(Op0, Op1);
3556       }
3557     }
3558     if (Op1->hasOneUse() &&
3559         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3560       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3561         cast<BinaryOperator>(Op1)->swapOperands();
3562         std::swap(A, B);
3563       }
3564       if (A == Op0) {                                // A&(A^B) -> A & ~B
3565         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3566         InsertNewInstBefore(NotB, I);
3567         return BinaryOperator::CreateAnd(A, NotB);
3568       }
3569     }
3570   }
3571   
3572   
3573   { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3574     // where C is a power of 2
3575     Value *A, *B;
3576     ConstantInt *C1, *C2;
3577     ICmpInst::Predicate LHSCC, RHSCC;
3578     if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3579                         m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3580       if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3581           (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3582         Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3583         InsertNewInstBefore(NewOr, I);
3584         return new ICmpInst(LHSCC, NewOr, C1);
3585       }
3586   }
3587
3588   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3589     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3590     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3591       return R;
3592
3593     Value *LHSVal, *RHSVal;
3594     ConstantInt *LHSCst, *RHSCst;
3595     ICmpInst::Predicate LHSCC, RHSCC;
3596     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3597       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3598         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3599             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3600             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3601             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3602             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3603             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3604             
3605             // Don't try to fold ICMP_SLT + ICMP_ULT.
3606             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3607              ICmpInst::isSignedPredicate(LHSCC) == 
3608                  ICmpInst::isSignedPredicate(RHSCC))) {
3609           // Ensure that the larger constant is on the RHS.
3610           ICmpInst::Predicate GT;
3611           if (ICmpInst::isSignedPredicate(LHSCC) ||
3612               (ICmpInst::isEquality(LHSCC) && 
3613                ICmpInst::isSignedPredicate(RHSCC)))
3614             GT = ICmpInst::ICMP_SGT;
3615           else
3616             GT = ICmpInst::ICMP_UGT;
3617           
3618           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3619           ICmpInst *LHS = cast<ICmpInst>(Op0);
3620           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3621             std::swap(LHS, RHS);
3622             std::swap(LHSCst, RHSCst);
3623             std::swap(LHSCC, RHSCC);
3624           }
3625
3626           // At this point, we know we have have two icmp instructions
3627           // comparing a value against two constants and and'ing the result
3628           // together.  Because of the above check, we know that we only have
3629           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3630           // (from the FoldICmpLogical check above), that the two constants 
3631           // are not equal and that the larger constant is on the RHS
3632           assert(LHSCst != RHSCst && "Compares not folded above?");
3633
3634           switch (LHSCC) {
3635           default: assert(0 && "Unknown integer condition code!");
3636           case ICmpInst::ICMP_EQ:
3637             switch (RHSCC) {
3638             default: assert(0 && "Unknown integer condition code!");
3639             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3640             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3641             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3642               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3643             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3644             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3645             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3646               return ReplaceInstUsesWith(I, LHS);
3647             }
3648           case ICmpInst::ICMP_NE:
3649             switch (RHSCC) {
3650             default: assert(0 && "Unknown integer condition code!");
3651             case ICmpInst::ICMP_ULT:
3652               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3653                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3654               break;                        // (X != 13 & X u< 15) -> no change
3655             case ICmpInst::ICMP_SLT:
3656               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3657                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3658               break;                        // (X != 13 & X s< 15) -> no change
3659             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3660             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3661             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3662               return ReplaceInstUsesWith(I, RHS);
3663             case ICmpInst::ICMP_NE:
3664               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3665                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3666                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3667                                                       LHSVal->getName()+".off");
3668                 InsertNewInstBefore(Add, I);
3669                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3670                                     ConstantInt::get(Add->getType(), 1));
3671               }
3672               break;                        // (X != 13 & X != 15) -> no change
3673             }
3674             break;
3675           case ICmpInst::ICMP_ULT:
3676             switch (RHSCC) {
3677             default: assert(0 && "Unknown integer condition code!");
3678             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3679             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3680               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3681             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3682               break;
3683             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3684             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3685               return ReplaceInstUsesWith(I, LHS);
3686             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3687               break;
3688             }
3689             break;
3690           case ICmpInst::ICMP_SLT:
3691             switch (RHSCC) {
3692             default: assert(0 && "Unknown integer condition code!");
3693             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3694             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3695               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3696             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3697               break;
3698             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3699             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3700               return ReplaceInstUsesWith(I, LHS);
3701             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3702               break;
3703             }
3704             break;
3705           case ICmpInst::ICMP_UGT:
3706             switch (RHSCC) {
3707             default: assert(0 && "Unknown integer condition code!");
3708             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3709             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3710               return ReplaceInstUsesWith(I, RHS);
3711             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3712               break;
3713             case ICmpInst::ICMP_NE:
3714               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3715                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3716               break;                        // (X u> 13 & X != 15) -> no change
3717             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3718               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3719                                      true, I);
3720             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3721               break;
3722             }
3723             break;
3724           case ICmpInst::ICMP_SGT:
3725             switch (RHSCC) {
3726             default: assert(0 && "Unknown integer condition code!");
3727             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3728             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3729               return ReplaceInstUsesWith(I, RHS);
3730             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3731               break;
3732             case ICmpInst::ICMP_NE:
3733               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3734                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3735               break;                        // (X s> 13 & X != 15) -> no change
3736             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3737               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3738                                      true, I);
3739             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3740               break;
3741             }
3742             break;
3743           }
3744         }
3745   }
3746
3747   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3748   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3749     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3750       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3751         const Type *SrcTy = Op0C->getOperand(0)->getType();
3752         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3753             // Only do this if the casts both really cause code to be generated.
3754             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3755                               I.getType(), TD) &&
3756             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3757                               I.getType(), TD)) {
3758           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3759                                                          Op1C->getOperand(0),
3760                                                          I.getName());
3761           InsertNewInstBefore(NewOp, I);
3762           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3763         }
3764       }
3765     
3766   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3767   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3768     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3769       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3770           SI0->getOperand(1) == SI1->getOperand(1) &&
3771           (SI0->hasOneUse() || SI1->hasOneUse())) {
3772         Instruction *NewOp =
3773           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3774                                                         SI1->getOperand(0),
3775                                                         SI0->getName()), I);
3776         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3777                                       SI1->getOperand(1));
3778       }
3779   }
3780
3781   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3782   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3783     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3784       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3785           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3786         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3787           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3788             // If either of the constants are nans, then the whole thing returns
3789             // false.
3790             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3791               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3792             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3793                                 RHS->getOperand(0));
3794           }
3795     }
3796   }
3797
3798   return Changed ? &I : 0;
3799 }
3800
3801 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3802 /// in the result.  If it does, and if the specified byte hasn't been filled in
3803 /// yet, fill it in and return false.
3804 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3805   Instruction *I = dyn_cast<Instruction>(V);
3806   if (I == 0) return true;
3807
3808   // If this is an or instruction, it is an inner node of the bswap.
3809   if (I->getOpcode() == Instruction::Or)
3810     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3811            CollectBSwapParts(I->getOperand(1), ByteValues);
3812   
3813   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3814   // If this is a shift by a constant int, and it is "24", then its operand
3815   // defines a byte.  We only handle unsigned types here.
3816   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3817     // Not shifting the entire input by N-1 bytes?
3818     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3819         8*(ByteValues.size()-1))
3820       return true;
3821     
3822     unsigned DestNo;
3823     if (I->getOpcode() == Instruction::Shl) {
3824       // X << 24 defines the top byte with the lowest of the input bytes.
3825       DestNo = ByteValues.size()-1;
3826     } else {
3827       // X >>u 24 defines the low byte with the highest of the input bytes.
3828       DestNo = 0;
3829     }
3830     
3831     // If the destination byte value is already defined, the values are or'd
3832     // together, which isn't a bswap (unless it's an or of the same bits).
3833     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3834       return true;
3835     ByteValues[DestNo] = I->getOperand(0);
3836     return false;
3837   }
3838   
3839   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3840   // don't have this.
3841   Value *Shift = 0, *ShiftLHS = 0;
3842   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3843   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3844       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3845     return true;
3846   Instruction *SI = cast<Instruction>(Shift);
3847
3848   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3849   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3850       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3851     return true;
3852   
3853   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3854   unsigned DestByte;
3855   if (AndAmt->getValue().getActiveBits() > 64)
3856     return true;
3857   uint64_t AndAmtVal = AndAmt->getZExtValue();
3858   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3859     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3860       break;
3861   // Unknown mask for bswap.
3862   if (DestByte == ByteValues.size()) return true;
3863   
3864   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3865   unsigned SrcByte;
3866   if (SI->getOpcode() == Instruction::Shl)
3867     SrcByte = DestByte - ShiftBytes;
3868   else
3869     SrcByte = DestByte + ShiftBytes;
3870   
3871   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3872   if (SrcByte != ByteValues.size()-DestByte-1)
3873     return true;
3874   
3875   // If the destination byte value is already defined, the values are or'd
3876   // together, which isn't a bswap (unless it's an or of the same bits).
3877   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3878     return true;
3879   ByteValues[DestByte] = SI->getOperand(0);
3880   return false;
3881 }
3882
3883 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3884 /// If so, insert the new bswap intrinsic and return it.
3885 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3886   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3887   if (!ITy || ITy->getBitWidth() % 16) 
3888     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3889   
3890   /// ByteValues - For each byte of the result, we keep track of which value
3891   /// defines each byte.
3892   SmallVector<Value*, 8> ByteValues;
3893   ByteValues.resize(ITy->getBitWidth()/8);
3894     
3895   // Try to find all the pieces corresponding to the bswap.
3896   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3897       CollectBSwapParts(I.getOperand(1), ByteValues))
3898     return 0;
3899   
3900   // Check to see if all of the bytes come from the same value.
3901   Value *V = ByteValues[0];
3902   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3903   
3904   // Check to make sure that all of the bytes come from the same value.
3905   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3906     if (ByteValues[i] != V)
3907       return 0;
3908   const Type *Tys[] = { ITy };
3909   Module *M = I.getParent()->getParent()->getParent();
3910   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3911   return CallInst::Create(F, V);
3912 }
3913
3914
3915 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3916   bool Changed = SimplifyCommutative(I);
3917   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3918
3919   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3920     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3921
3922   // or X, X = X
3923   if (Op0 == Op1)
3924     return ReplaceInstUsesWith(I, Op0);
3925
3926   // See if we can simplify any instructions used by the instruction whose sole 
3927   // purpose is to compute bits we don't care about.
3928   if (!isa<VectorType>(I.getType())) {
3929     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3930     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3931     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3932                              KnownZero, KnownOne))
3933       return &I;
3934   } else if (isa<ConstantAggregateZero>(Op1)) {
3935     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3936   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3937     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3938       return ReplaceInstUsesWith(I, I.getOperand(1));
3939   }
3940     
3941
3942   
3943   // or X, -1 == -1
3944   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3945     ConstantInt *C1 = 0; Value *X = 0;
3946     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3947     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3948       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3949       InsertNewInstBefore(Or, I);
3950       Or->takeName(Op0);
3951       return BinaryOperator::CreateAnd(Or, 
3952                ConstantInt::get(RHS->getValue() | C1->getValue()));
3953     }
3954
3955     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3956     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3957       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3958       InsertNewInstBefore(Or, I);
3959       Or->takeName(Op0);
3960       return BinaryOperator::CreateXor(Or,
3961                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3962     }
3963
3964     // Try to fold constant and into select arguments.
3965     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3966       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3967         return R;
3968     if (isa<PHINode>(Op0))
3969       if (Instruction *NV = FoldOpIntoPhi(I))
3970         return NV;
3971   }
3972
3973   Value *A = 0, *B = 0;
3974   ConstantInt *C1 = 0, *C2 = 0;
3975
3976   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3977     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3978       return ReplaceInstUsesWith(I, Op1);
3979   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3980     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3981       return ReplaceInstUsesWith(I, Op0);
3982
3983   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3984   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3985   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3986       match(Op1, m_Or(m_Value(), m_Value())) ||
3987       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3988        match(Op1, m_Shift(m_Value(), m_Value())))) {
3989     if (Instruction *BSwap = MatchBSwap(I))
3990       return BSwap;
3991   }
3992   
3993   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3994   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3995       MaskedValueIsZero(Op1, C1->getValue())) {
3996     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3997     InsertNewInstBefore(NOr, I);
3998     NOr->takeName(Op0);
3999     return BinaryOperator::CreateXor(NOr, C1);
4000   }
4001
4002   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4003   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4004       MaskedValueIsZero(Op0, C1->getValue())) {
4005     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4006     InsertNewInstBefore(NOr, I);
4007     NOr->takeName(Op0);
4008     return BinaryOperator::CreateXor(NOr, C1);
4009   }
4010
4011   // (A & C)|(B & D)
4012   Value *C = 0, *D = 0;
4013   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4014       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4015     Value *V1 = 0, *V2 = 0, *V3 = 0;
4016     C1 = dyn_cast<ConstantInt>(C);
4017     C2 = dyn_cast<ConstantInt>(D);
4018     if (C1 && C2) {  // (A & C1)|(B & C2)
4019       // If we have: ((V + N) & C1) | (V & C2)
4020       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4021       // replace with V+N.
4022       if (C1->getValue() == ~C2->getValue()) {
4023         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4024             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4025           // Add commutes, try both ways.
4026           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4027             return ReplaceInstUsesWith(I, A);
4028           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4029             return ReplaceInstUsesWith(I, A);
4030         }
4031         // Or commutes, try both ways.
4032         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4033             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4034           // Add commutes, try both ways.
4035           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4036             return ReplaceInstUsesWith(I, B);
4037           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4038             return ReplaceInstUsesWith(I, B);
4039         }
4040       }
4041       V1 = 0; V2 = 0; V3 = 0;
4042     }
4043     
4044     // Check to see if we have any common things being and'ed.  If so, find the
4045     // terms for V1 & (V2|V3).
4046     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4047       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4048         V1 = A, V2 = C, V3 = D;
4049       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4050         V1 = A, V2 = B, V3 = C;
4051       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4052         V1 = C, V2 = A, V3 = D;
4053       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4054         V1 = C, V2 = A, V3 = B;
4055       
4056       if (V1) {
4057         Value *Or =
4058           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4059         return BinaryOperator::CreateAnd(V1, Or);
4060       }
4061     }
4062   }
4063   
4064   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4065   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4066     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4067       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4068           SI0->getOperand(1) == SI1->getOperand(1) &&
4069           (SI0->hasOneUse() || SI1->hasOneUse())) {
4070         Instruction *NewOp =
4071         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4072                                                      SI1->getOperand(0),
4073                                                      SI0->getName()), I);
4074         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4075                                       SI1->getOperand(1));
4076       }
4077   }
4078
4079   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4080     if (A == Op1)   // ~A | A == -1
4081       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4082   } else {
4083     A = 0;
4084   }
4085   // Note, A is still live here!
4086   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4087     if (Op0 == B)
4088       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4089
4090     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4091     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4092       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4093                                               I.getName()+".demorgan"), I);
4094       return BinaryOperator::CreateNot(And);
4095     }
4096   }
4097
4098   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4099   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4100     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4101       return R;
4102
4103     Value *LHSVal, *RHSVal;
4104     ConstantInt *LHSCst, *RHSCst;
4105     ICmpInst::Predicate LHSCC, RHSCC;
4106     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4107       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4108         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4109             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4110             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4111             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4112             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4113             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4114             // We can't fold (ugt x, C) | (sgt x, C2).
4115             PredicatesFoldable(LHSCC, RHSCC)) {
4116           // Ensure that the larger constant is on the RHS.
4117           ICmpInst *LHS = cast<ICmpInst>(Op0);
4118           bool NeedsSwap;
4119           if (ICmpInst::isSignedPredicate(LHSCC))
4120             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4121           else
4122             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4123             
4124           if (NeedsSwap) {
4125             std::swap(LHS, RHS);
4126             std::swap(LHSCst, RHSCst);
4127             std::swap(LHSCC, RHSCC);
4128           }
4129
4130           // At this point, we know we have have two icmp instructions
4131           // comparing a value against two constants and or'ing the result
4132           // together.  Because of the above check, we know that we only have
4133           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4134           // FoldICmpLogical check above), that the two constants are not
4135           // equal.
4136           assert(LHSCst != RHSCst && "Compares not folded above?");
4137
4138           switch (LHSCC) {
4139           default: assert(0 && "Unknown integer condition code!");
4140           case ICmpInst::ICMP_EQ:
4141             switch (RHSCC) {
4142             default: assert(0 && "Unknown integer condition code!");
4143             case ICmpInst::ICMP_EQ:
4144               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4145                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4146                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4147                                                       LHSVal->getName()+".off");
4148                 InsertNewInstBefore(Add, I);
4149                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4150                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4151               }
4152               break;                         // (X == 13 | X == 15) -> no change
4153             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4154             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4155               break;
4156             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4157             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4158             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4159               return ReplaceInstUsesWith(I, RHS);
4160             }
4161             break;
4162           case ICmpInst::ICMP_NE:
4163             switch (RHSCC) {
4164             default: assert(0 && "Unknown integer condition code!");
4165             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4166             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4167             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4168               return ReplaceInstUsesWith(I, LHS);
4169             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4170             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4171             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4172               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4173             }
4174             break;
4175           case ICmpInst::ICMP_ULT:
4176             switch (RHSCC) {
4177             default: assert(0 && "Unknown integer condition code!");
4178             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4179               break;
4180             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4181               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4182               // this can cause overflow.
4183               if (RHSCst->isMaxValue(false))
4184                 return ReplaceInstUsesWith(I, LHS);
4185               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4186                                      false, I);
4187             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4188               break;
4189             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4190             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4191               return ReplaceInstUsesWith(I, RHS);
4192             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4193               break;
4194             }
4195             break;
4196           case ICmpInst::ICMP_SLT:
4197             switch (RHSCC) {
4198             default: assert(0 && "Unknown integer condition code!");
4199             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4200               break;
4201             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4202               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4203               // this can cause overflow.
4204               if (RHSCst->isMaxValue(true))
4205                 return ReplaceInstUsesWith(I, LHS);
4206               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4207                                      false, I);
4208             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4209               break;
4210             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4211             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4212               return ReplaceInstUsesWith(I, RHS);
4213             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4214               break;
4215             }
4216             break;
4217           case ICmpInst::ICMP_UGT:
4218             switch (RHSCC) {
4219             default: assert(0 && "Unknown integer condition code!");
4220             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4221             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4222               return ReplaceInstUsesWith(I, LHS);
4223             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4224               break;
4225             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4226             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4227               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4228             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4229               break;
4230             }
4231             break;
4232           case ICmpInst::ICMP_SGT:
4233             switch (RHSCC) {
4234             default: assert(0 && "Unknown integer condition code!");
4235             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4236             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4237               return ReplaceInstUsesWith(I, LHS);
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) -> true
4241             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4242               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4243             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4244               break;
4245             }
4246             break;
4247           }
4248         }
4249   }
4250     
4251   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4252   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4253     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4254       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4255         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4256             !isa<ICmpInst>(Op1C->getOperand(0))) {
4257           const Type *SrcTy = Op0C->getOperand(0)->getType();
4258           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4259               // Only do this if the casts both really cause code to be
4260               // generated.
4261               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4262                                 I.getType(), TD) &&
4263               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4264                                 I.getType(), TD)) {
4265             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4266                                                           Op1C->getOperand(0),
4267                                                           I.getName());
4268             InsertNewInstBefore(NewOp, I);
4269             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4270           }
4271         }
4272       }
4273   }
4274   
4275     
4276   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4277   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4278     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4279       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4280           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4281           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4282         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4283           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4284             // If either of the constants are nans, then the whole thing returns
4285             // true.
4286             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4287               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4288             
4289             // Otherwise, no need to compare the two constants, compare the
4290             // rest.
4291             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4292                                 RHS->getOperand(0));
4293           }
4294     }
4295   }
4296
4297   return Changed ? &I : 0;
4298 }
4299
4300 namespace {
4301
4302 // XorSelf - Implements: X ^ X --> 0
4303 struct XorSelf {
4304   Value *RHS;
4305   XorSelf(Value *rhs) : RHS(rhs) {}
4306   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4307   Instruction *apply(BinaryOperator &Xor) const {
4308     return &Xor;
4309   }
4310 };
4311
4312 }
4313
4314 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4315   bool Changed = SimplifyCommutative(I);
4316   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4317
4318   if (isa<UndefValue>(Op1)) {
4319     if (isa<UndefValue>(Op0))
4320       // Handle undef ^ undef -> 0 special case. This is a common
4321       // idiom (misuse).
4322       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4323     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4324   }
4325
4326   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4327   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4328     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4329     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4330   }
4331   
4332   // See if we can simplify any instructions used by the instruction whose sole 
4333   // purpose is to compute bits we don't care about.
4334   if (!isa<VectorType>(I.getType())) {
4335     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4336     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4337     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4338                              KnownZero, KnownOne))
4339       return &I;
4340   } else if (isa<ConstantAggregateZero>(Op1)) {
4341     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4342   }
4343
4344   // Is this a ~ operation?
4345   if (Value *NotOp = dyn_castNotVal(&I)) {
4346     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4347     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4348     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4349       if (Op0I->getOpcode() == Instruction::And || 
4350           Op0I->getOpcode() == Instruction::Or) {
4351         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4352         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4353           Instruction *NotY =
4354             BinaryOperator::CreateNot(Op0I->getOperand(1),
4355                                       Op0I->getOperand(1)->getName()+".not");
4356           InsertNewInstBefore(NotY, I);
4357           if (Op0I->getOpcode() == Instruction::And)
4358             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4359           else
4360             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4361         }
4362       }
4363     }
4364   }
4365   
4366   
4367   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4368     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4369     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4370       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4371         return new ICmpInst(ICI->getInversePredicate(),
4372                             ICI->getOperand(0), ICI->getOperand(1));
4373
4374       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4375         return new FCmpInst(FCI->getInversePredicate(),
4376                             FCI->getOperand(0), FCI->getOperand(1));
4377     }
4378
4379     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4380     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4381       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4382         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4383           Instruction::CastOps Opcode = Op0C->getOpcode();
4384           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4385             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4386                                              Op0C->getDestTy())) {
4387               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4388                                      CI->getOpcode(), CI->getInversePredicate(),
4389                                      CI->getOperand(0), CI->getOperand(1)), I);
4390               NewCI->takeName(CI);
4391               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4392             }
4393           }
4394         }
4395       }
4396     }
4397
4398     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4399       // ~(c-X) == X-c-1 == X+(-c-1)
4400       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4401         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4402           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4403           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4404                                               ConstantInt::get(I.getType(), 1));
4405           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4406         }
4407           
4408       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4409         if (Op0I->getOpcode() == Instruction::Add) {
4410           // ~(X-c) --> (-c-1)-X
4411           if (RHS->isAllOnesValue()) {
4412             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4413             return BinaryOperator::CreateSub(
4414                            ConstantExpr::getSub(NegOp0CI,
4415                                              ConstantInt::get(I.getType(), 1)),
4416                                           Op0I->getOperand(0));
4417           } else if (RHS->getValue().isSignBit()) {
4418             // (X + C) ^ signbit -> (X + C + signbit)
4419             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4420             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4421
4422           }
4423         } else if (Op0I->getOpcode() == Instruction::Or) {
4424           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4425           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4426             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4427             // Anything in both C1 and C2 is known to be zero, remove it from
4428             // NewRHS.
4429             Constant *CommonBits = And(Op0CI, RHS);
4430             NewRHS = ConstantExpr::getAnd(NewRHS, 
4431                                           ConstantExpr::getNot(CommonBits));
4432             AddToWorkList(Op0I);
4433             I.setOperand(0, Op0I->getOperand(0));
4434             I.setOperand(1, NewRHS);
4435             return &I;
4436           }
4437         }
4438       }
4439     }
4440
4441     // Try to fold constant and into select arguments.
4442     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4443       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4444         return R;
4445     if (isa<PHINode>(Op0))
4446       if (Instruction *NV = FoldOpIntoPhi(I))
4447         return NV;
4448   }
4449
4450   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4451     if (X == Op1)
4452       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4453
4454   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4455     if (X == Op0)
4456       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4457
4458   
4459   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4460   if (Op1I) {
4461     Value *A, *B;
4462     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4463       if (A == Op0) {              // B^(B|A) == (A|B)^B
4464         Op1I->swapOperands();
4465         I.swapOperands();
4466         std::swap(Op0, Op1);
4467       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4468         I.swapOperands();     // Simplified below.
4469         std::swap(Op0, Op1);
4470       }
4471     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4472       if (Op0 == A)                                          // A^(A^B) == B
4473         return ReplaceInstUsesWith(I, B);
4474       else if (Op0 == B)                                     // A^(B^A) == B
4475         return ReplaceInstUsesWith(I, A);
4476     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4477       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4478         Op1I->swapOperands();
4479         std::swap(A, B);
4480       }
4481       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4482         I.swapOperands();     // Simplified below.
4483         std::swap(Op0, Op1);
4484       }
4485     }
4486   }
4487   
4488   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4489   if (Op0I) {
4490     Value *A, *B;
4491     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4492       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4493         std::swap(A, B);
4494       if (B == Op1) {                                // (A|B)^B == A & ~B
4495         Instruction *NotB =
4496           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4497         return BinaryOperator::CreateAnd(A, NotB);
4498       }
4499     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4500       if (Op1 == A)                                          // (A^B)^A == B
4501         return ReplaceInstUsesWith(I, B);
4502       else if (Op1 == B)                                     // (B^A)^A == B
4503         return ReplaceInstUsesWith(I, A);
4504     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4505       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4506         std::swap(A, B);
4507       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4508           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4509         Instruction *N =
4510           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4511         return BinaryOperator::CreateAnd(N, Op1);
4512       }
4513     }
4514   }
4515   
4516   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4517   if (Op0I && Op1I && Op0I->isShift() && 
4518       Op0I->getOpcode() == Op1I->getOpcode() && 
4519       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4520       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4521     Instruction *NewOp =
4522       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4523                                                     Op1I->getOperand(0),
4524                                                     Op0I->getName()), I);
4525     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4526                                   Op1I->getOperand(1));
4527   }
4528     
4529   if (Op0I && Op1I) {
4530     Value *A, *B, *C, *D;
4531     // (A & B)^(A | B) -> A ^ B
4532     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4533         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4534       if ((A == C && B == D) || (A == D && B == C)) 
4535         return BinaryOperator::CreateXor(A, B);
4536     }
4537     // (A | B)^(A & B) -> A ^ B
4538     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4539         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4540       if ((A == C && B == D) || (A == D && B == C)) 
4541         return BinaryOperator::CreateXor(A, B);
4542     }
4543     
4544     // (A & B)^(C & D)
4545     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4546         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4547         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4548       // (X & Y)^(X & Y) -> (Y^Z) & X
4549       Value *X = 0, *Y = 0, *Z = 0;
4550       if (A == C)
4551         X = A, Y = B, Z = D;
4552       else if (A == D)
4553         X = A, Y = B, Z = C;
4554       else if (B == C)
4555         X = B, Y = A, Z = D;
4556       else if (B == D)
4557         X = B, Y = A, Z = C;
4558       
4559       if (X) {
4560         Instruction *NewOp =
4561         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4562         return BinaryOperator::CreateAnd(NewOp, X);
4563       }
4564     }
4565   }
4566     
4567   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4568   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4569     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4570       return R;
4571
4572   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4573   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4574     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4575       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4576         const Type *SrcTy = Op0C->getOperand(0)->getType();
4577         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4578             // Only do this if the casts both really cause code to be generated.
4579             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4580                               I.getType(), TD) &&
4581             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4582                               I.getType(), TD)) {
4583           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4584                                                          Op1C->getOperand(0),
4585                                                          I.getName());
4586           InsertNewInstBefore(NewOp, I);
4587           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4588         }
4589       }
4590   }
4591
4592   return Changed ? &I : 0;
4593 }
4594
4595 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4596 /// overflowed for this type.
4597 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4598                             ConstantInt *In2, bool IsSigned = false) {
4599   Result = cast<ConstantInt>(Add(In1, In2));
4600
4601   if (IsSigned)
4602     if (In2->getValue().isNegative())
4603       return Result->getValue().sgt(In1->getValue());
4604     else
4605       return Result->getValue().slt(In1->getValue());
4606   else
4607     return Result->getValue().ult(In1->getValue());
4608 }
4609
4610 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4611 /// code necessary to compute the offset from the base pointer (without adding
4612 /// in the base pointer).  Return the result as a signed integer of intptr size.
4613 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4614   TargetData &TD = IC.getTargetData();
4615   gep_type_iterator GTI = gep_type_begin(GEP);
4616   const Type *IntPtrTy = TD.getIntPtrType();
4617   Value *Result = Constant::getNullValue(IntPtrTy);
4618
4619   // Build a mask for high order bits.
4620   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4621   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4622
4623   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4624        ++i, ++GTI) {
4625     Value *Op = *i;
4626     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4627     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4628       if (OpC->isZero()) continue;
4629       
4630       // Handle a struct index, which adds its field offset to the pointer.
4631       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4632         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4633         
4634         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4635           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4636         else
4637           Result = IC.InsertNewInstBefore(
4638                    BinaryOperator::CreateAdd(Result,
4639                                              ConstantInt::get(IntPtrTy, Size),
4640                                              GEP->getName()+".offs"), I);
4641         continue;
4642       }
4643       
4644       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4645       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4646       Scale = ConstantExpr::getMul(OC, Scale);
4647       if (Constant *RC = dyn_cast<Constant>(Result))
4648         Result = ConstantExpr::getAdd(RC, Scale);
4649       else {
4650         // Emit an add instruction.
4651         Result = IC.InsertNewInstBefore(
4652            BinaryOperator::CreateAdd(Result, Scale,
4653                                      GEP->getName()+".offs"), I);
4654       }
4655       continue;
4656     }
4657     // Convert to correct type.
4658     if (Op->getType() != IntPtrTy) {
4659       if (Constant *OpC = dyn_cast<Constant>(Op))
4660         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4661       else
4662         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4663                                                  Op->getName()+".c"), I);
4664     }
4665     if (Size != 1) {
4666       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4667       if (Constant *OpC = dyn_cast<Constant>(Op))
4668         Op = ConstantExpr::getMul(OpC, Scale);
4669       else    // We'll let instcombine(mul) convert this to a shl if possible.
4670         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4671                                                   GEP->getName()+".idx"), I);
4672     }
4673
4674     // Emit an add instruction.
4675     if (isa<Constant>(Op) && isa<Constant>(Result))
4676       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4677                                     cast<Constant>(Result));
4678     else
4679       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4680                                                   GEP->getName()+".offs"), I);
4681   }
4682   return Result;
4683 }
4684
4685
4686 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4687 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4688 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4689 /// complex, and scales are involved.  The above expression would also be legal
4690 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4691 /// later form is less amenable to optimization though, and we are allowed to
4692 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4693 ///
4694 /// If we can't emit an optimized form for this expression, this returns null.
4695 /// 
4696 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4697                                           InstCombiner &IC) {
4698   TargetData &TD = IC.getTargetData();
4699   gep_type_iterator GTI = gep_type_begin(GEP);
4700
4701   // Check to see if this gep only has a single variable index.  If so, and if
4702   // any constant indices are a multiple of its scale, then we can compute this
4703   // in terms of the scale of the variable index.  For example, if the GEP
4704   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4705   // because the expression will cross zero at the same point.
4706   unsigned i, e = GEP->getNumOperands();
4707   int64_t Offset = 0;
4708   for (i = 1; i != e; ++i, ++GTI) {
4709     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4710       // Compute the aggregate offset of constant indices.
4711       if (CI->isZero()) continue;
4712
4713       // Handle a struct index, which adds its field offset to the pointer.
4714       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4715         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4716       } else {
4717         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4718         Offset += Size*CI->getSExtValue();
4719       }
4720     } else {
4721       // Found our variable index.
4722       break;
4723     }
4724   }
4725   
4726   // If there are no variable indices, we must have a constant offset, just
4727   // evaluate it the general way.
4728   if (i == e) return 0;
4729   
4730   Value *VariableIdx = GEP->getOperand(i);
4731   // Determine the scale factor of the variable element.  For example, this is
4732   // 4 if the variable index is into an array of i32.
4733   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4734   
4735   // Verify that there are no other variable indices.  If so, emit the hard way.
4736   for (++i, ++GTI; i != e; ++i, ++GTI) {
4737     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4738     if (!CI) return 0;
4739    
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   }
4751   
4752   // Okay, we know we have a single variable index, which must be a
4753   // pointer/array/vector index.  If there is no offset, life is simple, return
4754   // the index.
4755   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4756   if (Offset == 0) {
4757     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4758     // we don't need to bother extending: the extension won't affect where the
4759     // computation crosses zero.
4760     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4761       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4762                                   VariableIdx->getNameStart(), &I);
4763     return VariableIdx;
4764   }
4765   
4766   // Otherwise, there is an index.  The computation we will do will be modulo
4767   // the pointer size, so get it.
4768   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4769   
4770   Offset &= PtrSizeMask;
4771   VariableScale &= PtrSizeMask;
4772
4773   // To do this transformation, any constant index must be a multiple of the
4774   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4775   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4776   // multiple of the variable scale.
4777   int64_t NewOffs = Offset / (int64_t)VariableScale;
4778   if (Offset != NewOffs*(int64_t)VariableScale)
4779     return 0;
4780
4781   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4782   const Type *IntPtrTy = TD.getIntPtrType();
4783   if (VariableIdx->getType() != IntPtrTy)
4784     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4785                                               true /*SExt*/, 
4786                                               VariableIdx->getNameStart(), &I);
4787   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4788   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4789 }
4790
4791
4792 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4793 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4794 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4795                                        ICmpInst::Predicate Cond,
4796                                        Instruction &I) {
4797   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4798
4799   // Look through bitcasts.
4800   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4801     RHS = BCI->getOperand(0);
4802
4803   Value *PtrBase = GEPLHS->getOperand(0);
4804   if (PtrBase == RHS) {
4805     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4806     // This transformation (ignoring the base and scales) is valid because we
4807     // know pointers can't overflow.  See if we can output an optimized form.
4808     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4809     
4810     // If not, synthesize the offset the hard way.
4811     if (Offset == 0)
4812       Offset = EmitGEPOffset(GEPLHS, I, *this);
4813     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4814                         Constant::getNullValue(Offset->getType()));
4815   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4816     // If the base pointers are different, but the indices are the same, just
4817     // compare the base pointer.
4818     if (PtrBase != GEPRHS->getOperand(0)) {
4819       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4820       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4821                         GEPRHS->getOperand(0)->getType();
4822       if (IndicesTheSame)
4823         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4824           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4825             IndicesTheSame = false;
4826             break;
4827           }
4828
4829       // If all indices are the same, just compare the base pointers.
4830       if (IndicesTheSame)
4831         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4832                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4833
4834       // Otherwise, the base pointers are different and the indices are
4835       // different, bail out.
4836       return 0;
4837     }
4838
4839     // If one of the GEPs has all zero indices, recurse.
4840     bool AllZeros = true;
4841     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4842       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4843           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4844         AllZeros = false;
4845         break;
4846       }
4847     if (AllZeros)
4848       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4849                           ICmpInst::getSwappedPredicate(Cond), I);
4850
4851     // If the other GEP has all zero indices, recurse.
4852     AllZeros = true;
4853     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4854       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4855           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4856         AllZeros = false;
4857         break;
4858       }
4859     if (AllZeros)
4860       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4861
4862     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4863       // If the GEPs only differ by one index, compare it.
4864       unsigned NumDifferences = 0;  // Keep track of # differences.
4865       unsigned DiffOperand = 0;     // The operand that differs.
4866       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4867         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4868           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4869                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4870             // Irreconcilable differences.
4871             NumDifferences = 2;
4872             break;
4873           } else {
4874             if (NumDifferences++) break;
4875             DiffOperand = i;
4876           }
4877         }
4878
4879       if (NumDifferences == 0)   // SAME GEP?
4880         return ReplaceInstUsesWith(I, // No comparison is needed here.
4881                                    ConstantInt::get(Type::Int1Ty,
4882                                              ICmpInst::isTrueWhenEqual(Cond)));
4883
4884       else if (NumDifferences == 1) {
4885         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4886         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4887         // Make sure we do a signed comparison here.
4888         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4889       }
4890     }
4891
4892     // Only lower this if the icmp is the only user of the GEP or if we expect
4893     // the result to fold to a constant!
4894     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4895         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4896       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4897       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4898       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4899       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4900     }
4901   }
4902   return 0;
4903 }
4904
4905 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4906 ///
4907 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4908                                                 Instruction *LHSI,
4909                                                 Constant *RHSC) {
4910   if (!isa<ConstantFP>(RHSC)) return 0;
4911   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4912   
4913   // Get the width of the mantissa.  We don't want to hack on conversions that
4914   // might lose information from the integer, e.g. "i64 -> float"
4915   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4916   if (MantissaWidth == -1) return 0;  // Unknown.
4917   
4918   // Check to see that the input is converted from an integer type that is small
4919   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4920   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4921   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4922   
4923   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4924   if (isa<UIToFPInst>(LHSI))
4925     ++InputSize;
4926   
4927   // If the conversion would lose info, don't hack on this.
4928   if ((int)InputSize > MantissaWidth)
4929     return 0;
4930   
4931   // Otherwise, we can potentially simplify the comparison.  We know that it
4932   // will always come through as an integer value and we know the constant is
4933   // not a NAN (it would have been previously simplified).
4934   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4935   
4936   ICmpInst::Predicate Pred;
4937   switch (I.getPredicate()) {
4938   default: assert(0 && "Unexpected predicate!");
4939   case FCmpInst::FCMP_UEQ:
4940   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4941   case FCmpInst::FCMP_UGT:
4942   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4943   case FCmpInst::FCMP_UGE:
4944   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4945   case FCmpInst::FCMP_ULT:
4946   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4947   case FCmpInst::FCMP_ULE:
4948   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4949   case FCmpInst::FCMP_UNE:
4950   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4951   case FCmpInst::FCMP_ORD:
4952     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4953   case FCmpInst::FCMP_UNO:
4954     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4955   }
4956   
4957   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4958   
4959   // Now we know that the APFloat is a normal number, zero or inf.
4960   
4961   // See if the FP constant is too large for the integer.  For example,
4962   // comparing an i8 to 300.0.
4963   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4964   
4965   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4966   // and large values. 
4967   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4968   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4969                         APFloat::rmNearestTiesToEven);
4970   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4971     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4972         Pred == ICmpInst::ICMP_SLE)
4973       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4975   }
4976   
4977   // See if the RHS value is < SignedMin.
4978   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4979   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4980                         APFloat::rmNearestTiesToEven);
4981   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4982     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4983         Pred == ICmpInst::ICMP_SGE)
4984       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4985     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4986   }
4987
4988   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4989   // it may still be fractional.  See if it is fractional by casting the FP
4990   // value to the integer value and back, checking for equality.  Don't do this
4991   // for zero, because -0.0 is not fractional.
4992   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4993   if (!RHS.isZero() &&
4994       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4995     // If we had a comparison against a fractional value, we have to adjust
4996     // the compare predicate and sometimes the value.  RHSC is rounded towards
4997     // zero at this point.
4998     switch (Pred) {
4999     default: assert(0 && "Unexpected integer comparison!");
5000     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5001       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5002     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5003       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5004     case ICmpInst::ICMP_SLE:
5005       // (float)int <= 4.4   --> int <= 4
5006       // (float)int <= -4.4  --> int < -4
5007       if (RHS.isNegative())
5008         Pred = ICmpInst::ICMP_SLT;
5009       break;
5010     case ICmpInst::ICMP_SLT:
5011       // (float)int < -4.4   --> int < -4
5012       // (float)int < 4.4    --> int <= 4
5013       if (!RHS.isNegative())
5014         Pred = ICmpInst::ICMP_SLE;
5015       break;
5016     case ICmpInst::ICMP_SGT:
5017       // (float)int > 4.4    --> int > 4
5018       // (float)int > -4.4   --> int >= -4
5019       if (RHS.isNegative())
5020         Pred = ICmpInst::ICMP_SGE;
5021       break;
5022     case ICmpInst::ICMP_SGE:
5023       // (float)int >= -4.4   --> int >= -4
5024       // (float)int >= 4.4    --> int > 4
5025       if (!RHS.isNegative())
5026         Pred = ICmpInst::ICMP_SGT;
5027       break;
5028     }
5029   }
5030
5031   // Lower this FP comparison into an appropriate integer version of the
5032   // comparison.
5033   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5034 }
5035
5036 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5037   bool Changed = SimplifyCompare(I);
5038   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5039
5040   // Fold trivial predicates.
5041   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5042     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5043   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5044     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5045   
5046   // Simplify 'fcmp pred X, X'
5047   if (Op0 == Op1) {
5048     switch (I.getPredicate()) {
5049     default: assert(0 && "Unknown predicate!");
5050     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5051     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5052     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5053       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5054     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5055     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5056     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5057       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5058       
5059     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5060     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5061     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5062     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5063       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5064       I.setPredicate(FCmpInst::FCMP_UNO);
5065       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5066       return &I;
5067       
5068     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5069     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5070     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5071     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5072       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5073       I.setPredicate(FCmpInst::FCMP_ORD);
5074       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5075       return &I;
5076     }
5077   }
5078     
5079   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5080     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5081
5082   // Handle fcmp with constant RHS
5083   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5084     // If the constant is a nan, see if we can fold the comparison based on it.
5085     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5086       if (CFP->getValueAPF().isNaN()) {
5087         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5088           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5089         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5090                "Comparison must be either ordered or unordered!");
5091         // True if unordered.
5092         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5093       }
5094     }
5095     
5096     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5097       switch (LHSI->getOpcode()) {
5098       case Instruction::PHI:
5099         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5100         // block.  If in the same block, we're encouraging jump threading.  If
5101         // not, we are just pessimizing the code by making an i1 phi.
5102         if (LHSI->getParent() == I.getParent())
5103           if (Instruction *NV = FoldOpIntoPhi(I))
5104             return NV;
5105         break;
5106       case Instruction::SIToFP:
5107       case Instruction::UIToFP:
5108         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5109           return NV;
5110         break;
5111       case Instruction::Select:
5112         // If either operand of the select is a constant, we can fold the
5113         // comparison into the select arms, which will cause one to be
5114         // constant folded and the select turned into a bitwise or.
5115         Value *Op1 = 0, *Op2 = 0;
5116         if (LHSI->hasOneUse()) {
5117           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5118             // Fold the known value into the constant operand.
5119             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5120             // Insert a new FCmp of the other select operand.
5121             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5122                                                       LHSI->getOperand(2), RHSC,
5123                                                       I.getName()), I);
5124           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5125             // Fold the known value into the constant operand.
5126             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5127             // Insert a new FCmp of the other select operand.
5128             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5129                                                       LHSI->getOperand(1), RHSC,
5130                                                       I.getName()), I);
5131           }
5132         }
5133
5134         if (Op1)
5135           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5136         break;
5137       }
5138   }
5139
5140   return Changed ? &I : 0;
5141 }
5142
5143 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5144   bool Changed = SimplifyCompare(I);
5145   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5146   const Type *Ty = Op0->getType();
5147
5148   // icmp X, X
5149   if (Op0 == Op1)
5150     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5151                                                    I.isTrueWhenEqual()));
5152
5153   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5154     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5155   
5156   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5157   // addresses never equal each other!  We already know that Op0 != Op1.
5158   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5159        isa<ConstantPointerNull>(Op0)) &&
5160       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5161        isa<ConstantPointerNull>(Op1)))
5162     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5163                                                    !I.isTrueWhenEqual()));
5164
5165   // icmp's with boolean values can always be turned into bitwise operations
5166   if (Ty == Type::Int1Ty) {
5167     switch (I.getPredicate()) {
5168     default: assert(0 && "Invalid icmp instruction!");
5169     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5170       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5171       InsertNewInstBefore(Xor, I);
5172       return BinaryOperator::CreateNot(Xor);
5173     }
5174     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5175       return BinaryOperator::CreateXor(Op0, Op1);
5176
5177     case ICmpInst::ICMP_UGT:
5178       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5179       // FALL THROUGH
5180     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5181       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5182       InsertNewInstBefore(Not, I);
5183       return BinaryOperator::CreateAnd(Not, Op1);
5184     }
5185     case ICmpInst::ICMP_SGT:
5186       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5187       // FALL THROUGH
5188     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5189       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5190       InsertNewInstBefore(Not, I);
5191       return BinaryOperator::CreateAnd(Not, Op0);
5192     }
5193     case ICmpInst::ICMP_UGE:
5194       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5195       // FALL THROUGH
5196     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5197       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5198       InsertNewInstBefore(Not, I);
5199       return BinaryOperator::CreateOr(Not, Op1);
5200     }
5201     case ICmpInst::ICMP_SGE:
5202       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5203       // FALL THROUGH
5204     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5205       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5206       InsertNewInstBefore(Not, I);
5207       return BinaryOperator::CreateOr(Not, Op0);
5208     }
5209     }
5210   }
5211
5212   // See if we are doing a comparison between a constant and an instruction that
5213   // can be folded into the comparison.
5214   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5215     Value *A, *B;
5216     
5217     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5218     if (I.isEquality() && CI->isNullValue() &&
5219         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5220       // (icmp cond A B) if cond is equality
5221       return new ICmpInst(I.getPredicate(), A, B);
5222     }
5223     
5224     // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5225     // icmp lt or icmp gt instruction.  This allows us to rely on them being
5226     // folded in the code below.
5227     switch (I.getPredicate()) {
5228     default: break;
5229     case ICmpInst::ICMP_ULE:
5230       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5231         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5232       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5233     case ICmpInst::ICMP_SLE:
5234       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5235         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5236       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5237     case ICmpInst::ICMP_UGE:
5238       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5239         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5240       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5241     case ICmpInst::ICMP_SGE:
5242       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5243         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5244       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5245     }
5246     
5247     // See if we can fold the comparison based on range information we can get
5248     // by checking whether bits are known to be zero or one in the input.
5249     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5250     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5251     
5252     // If this comparison is a normal comparison, it demands all
5253     // bits, if it is a sign bit comparison, it only demands the sign bit.
5254     bool UnusedBit;
5255     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5256     
5257     if (SimplifyDemandedBits(Op0, 
5258                              isSignBit ? APInt::getSignBit(BitWidth)
5259                                        : APInt::getAllOnesValue(BitWidth),
5260                              KnownZero, KnownOne, 0))
5261       return &I;
5262         
5263     // Given the known and unknown bits, compute a range that the LHS could be
5264     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5265     // EQ and NE we use unsigned values.
5266     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5267     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5268       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5269     else
5270       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5271     
5272     // If Min and Max are known to be the same, then SimplifyDemandedBits
5273     // figured out that the LHS is a constant.  Just constant fold this now so
5274     // that code below can assume that Min != Max.
5275     if (Min == Max)
5276       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5277                                                           ConstantInt::get(Min),
5278                                                           CI));
5279     
5280     // Based on the range information we know about the LHS, see if we can
5281     // simplify this comparison.  For example, (x&4) < 8  is always true.
5282     const APInt &RHSVal = CI->getValue();
5283     switch (I.getPredicate()) {  // LE/GE have been folded already.
5284     default: assert(0 && "Unknown icmp opcode!");
5285     case ICmpInst::ICMP_EQ:
5286       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5287         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5288       break;
5289     case ICmpInst::ICMP_NE:
5290       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5291         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5292       break;
5293     case ICmpInst::ICMP_ULT:
5294       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5295         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5296       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5297         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5298       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5299         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5300       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5301         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5302         
5303       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5304       if (CI->isMinValue(true))
5305         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5306                             ConstantInt::getAllOnesValue(Op0->getType()));
5307       break;
5308     case ICmpInst::ICMP_UGT:
5309       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5310         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5311       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5312         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5313         
5314       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5315         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5316       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5317         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5318       
5319       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5320       if (CI->isMaxValue(true))
5321         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5322                             ConstantInt::getNullValue(Op0->getType()));
5323       break;
5324     case ICmpInst::ICMP_SLT:
5325       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5326         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5327       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5328         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5329       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5330         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5331       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5332         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5333       break;
5334     case ICmpInst::ICMP_SGT: 
5335       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5336         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5337       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5338         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5339         
5340       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5341         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5342       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5343         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5344       break;
5345     }
5346           
5347     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5348     // instruction, see if that instruction also has constants so that the 
5349     // instruction can be folded into the icmp 
5350     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5351       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5352         return Res;
5353   }
5354
5355   // Handle icmp with constant (but not simple integer constant) RHS
5356   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5357     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5358       switch (LHSI->getOpcode()) {
5359       case Instruction::GetElementPtr:
5360         if (RHSC->isNullValue()) {
5361           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5362           bool isAllZeros = true;
5363           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5364             if (!isa<Constant>(LHSI->getOperand(i)) ||
5365                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5366               isAllZeros = false;
5367               break;
5368             }
5369           if (isAllZeros)
5370             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5371                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5372         }
5373         break;
5374
5375       case Instruction::PHI:
5376         // Only fold icmp into the PHI if the phi and fcmp are in the same
5377         // block.  If in the same block, we're encouraging jump threading.  If
5378         // not, we are just pessimizing the code by making an i1 phi.
5379         if (LHSI->getParent() == I.getParent())
5380           if (Instruction *NV = FoldOpIntoPhi(I))
5381             return NV;
5382         break;
5383       case Instruction::Select: {
5384         // If either operand of the select is a constant, we can fold the
5385         // comparison into the select arms, which will cause one to be
5386         // constant folded and the select turned into a bitwise or.
5387         Value *Op1 = 0, *Op2 = 0;
5388         if (LHSI->hasOneUse()) {
5389           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5390             // Fold the known value into the constant operand.
5391             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5392             // Insert a new ICmp of the other select operand.
5393             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5394                                                    LHSI->getOperand(2), RHSC,
5395                                                    I.getName()), I);
5396           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5397             // Fold the known value into the constant operand.
5398             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5399             // Insert a new ICmp of the other select operand.
5400             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5401                                                    LHSI->getOperand(1), RHSC,
5402                                                    I.getName()), I);
5403           }
5404         }
5405
5406         if (Op1)
5407           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5408         break;
5409       }
5410       case Instruction::Malloc:
5411         // If we have (malloc != null), and if the malloc has a single use, we
5412         // can assume it is successful and remove the malloc.
5413         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5414           AddToWorkList(LHSI);
5415           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5416                                                          !I.isTrueWhenEqual()));
5417         }
5418         break;
5419       }
5420   }
5421
5422   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5423   if (User *GEP = dyn_castGetElementPtr(Op0))
5424     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5425       return NI;
5426   if (User *GEP = dyn_castGetElementPtr(Op1))
5427     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5428                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5429       return NI;
5430
5431   // Test to see if the operands of the icmp are casted versions of other
5432   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5433   // now.
5434   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5435     if (isa<PointerType>(Op0->getType()) && 
5436         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5437       // We keep moving the cast from the left operand over to the right
5438       // operand, where it can often be eliminated completely.
5439       Op0 = CI->getOperand(0);
5440
5441       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5442       // so eliminate it as well.
5443       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5444         Op1 = CI2->getOperand(0);
5445
5446       // If Op1 is a constant, we can fold the cast into the constant.
5447       if (Op0->getType() != Op1->getType()) {
5448         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5449           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5450         } else {
5451           // Otherwise, cast the RHS right before the icmp
5452           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5453         }
5454       }
5455       return new ICmpInst(I.getPredicate(), Op0, Op1);
5456     }
5457   }
5458   
5459   if (isa<CastInst>(Op0)) {
5460     // Handle the special case of: icmp (cast bool to X), <cst>
5461     // This comes up when you have code like
5462     //   int X = A < B;
5463     //   if (X) ...
5464     // For generality, we handle any zero-extension of any operand comparison
5465     // with a constant or another cast from the same type.
5466     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5467       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5468         return R;
5469   }
5470   
5471   // See if it's the same type of instruction on the left and right.
5472   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5473     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5474       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5475           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5476           I.isEquality()) {
5477         switch (Op0I->getOpcode()) {
5478         default: break;
5479         case Instruction::Add:
5480         case Instruction::Sub:
5481         case Instruction::Xor:
5482           // a+x icmp eq/ne b+x --> a icmp b
5483           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5484                               Op1I->getOperand(0));
5485           break;
5486         case Instruction::Mul:
5487           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5488             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5489             // Mask = -1 >> count-trailing-zeros(Cst).
5490             if (!CI->isZero() && !CI->isOne()) {
5491               const APInt &AP = CI->getValue();
5492               ConstantInt *Mask = ConstantInt::get(
5493                                       APInt::getLowBitsSet(AP.getBitWidth(),
5494                                                            AP.getBitWidth() -
5495                                                       AP.countTrailingZeros()));
5496               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5497                                                             Mask);
5498               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5499                                                             Mask);
5500               InsertNewInstBefore(And1, I);
5501               InsertNewInstBefore(And2, I);
5502               return new ICmpInst(I.getPredicate(), And1, And2);
5503             }
5504           }
5505           break;
5506         }
5507       }
5508     }
5509   }
5510   
5511   // ~x < ~y --> y < x
5512   { Value *A, *B;
5513     if (match(Op0, m_Not(m_Value(A))) &&
5514         match(Op1, m_Not(m_Value(B))))
5515       return new ICmpInst(I.getPredicate(), B, A);
5516   }
5517   
5518   if (I.isEquality()) {
5519     Value *A, *B, *C, *D;
5520     
5521     // -x == -y --> x == y
5522     if (match(Op0, m_Neg(m_Value(A))) &&
5523         match(Op1, m_Neg(m_Value(B))))
5524       return new ICmpInst(I.getPredicate(), A, B);
5525     
5526     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5527       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5528         Value *OtherVal = A == Op1 ? B : A;
5529         return new ICmpInst(I.getPredicate(), OtherVal,
5530                             Constant::getNullValue(A->getType()));
5531       }
5532
5533       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5534         // A^c1 == C^c2 --> A == C^(c1^c2)
5535         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5536           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5537             if (Op1->hasOneUse()) {
5538               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5539               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5540               return new ICmpInst(I.getPredicate(), A,
5541                                   InsertNewInstBefore(Xor, I));
5542             }
5543         
5544         // A^B == A^D -> B == D
5545         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5546         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5547         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5548         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5549       }
5550     }
5551     
5552     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5553         (A == Op0 || B == Op0)) {
5554       // A == (A^B)  ->  B == 0
5555       Value *OtherVal = A == Op0 ? B : A;
5556       return new ICmpInst(I.getPredicate(), OtherVal,
5557                           Constant::getNullValue(A->getType()));
5558     }
5559     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5560       // (A-B) == A  ->  B == 0
5561       return new ICmpInst(I.getPredicate(), B,
5562                           Constant::getNullValue(B->getType()));
5563     }
5564     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5565       // A == (A-B)  ->  B == 0
5566       return new ICmpInst(I.getPredicate(), B,
5567                           Constant::getNullValue(B->getType()));
5568     }
5569     
5570     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5571     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5572         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5573         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5574       Value *X = 0, *Y = 0, *Z = 0;
5575       
5576       if (A == C) {
5577         X = B; Y = D; Z = A;
5578       } else if (A == D) {
5579         X = B; Y = C; Z = A;
5580       } else if (B == C) {
5581         X = A; Y = D; Z = B;
5582       } else if (B == D) {
5583         X = A; Y = C; Z = B;
5584       }
5585       
5586       if (X) {   // Build (X^Y) & Z
5587         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5588         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5589         I.setOperand(0, Op1);
5590         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5591         return &I;
5592       }
5593     }
5594   }
5595   return Changed ? &I : 0;
5596 }
5597
5598
5599 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5600 /// and CmpRHS are both known to be integer constants.
5601 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5602                                           ConstantInt *DivRHS) {
5603   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5604   const APInt &CmpRHSV = CmpRHS->getValue();
5605   
5606   // FIXME: If the operand types don't match the type of the divide 
5607   // then don't attempt this transform. The code below doesn't have the
5608   // logic to deal with a signed divide and an unsigned compare (and
5609   // vice versa). This is because (x /s C1) <s C2  produces different 
5610   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5611   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5612   // work. :(  The if statement below tests that condition and bails 
5613   // if it finds it. 
5614   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5615   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5616     return 0;
5617   if (DivRHS->isZero())
5618     return 0; // The ProdOV computation fails on divide by zero.
5619
5620   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5621   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5622   // C2 (CI). By solving for X we can turn this into a range check 
5623   // instead of computing a divide. 
5624   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5625
5626   // Determine if the product overflows by seeing if the product is
5627   // not equal to the divide. Make sure we do the same kind of divide
5628   // as in the LHS instruction that we're folding. 
5629   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5630                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5631
5632   // Get the ICmp opcode
5633   ICmpInst::Predicate Pred = ICI.getPredicate();
5634
5635   // Figure out the interval that is being checked.  For example, a comparison
5636   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5637   // Compute this interval based on the constants involved and the signedness of
5638   // the compare/divide.  This computes a half-open interval, keeping track of
5639   // whether either value in the interval overflows.  After analysis each
5640   // overflow variable is set to 0 if it's corresponding bound variable is valid
5641   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5642   int LoOverflow = 0, HiOverflow = 0;
5643   ConstantInt *LoBound = 0, *HiBound = 0;
5644   
5645   
5646   if (!DivIsSigned) {  // udiv
5647     // e.g. X/5 op 3  --> [15, 20)
5648     LoBound = Prod;
5649     HiOverflow = LoOverflow = ProdOV;
5650     if (!HiOverflow)
5651       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5652   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5653     if (CmpRHSV == 0) {       // (X / pos) op 0
5654       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5655       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5656       HiBound = DivRHS;
5657     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5658       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5659       HiOverflow = LoOverflow = ProdOV;
5660       if (!HiOverflow)
5661         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5662     } else {                       // (X / pos) op neg
5663       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5664       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5665       LoOverflow = AddWithOverflow(LoBound, Prod,
5666                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5667       HiBound = AddOne(Prod);
5668       HiOverflow = ProdOV ? -1 : 0;
5669     }
5670   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5671     if (CmpRHSV == 0) {       // (X / neg) op 0
5672       // e.g. X/-5 op 0  --> [-4, 5)
5673       LoBound = AddOne(DivRHS);
5674       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5675       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5676         HiOverflow = 1;            // [INTMIN+1, overflow)
5677         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5678       }
5679     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5680       // e.g. X/-5 op 3  --> [-19, -14)
5681       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5682       if (!LoOverflow)
5683         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5684       HiBound = AddOne(Prod);
5685     } else {                       // (X / neg) op neg
5686       // e.g. X/-5 op -3  --> [15, 20)
5687       LoBound = Prod;
5688       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5689       HiBound = Subtract(Prod, DivRHS);
5690     }
5691     
5692     // Dividing by a negative swaps the condition.  LT <-> GT
5693     Pred = ICmpInst::getSwappedPredicate(Pred);
5694   }
5695
5696   Value *X = DivI->getOperand(0);
5697   switch (Pred) {
5698   default: assert(0 && "Unhandled icmp opcode!");
5699   case ICmpInst::ICMP_EQ:
5700     if (LoOverflow && HiOverflow)
5701       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5702     else if (HiOverflow)
5703       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5704                           ICmpInst::ICMP_UGE, X, LoBound);
5705     else if (LoOverflow)
5706       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5707                           ICmpInst::ICMP_ULT, X, HiBound);
5708     else
5709       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5710   case ICmpInst::ICMP_NE:
5711     if (LoOverflow && HiOverflow)
5712       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5713     else if (HiOverflow)
5714       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5715                           ICmpInst::ICMP_ULT, X, LoBound);
5716     else if (LoOverflow)
5717       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5718                           ICmpInst::ICMP_UGE, X, HiBound);
5719     else
5720       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5721   case ICmpInst::ICMP_ULT:
5722   case ICmpInst::ICMP_SLT:
5723     if (LoOverflow == +1)   // Low bound is greater than input range.
5724       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5725     if (LoOverflow == -1)   // Low bound is less than input range.
5726       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5727     return new ICmpInst(Pred, X, LoBound);
5728   case ICmpInst::ICMP_UGT:
5729   case ICmpInst::ICMP_SGT:
5730     if (HiOverflow == +1)       // High bound greater than input range.
5731       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5732     else if (HiOverflow == -1)  // High bound less than input range.
5733       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5734     if (Pred == ICmpInst::ICMP_UGT)
5735       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5736     else
5737       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5738   }
5739 }
5740
5741
5742 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5743 ///
5744 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5745                                                           Instruction *LHSI,
5746                                                           ConstantInt *RHS) {
5747   const APInt &RHSV = RHS->getValue();
5748   
5749   switch (LHSI->getOpcode()) {
5750   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5751     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5752       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5753       // fold the xor.
5754       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5755           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5756         Value *CompareVal = LHSI->getOperand(0);
5757         
5758         // If the sign bit of the XorCST is not set, there is no change to
5759         // the operation, just stop using the Xor.
5760         if (!XorCST->getValue().isNegative()) {
5761           ICI.setOperand(0, CompareVal);
5762           AddToWorkList(LHSI);
5763           return &ICI;
5764         }
5765         
5766         // Was the old condition true if the operand is positive?
5767         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5768         
5769         // If so, the new one isn't.
5770         isTrueIfPositive ^= true;
5771         
5772         if (isTrueIfPositive)
5773           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5774         else
5775           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5776       }
5777     }
5778     break;
5779   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5780     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5781         LHSI->getOperand(0)->hasOneUse()) {
5782       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5783       
5784       // If the LHS is an AND of a truncating cast, we can widen the
5785       // and/compare to be the input width without changing the value
5786       // produced, eliminating a cast.
5787       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5788         // We can do this transformation if either the AND constant does not
5789         // have its sign bit set or if it is an equality comparison. 
5790         // Extending a relational comparison when we're checking the sign
5791         // bit would not work.
5792         if (Cast->hasOneUse() &&
5793             (ICI.isEquality() ||
5794              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5795           uint32_t BitWidth = 
5796             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5797           APInt NewCST = AndCST->getValue();
5798           NewCST.zext(BitWidth);
5799           APInt NewCI = RHSV;
5800           NewCI.zext(BitWidth);
5801           Instruction *NewAnd = 
5802             BinaryOperator::CreateAnd(Cast->getOperand(0),
5803                                       ConstantInt::get(NewCST),LHSI->getName());
5804           InsertNewInstBefore(NewAnd, ICI);
5805           return new ICmpInst(ICI.getPredicate(), NewAnd,
5806                               ConstantInt::get(NewCI));
5807         }
5808       }
5809       
5810       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5811       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5812       // happens a LOT in code produced by the C front-end, for bitfield
5813       // access.
5814       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5815       if (Shift && !Shift->isShift())
5816         Shift = 0;
5817       
5818       ConstantInt *ShAmt;
5819       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5820       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5821       const Type *AndTy = AndCST->getType();          // Type of the and.
5822       
5823       // We can fold this as long as we can't shift unknown bits
5824       // into the mask.  This can only happen with signed shift
5825       // rights, as they sign-extend.
5826       if (ShAmt) {
5827         bool CanFold = Shift->isLogicalShift();
5828         if (!CanFold) {
5829           // To test for the bad case of the signed shr, see if any
5830           // of the bits shifted in could be tested after the mask.
5831           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5832           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5833           
5834           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5835           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5836                AndCST->getValue()) == 0)
5837             CanFold = true;
5838         }
5839         
5840         if (CanFold) {
5841           Constant *NewCst;
5842           if (Shift->getOpcode() == Instruction::Shl)
5843             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5844           else
5845             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5846           
5847           // Check to see if we are shifting out any of the bits being
5848           // compared.
5849           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5850             // If we shifted bits out, the fold is not going to work out.
5851             // As a special case, check to see if this means that the
5852             // result is always true or false now.
5853             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5854               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5855             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5856               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5857           } else {
5858             ICI.setOperand(1, NewCst);
5859             Constant *NewAndCST;
5860             if (Shift->getOpcode() == Instruction::Shl)
5861               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5862             else
5863               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5864             LHSI->setOperand(1, NewAndCST);
5865             LHSI->setOperand(0, Shift->getOperand(0));
5866             AddToWorkList(Shift); // Shift is dead.
5867             AddUsesToWorkList(ICI);
5868             return &ICI;
5869           }
5870         }
5871       }
5872       
5873       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5874       // preferable because it allows the C<<Y expression to be hoisted out
5875       // of a loop if Y is invariant and X is not.
5876       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5877           ICI.isEquality() && !Shift->isArithmeticShift() &&
5878           isa<Instruction>(Shift->getOperand(0))) {
5879         // Compute C << Y.
5880         Value *NS;
5881         if (Shift->getOpcode() == Instruction::LShr) {
5882           NS = BinaryOperator::CreateShl(AndCST, 
5883                                          Shift->getOperand(1), "tmp");
5884         } else {
5885           // Insert a logical shift.
5886           NS = BinaryOperator::CreateLShr(AndCST,
5887                                           Shift->getOperand(1), "tmp");
5888         }
5889         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5890         
5891         // Compute X & (C << Y).
5892         Instruction *NewAnd = 
5893           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5894         InsertNewInstBefore(NewAnd, ICI);
5895         
5896         ICI.setOperand(0, NewAnd);
5897         return &ICI;
5898       }
5899     }
5900     break;
5901     
5902   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5903     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5904     if (!ShAmt) break;
5905     
5906     uint32_t TypeBits = RHSV.getBitWidth();
5907     
5908     // Check that the shift amount is in range.  If not, don't perform
5909     // undefined shifts.  When the shift is visited it will be
5910     // simplified.
5911     if (ShAmt->uge(TypeBits))
5912       break;
5913     
5914     if (ICI.isEquality()) {
5915       // If we are comparing against bits always shifted out, the
5916       // comparison cannot succeed.
5917       Constant *Comp =
5918         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5919       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5920         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5921         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5922         return ReplaceInstUsesWith(ICI, Cst);
5923       }
5924       
5925       if (LHSI->hasOneUse()) {
5926         // Otherwise strength reduce the shift into an and.
5927         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5928         Constant *Mask =
5929           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5930         
5931         Instruction *AndI =
5932           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5933                                     Mask, LHSI->getName()+".mask");
5934         Value *And = InsertNewInstBefore(AndI, ICI);
5935         return new ICmpInst(ICI.getPredicate(), And,
5936                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5937       }
5938     }
5939     
5940     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5941     bool TrueIfSigned = false;
5942     if (LHSI->hasOneUse() &&
5943         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5944       // (X << 31) <s 0  --> (X&1) != 0
5945       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5946                                            (TypeBits-ShAmt->getZExtValue()-1));
5947       Instruction *AndI =
5948         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5949                                   Mask, LHSI->getName()+".mask");
5950       Value *And = InsertNewInstBefore(AndI, ICI);
5951       
5952       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5953                           And, Constant::getNullValue(And->getType()));
5954     }
5955     break;
5956   }
5957     
5958   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5959   case Instruction::AShr: {
5960     // Only handle equality comparisons of shift-by-constant.
5961     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5962     if (!ShAmt || !ICI.isEquality()) break;
5963
5964     // Check that the shift amount is in range.  If not, don't perform
5965     // undefined shifts.  When the shift is visited it will be
5966     // simplified.
5967     uint32_t TypeBits = RHSV.getBitWidth();
5968     if (ShAmt->uge(TypeBits))
5969       break;
5970     
5971     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5972       
5973     // If we are comparing against bits always shifted out, the
5974     // comparison cannot succeed.
5975     APInt Comp = RHSV << ShAmtVal;
5976     if (LHSI->getOpcode() == Instruction::LShr)
5977       Comp = Comp.lshr(ShAmtVal);
5978     else
5979       Comp = Comp.ashr(ShAmtVal);
5980     
5981     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5982       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5983       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5984       return ReplaceInstUsesWith(ICI, Cst);
5985     }
5986     
5987     // Otherwise, check to see if the bits shifted out are known to be zero.
5988     // If so, we can compare against the unshifted value:
5989     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5990     if (LHSI->hasOneUse() &&
5991         MaskedValueIsZero(LHSI->getOperand(0), 
5992                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5993       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5994                           ConstantExpr::getShl(RHS, ShAmt));
5995     }
5996       
5997     if (LHSI->hasOneUse()) {
5998       // Otherwise strength reduce the shift into an and.
5999       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6000       Constant *Mask = ConstantInt::get(Val);
6001       
6002       Instruction *AndI =
6003         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6004                                   Mask, LHSI->getName()+".mask");
6005       Value *And = InsertNewInstBefore(AndI, ICI);
6006       return new ICmpInst(ICI.getPredicate(), And,
6007                           ConstantExpr::getShl(RHS, ShAmt));
6008     }
6009     break;
6010   }
6011     
6012   case Instruction::SDiv:
6013   case Instruction::UDiv:
6014     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6015     // Fold this div into the comparison, producing a range check. 
6016     // Determine, based on the divide type, what the range is being 
6017     // checked.  If there is an overflow on the low or high side, remember 
6018     // it, otherwise compute the range [low, hi) bounding the new value.
6019     // See: InsertRangeTest above for the kinds of replacements possible.
6020     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6021       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6022                                           DivRHS))
6023         return R;
6024     break;
6025
6026   case Instruction::Add:
6027     // Fold: icmp pred (add, X, C1), C2
6028
6029     if (!ICI.isEquality()) {
6030       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6031       if (!LHSC) break;
6032       const APInt &LHSV = LHSC->getValue();
6033
6034       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6035                             .subtract(LHSV);
6036
6037       if (ICI.isSignedPredicate()) {
6038         if (CR.getLower().isSignBit()) {
6039           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6040                               ConstantInt::get(CR.getUpper()));
6041         } else if (CR.getUpper().isSignBit()) {
6042           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6043                               ConstantInt::get(CR.getLower()));
6044         }
6045       } else {
6046         if (CR.getLower().isMinValue()) {
6047           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6048                               ConstantInt::get(CR.getUpper()));
6049         } else if (CR.getUpper().isMinValue()) {
6050           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6051                               ConstantInt::get(CR.getLower()));
6052         }
6053       }
6054     }
6055     break;
6056   }
6057   
6058   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6059   if (ICI.isEquality()) {
6060     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6061     
6062     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6063     // the second operand is a constant, simplify a bit.
6064     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6065       switch (BO->getOpcode()) {
6066       case Instruction::SRem:
6067         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6068         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6069           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6070           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6071             Instruction *NewRem =
6072               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6073                                          BO->getName());
6074             InsertNewInstBefore(NewRem, ICI);
6075             return new ICmpInst(ICI.getPredicate(), NewRem, 
6076                                 Constant::getNullValue(BO->getType()));
6077           }
6078         }
6079         break;
6080       case Instruction::Add:
6081         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6082         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6083           if (BO->hasOneUse())
6084             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6085                                 Subtract(RHS, BOp1C));
6086         } else if (RHSV == 0) {
6087           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6088           // efficiently invertible, or if the add has just this one use.
6089           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6090           
6091           if (Value *NegVal = dyn_castNegVal(BOp1))
6092             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6093           else if (Value *NegVal = dyn_castNegVal(BOp0))
6094             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6095           else if (BO->hasOneUse()) {
6096             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6097             InsertNewInstBefore(Neg, ICI);
6098             Neg->takeName(BO);
6099             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6100           }
6101         }
6102         break;
6103       case Instruction::Xor:
6104         // For the xor case, we can xor two constants together, eliminating
6105         // the explicit xor.
6106         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6107           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6108                               ConstantExpr::getXor(RHS, BOC));
6109         
6110         // FALLTHROUGH
6111       case Instruction::Sub:
6112         // Replace (([sub|xor] A, B) != 0) with (A != B)
6113         if (RHSV == 0)
6114           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6115                               BO->getOperand(1));
6116         break;
6117         
6118       case Instruction::Or:
6119         // If bits are being or'd in that are not present in the constant we
6120         // are comparing against, then the comparison could never succeed!
6121         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6122           Constant *NotCI = ConstantExpr::getNot(RHS);
6123           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6124             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6125                                                              isICMP_NE));
6126         }
6127         break;
6128         
6129       case Instruction::And:
6130         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6131           // If bits are being compared against that are and'd out, then the
6132           // comparison can never succeed!
6133           if ((RHSV & ~BOC->getValue()) != 0)
6134             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6135                                                              isICMP_NE));
6136           
6137           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6138           if (RHS == BOC && RHSV.isPowerOf2())
6139             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6140                                 ICmpInst::ICMP_NE, LHSI,
6141                                 Constant::getNullValue(RHS->getType()));
6142           
6143           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6144           if (BOC->getValue().isSignBit()) {
6145             Value *X = BO->getOperand(0);
6146             Constant *Zero = Constant::getNullValue(X->getType());
6147             ICmpInst::Predicate pred = isICMP_NE ? 
6148               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6149             return new ICmpInst(pred, X, Zero);
6150           }
6151           
6152           // ((X & ~7) == 0) --> X < 8
6153           if (RHSV == 0 && isHighOnes(BOC)) {
6154             Value *X = BO->getOperand(0);
6155             Constant *NegX = ConstantExpr::getNeg(BOC);
6156             ICmpInst::Predicate pred = isICMP_NE ? 
6157               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6158             return new ICmpInst(pred, X, NegX);
6159           }
6160         }
6161       default: break;
6162       }
6163     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6164       // Handle icmp {eq|ne} <intrinsic>, intcst.
6165       if (II->getIntrinsicID() == Intrinsic::bswap) {
6166         AddToWorkList(II);
6167         ICI.setOperand(0, II->getOperand(1));
6168         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6169         return &ICI;
6170       }
6171     }
6172   } else {  // Not a ICMP_EQ/ICMP_NE
6173             // If the LHS is a cast from an integral value of the same size, 
6174             // then since we know the RHS is a constant, try to simlify.
6175     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6176       Value *CastOp = Cast->getOperand(0);
6177       const Type *SrcTy = CastOp->getType();
6178       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6179       if (SrcTy->isInteger() && 
6180           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6181         // If this is an unsigned comparison, try to make the comparison use
6182         // smaller constant values.
6183         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6184           // X u< 128 => X s> -1
6185           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6186                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6187         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6188                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6189           // X u> 127 => X s< 0
6190           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6191                               Constant::getNullValue(SrcTy));
6192         }
6193       }
6194     }
6195   }
6196   return 0;
6197 }
6198
6199 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6200 /// We only handle extending casts so far.
6201 ///
6202 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6203   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6204   Value *LHSCIOp        = LHSCI->getOperand(0);
6205   const Type *SrcTy     = LHSCIOp->getType();
6206   const Type *DestTy    = LHSCI->getType();
6207   Value *RHSCIOp;
6208
6209   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6210   // integer type is the same size as the pointer type.
6211   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6212       getTargetData().getPointerSizeInBits() == 
6213          cast<IntegerType>(DestTy)->getBitWidth()) {
6214     Value *RHSOp = 0;
6215     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6216       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6217     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6218       RHSOp = RHSC->getOperand(0);
6219       // If the pointer types don't match, insert a bitcast.
6220       if (LHSCIOp->getType() != RHSOp->getType())
6221         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6222     }
6223
6224     if (RHSOp)
6225       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6226   }
6227   
6228   // The code below only handles extension cast instructions, so far.
6229   // Enforce this.
6230   if (LHSCI->getOpcode() != Instruction::ZExt &&
6231       LHSCI->getOpcode() != Instruction::SExt)
6232     return 0;
6233
6234   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6235   bool isSignedCmp = ICI.isSignedPredicate();
6236
6237   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6238     // Not an extension from the same type?
6239     RHSCIOp = CI->getOperand(0);
6240     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6241       return 0;
6242     
6243     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6244     // and the other is a zext), then we can't handle this.
6245     if (CI->getOpcode() != LHSCI->getOpcode())
6246       return 0;
6247
6248     // Deal with equality cases early.
6249     if (ICI.isEquality())
6250       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6251
6252     // A signed comparison of sign extended values simplifies into a
6253     // signed comparison.
6254     if (isSignedCmp && isSignedExt)
6255       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6256
6257     // The other three cases all fold into an unsigned comparison.
6258     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6259   }
6260
6261   // If we aren't dealing with a constant on the RHS, exit early
6262   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6263   if (!CI)
6264     return 0;
6265
6266   // Compute the constant that would happen if we truncated to SrcTy then
6267   // reextended to DestTy.
6268   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6269   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6270
6271   // If the re-extended constant didn't change...
6272   if (Res2 == CI) {
6273     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6274     // For example, we might have:
6275     //    %A = sext short %X to uint
6276     //    %B = icmp ugt uint %A, 1330
6277     // It is incorrect to transform this into 
6278     //    %B = icmp ugt short %X, 1330 
6279     // because %A may have negative value. 
6280     //
6281     // However, we allow this when the compare is EQ/NE, because they are
6282     // signless.
6283     if (isSignedExt == isSignedCmp || ICI.isEquality())
6284       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6285     return 0;
6286   }
6287
6288   // The re-extended constant changed so the constant cannot be represented 
6289   // in the shorter type. Consequently, we cannot emit a simple comparison.
6290
6291   // First, handle some easy cases. We know the result cannot be equal at this
6292   // point so handle the ICI.isEquality() cases
6293   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6294     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6295   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6296     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6297
6298   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6299   // should have been folded away previously and not enter in here.
6300   Value *Result;
6301   if (isSignedCmp) {
6302     // We're performing a signed comparison.
6303     if (cast<ConstantInt>(CI)->getValue().isNegative())
6304       Result = ConstantInt::getFalse();          // X < (small) --> false
6305     else
6306       Result = ConstantInt::getTrue();           // X < (large) --> true
6307   } else {
6308     // We're performing an unsigned comparison.
6309     if (isSignedExt) {
6310       // We're performing an unsigned comp with a sign extended value.
6311       // This is true if the input is >= 0. [aka >s -1]
6312       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6313       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6314                                    NegOne, ICI.getName()), ICI);
6315     } else {
6316       // Unsigned extend & unsigned compare -> always true.
6317       Result = ConstantInt::getTrue();
6318     }
6319   }
6320
6321   // Finally, return the value computed.
6322   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6323       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6324     return ReplaceInstUsesWith(ICI, Result);
6325
6326   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6327           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6328          "ICmp should be folded!");
6329   if (Constant *CI = dyn_cast<Constant>(Result))
6330     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6331   return BinaryOperator::CreateNot(Result);
6332 }
6333
6334 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6335   return commonShiftTransforms(I);
6336 }
6337
6338 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6339   return commonShiftTransforms(I);
6340 }
6341
6342 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6343   if (Instruction *R = commonShiftTransforms(I))
6344     return R;
6345   
6346   Value *Op0 = I.getOperand(0);
6347   
6348   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6349   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6350     if (CSI->isAllOnesValue())
6351       return ReplaceInstUsesWith(I, CSI);
6352   
6353   // See if we can turn a signed shr into an unsigned shr.
6354   if (MaskedValueIsZero(Op0, 
6355                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6356     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6357   
6358   return 0;
6359 }
6360
6361 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6362   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6363   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6364
6365   // shl X, 0 == X and shr X, 0 == X
6366   // shl 0, X == 0 and shr 0, X == 0
6367   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6368       Op0 == Constant::getNullValue(Op0->getType()))
6369     return ReplaceInstUsesWith(I, Op0);
6370   
6371   if (isa<UndefValue>(Op0)) {            
6372     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6373       return ReplaceInstUsesWith(I, Op0);
6374     else                                    // undef << X -> 0, undef >>u X -> 0
6375       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6376   }
6377   if (isa<UndefValue>(Op1)) {
6378     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6379       return ReplaceInstUsesWith(I, Op0);          
6380     else                                     // X << undef, X >>u undef -> 0
6381       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6382   }
6383
6384   // Try to fold constant and into select arguments.
6385   if (isa<Constant>(Op0))
6386     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6387       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6388         return R;
6389
6390   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6391     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6392       return Res;
6393   return 0;
6394 }
6395
6396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6397                                                BinaryOperator &I) {
6398   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6399
6400   // See if we can simplify any instructions used by the instruction whose sole 
6401   // purpose is to compute bits we don't care about.
6402   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6403   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6404   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6405                            KnownZero, KnownOne))
6406     return &I;
6407   
6408   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6409   // of a signed value.
6410   //
6411   if (Op1->uge(TypeBits)) {
6412     if (I.getOpcode() != Instruction::AShr)
6413       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6414     else {
6415       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6416       return &I;
6417     }
6418   }
6419   
6420   // ((X*C1) << C2) == (X * (C1 << C2))
6421   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6422     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6423       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6424         return BinaryOperator::CreateMul(BO->getOperand(0),
6425                                          ConstantExpr::getShl(BOOp, Op1));
6426   
6427   // Try to fold constant and into select arguments.
6428   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6429     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6430       return R;
6431   if (isa<PHINode>(Op0))
6432     if (Instruction *NV = FoldOpIntoPhi(I))
6433       return NV;
6434   
6435   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6436   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6437     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6438     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6439     // place.  Don't try to do this transformation in this case.  Also, we
6440     // require that the input operand is a shift-by-constant so that we have
6441     // confidence that the shifts will get folded together.  We could do this
6442     // xform in more cases, but it is unlikely to be profitable.
6443     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6444         isa<ConstantInt>(TrOp->getOperand(1))) {
6445       // Okay, we'll do this xform.  Make the shift of shift.
6446       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6447       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6448                                                 I.getName());
6449       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6450
6451       // For logical shifts, the truncation has the effect of making the high
6452       // part of the register be zeros.  Emulate this by inserting an AND to
6453       // clear the top bits as needed.  This 'and' will usually be zapped by
6454       // other xforms later if dead.
6455       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6456       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6457       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6458       
6459       // The mask we constructed says what the trunc would do if occurring
6460       // between the shifts.  We want to know the effect *after* the second
6461       // shift.  We know that it is a logical shift by a constant, so adjust the
6462       // mask as appropriate.
6463       if (I.getOpcode() == Instruction::Shl)
6464         MaskV <<= Op1->getZExtValue();
6465       else {
6466         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6467         MaskV = MaskV.lshr(Op1->getZExtValue());
6468       }
6469
6470       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6471                                                    TI->getName());
6472       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6473
6474       // Return the value truncated to the interesting size.
6475       return new TruncInst(And, I.getType());
6476     }
6477   }
6478   
6479   if (Op0->hasOneUse()) {
6480     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6481       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6482       Value *V1, *V2;
6483       ConstantInt *CC;
6484       switch (Op0BO->getOpcode()) {
6485         default: break;
6486         case Instruction::Add:
6487         case Instruction::And:
6488         case Instruction::Or:
6489         case Instruction::Xor: {
6490           // These operators commute.
6491           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6492           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6493               match(Op0BO->getOperand(1),
6494                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6495             Instruction *YS = BinaryOperator::CreateShl(
6496                                             Op0BO->getOperand(0), Op1,
6497                                             Op0BO->getName());
6498             InsertNewInstBefore(YS, I); // (Y << C)
6499             Instruction *X = 
6500               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6501                                      Op0BO->getOperand(1)->getName());
6502             InsertNewInstBefore(X, I);  // (X + (Y << C))
6503             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6504             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6505                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6506           }
6507           
6508           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6509           Value *Op0BOOp1 = Op0BO->getOperand(1);
6510           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6511               match(Op0BOOp1, 
6512                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6513               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6514               V2 == Op1) {
6515             Instruction *YS = BinaryOperator::CreateShl(
6516                                                      Op0BO->getOperand(0), Op1,
6517                                                      Op0BO->getName());
6518             InsertNewInstBefore(YS, I); // (Y << C)
6519             Instruction *XM =
6520               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6521                                         V1->getName()+".mask");
6522             InsertNewInstBefore(XM, I); // X & (CC << C)
6523             
6524             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6525           }
6526         }
6527           
6528         // FALL THROUGH.
6529         case Instruction::Sub: {
6530           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6531           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6532               match(Op0BO->getOperand(0),
6533                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6534             Instruction *YS = BinaryOperator::CreateShl(
6535                                                      Op0BO->getOperand(1), Op1,
6536                                                      Op0BO->getName());
6537             InsertNewInstBefore(YS, I); // (Y << C)
6538             Instruction *X =
6539               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6540                                      Op0BO->getOperand(0)->getName());
6541             InsertNewInstBefore(X, I);  // (X + (Y << C))
6542             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6543             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6544                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6545           }
6546           
6547           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6548           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6549               match(Op0BO->getOperand(0),
6550                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6551                           m_ConstantInt(CC))) && V2 == Op1 &&
6552               cast<BinaryOperator>(Op0BO->getOperand(0))
6553                   ->getOperand(0)->hasOneUse()) {
6554             Instruction *YS = BinaryOperator::CreateShl(
6555                                                      Op0BO->getOperand(1), Op1,
6556                                                      Op0BO->getName());
6557             InsertNewInstBefore(YS, I); // (Y << C)
6558             Instruction *XM =
6559               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6560                                         V1->getName()+".mask");
6561             InsertNewInstBefore(XM, I); // X & (CC << C)
6562             
6563             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6564           }
6565           
6566           break;
6567         }
6568       }
6569       
6570       
6571       // If the operand is an bitwise operator with a constant RHS, and the
6572       // shift is the only use, we can pull it out of the shift.
6573       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6574         bool isValid = true;     // Valid only for And, Or, Xor
6575         bool highBitSet = false; // Transform if high bit of constant set?
6576         
6577         switch (Op0BO->getOpcode()) {
6578           default: isValid = false; break;   // Do not perform transform!
6579           case Instruction::Add:
6580             isValid = isLeftShift;
6581             break;
6582           case Instruction::Or:
6583           case Instruction::Xor:
6584             highBitSet = false;
6585             break;
6586           case Instruction::And:
6587             highBitSet = true;
6588             break;
6589         }
6590         
6591         // If this is a signed shift right, and the high bit is modified
6592         // by the logical operation, do not perform the transformation.
6593         // The highBitSet boolean indicates the value of the high bit of
6594         // the constant which would cause it to be modified for this
6595         // operation.
6596         //
6597         if (isValid && I.getOpcode() == Instruction::AShr)
6598           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6599         
6600         if (isValid) {
6601           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6602           
6603           Instruction *NewShift =
6604             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6605           InsertNewInstBefore(NewShift, I);
6606           NewShift->takeName(Op0BO);
6607           
6608           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6609                                         NewRHS);
6610         }
6611       }
6612     }
6613   }
6614   
6615   // Find out if this is a shift of a shift by a constant.
6616   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6617   if (ShiftOp && !ShiftOp->isShift())
6618     ShiftOp = 0;
6619   
6620   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6621     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6622     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6623     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6624     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6625     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6626     Value *X = ShiftOp->getOperand(0);
6627     
6628     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6629     if (AmtSum > TypeBits)
6630       AmtSum = TypeBits;
6631     
6632     const IntegerType *Ty = cast<IntegerType>(I.getType());
6633     
6634     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6635     if (I.getOpcode() == ShiftOp->getOpcode()) {
6636       return BinaryOperator::Create(I.getOpcode(), X,
6637                                     ConstantInt::get(Ty, AmtSum));
6638     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6639                I.getOpcode() == Instruction::AShr) {
6640       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6641       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6642     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6643                I.getOpcode() == Instruction::LShr) {
6644       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6645       Instruction *Shift =
6646         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6647       InsertNewInstBefore(Shift, I);
6648
6649       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6650       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6651     }
6652     
6653     // Okay, if we get here, one shift must be left, and the other shift must be
6654     // right.  See if the amounts are equal.
6655     if (ShiftAmt1 == ShiftAmt2) {
6656       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6657       if (I.getOpcode() == Instruction::Shl) {
6658         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6659         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6660       }
6661       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6662       if (I.getOpcode() == Instruction::LShr) {
6663         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6664         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6665       }
6666       // We can simplify ((X << C) >>s C) into a trunc + sext.
6667       // NOTE: we could do this for any C, but that would make 'unusual' integer
6668       // types.  For now, just stick to ones well-supported by the code
6669       // generators.
6670       const Type *SExtType = 0;
6671       switch (Ty->getBitWidth() - ShiftAmt1) {
6672       case 1  :
6673       case 8  :
6674       case 16 :
6675       case 32 :
6676       case 64 :
6677       case 128:
6678         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6679         break;
6680       default: break;
6681       }
6682       if (SExtType) {
6683         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6684         InsertNewInstBefore(NewTrunc, I);
6685         return new SExtInst(NewTrunc, Ty);
6686       }
6687       // Otherwise, we can't handle it yet.
6688     } else if (ShiftAmt1 < ShiftAmt2) {
6689       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6690       
6691       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6692       if (I.getOpcode() == Instruction::Shl) {
6693         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6694                ShiftOp->getOpcode() == Instruction::AShr);
6695         Instruction *Shift =
6696           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6697         InsertNewInstBefore(Shift, I);
6698         
6699         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6700         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6701       }
6702       
6703       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6704       if (I.getOpcode() == Instruction::LShr) {
6705         assert(ShiftOp->getOpcode() == Instruction::Shl);
6706         Instruction *Shift =
6707           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6708         InsertNewInstBefore(Shift, I);
6709         
6710         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6711         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6712       }
6713       
6714       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6715     } else {
6716       assert(ShiftAmt2 < ShiftAmt1);
6717       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6718
6719       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6720       if (I.getOpcode() == Instruction::Shl) {
6721         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6722                ShiftOp->getOpcode() == Instruction::AShr);
6723         Instruction *Shift =
6724           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6725                                  ConstantInt::get(Ty, ShiftDiff));
6726         InsertNewInstBefore(Shift, I);
6727         
6728         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6729         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6730       }
6731       
6732       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6733       if (I.getOpcode() == Instruction::LShr) {
6734         assert(ShiftOp->getOpcode() == Instruction::Shl);
6735         Instruction *Shift =
6736           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6737         InsertNewInstBefore(Shift, I);
6738         
6739         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6740         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6741       }
6742       
6743       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6744     }
6745   }
6746   return 0;
6747 }
6748
6749
6750 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6751 /// expression.  If so, decompose it, returning some value X, such that Val is
6752 /// X*Scale+Offset.
6753 ///
6754 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6755                                         int &Offset) {
6756   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6757   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6758     Offset = CI->getZExtValue();
6759     Scale  = 0;
6760     return ConstantInt::get(Type::Int32Ty, 0);
6761   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6762     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6763       if (I->getOpcode() == Instruction::Shl) {
6764         // This is a value scaled by '1 << the shift amt'.
6765         Scale = 1U << RHS->getZExtValue();
6766         Offset = 0;
6767         return I->getOperand(0);
6768       } else if (I->getOpcode() == Instruction::Mul) {
6769         // This value is scaled by 'RHS'.
6770         Scale = RHS->getZExtValue();
6771         Offset = 0;
6772         return I->getOperand(0);
6773       } else if (I->getOpcode() == Instruction::Add) {
6774         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6775         // where C1 is divisible by C2.
6776         unsigned SubScale;
6777         Value *SubVal = 
6778           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6779         Offset += RHS->getZExtValue();
6780         Scale = SubScale;
6781         return SubVal;
6782       }
6783     }
6784   }
6785
6786   // Otherwise, we can't look past this.
6787   Scale = 1;
6788   Offset = 0;
6789   return Val;
6790 }
6791
6792
6793 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6794 /// try to eliminate the cast by moving the type information into the alloc.
6795 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6796                                                    AllocationInst &AI) {
6797   const PointerType *PTy = cast<PointerType>(CI.getType());
6798   
6799   // Remove any uses of AI that are dead.
6800   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6801   
6802   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6803     Instruction *User = cast<Instruction>(*UI++);
6804     if (isInstructionTriviallyDead(User)) {
6805       while (UI != E && *UI == User)
6806         ++UI; // If this instruction uses AI more than once, don't break UI.
6807       
6808       ++NumDeadInst;
6809       DOUT << "IC: DCE: " << *User;
6810       EraseInstFromFunction(*User);
6811     }
6812   }
6813   
6814   // Get the type really allocated and the type casted to.
6815   const Type *AllocElTy = AI.getAllocatedType();
6816   const Type *CastElTy = PTy->getElementType();
6817   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6818
6819   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6820   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6821   if (CastElTyAlign < AllocElTyAlign) return 0;
6822
6823   // If the allocation has multiple uses, only promote it if we are strictly
6824   // increasing the alignment of the resultant allocation.  If we keep it the
6825   // same, we open the door to infinite loops of various kinds.
6826   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6827
6828   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6829   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6830   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6831
6832   // See if we can satisfy the modulus by pulling a scale out of the array
6833   // size argument.
6834   unsigned ArraySizeScale;
6835   int ArrayOffset;
6836   Value *NumElements = // See if the array size is a decomposable linear expr.
6837     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6838  
6839   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6840   // do the xform.
6841   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6842       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6843
6844   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6845   Value *Amt = 0;
6846   if (Scale == 1) {
6847     Amt = NumElements;
6848   } else {
6849     // If the allocation size is constant, form a constant mul expression
6850     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6851     if (isa<ConstantInt>(NumElements))
6852       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6853     // otherwise multiply the amount and the number of elements
6854     else if (Scale != 1) {
6855       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6856       Amt = InsertNewInstBefore(Tmp, AI);
6857     }
6858   }
6859   
6860   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6861     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6862     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6863     Amt = InsertNewInstBefore(Tmp, AI);
6864   }
6865   
6866   AllocationInst *New;
6867   if (isa<MallocInst>(AI))
6868     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6869   else
6870     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6871   InsertNewInstBefore(New, AI);
6872   New->takeName(&AI);
6873   
6874   // If the allocation has multiple uses, insert a cast and change all things
6875   // that used it to use the new cast.  This will also hack on CI, but it will
6876   // die soon.
6877   if (!AI.hasOneUse()) {
6878     AddUsesToWorkList(AI);
6879     // New is the allocation instruction, pointer typed. AI is the original
6880     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6881     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6882     InsertNewInstBefore(NewCast, AI);
6883     AI.replaceAllUsesWith(NewCast);
6884   }
6885   return ReplaceInstUsesWith(CI, New);
6886 }
6887
6888 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6889 /// and return it as type Ty without inserting any new casts and without
6890 /// changing the computed value.  This is used by code that tries to decide
6891 /// whether promoting or shrinking integer operations to wider or smaller types
6892 /// will allow us to eliminate a truncate or extend.
6893 ///
6894 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6895 /// extension operation if Ty is larger.
6896 ///
6897 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6898 /// should return true if trunc(V) can be computed by computing V in the smaller
6899 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6900 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6901 /// efficiently truncated.
6902 ///
6903 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6904 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6905 /// the final result.
6906 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6907                                               unsigned CastOpc,
6908                                               int &NumCastsRemoved) {
6909   // We can always evaluate constants in another type.
6910   if (isa<ConstantInt>(V))
6911     return true;
6912   
6913   Instruction *I = dyn_cast<Instruction>(V);
6914   if (!I) return false;
6915   
6916   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6917   
6918   // If this is an extension or truncate, we can often eliminate it.
6919   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6920     // If this is a cast from the destination type, we can trivially eliminate
6921     // it, and this will remove a cast overall.
6922     if (I->getOperand(0)->getType() == Ty) {
6923       // If the first operand is itself a cast, and is eliminable, do not count
6924       // this as an eliminable cast.  We would prefer to eliminate those two
6925       // casts first.
6926       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6927         ++NumCastsRemoved;
6928       return true;
6929     }
6930   }
6931
6932   // We can't extend or shrink something that has multiple uses: doing so would
6933   // require duplicating the instruction in general, which isn't profitable.
6934   if (!I->hasOneUse()) return false;
6935
6936   switch (I->getOpcode()) {
6937   case Instruction::Add:
6938   case Instruction::Sub:
6939   case Instruction::Mul:
6940   case Instruction::And:
6941   case Instruction::Or:
6942   case Instruction::Xor:
6943     // These operators can all arbitrarily be extended or truncated.
6944     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6945                                       NumCastsRemoved) &&
6946            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6947                                       NumCastsRemoved);
6948
6949   case Instruction::Shl:
6950     // If we are truncating the result of this SHL, and if it's a shift of a
6951     // constant amount, we can always perform a SHL in a smaller type.
6952     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6953       uint32_t BitWidth = Ty->getBitWidth();
6954       if (BitWidth < OrigTy->getBitWidth() && 
6955           CI->getLimitedValue(BitWidth) < BitWidth)
6956         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6957                                           NumCastsRemoved);
6958     }
6959     break;
6960   case Instruction::LShr:
6961     // If this is a truncate of a logical shr, we can truncate it to a smaller
6962     // lshr iff we know that the bits we would otherwise be shifting in are
6963     // already zeros.
6964     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6965       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6966       uint32_t BitWidth = Ty->getBitWidth();
6967       if (BitWidth < OrigBitWidth &&
6968           MaskedValueIsZero(I->getOperand(0),
6969             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6970           CI->getLimitedValue(BitWidth) < BitWidth) {
6971         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6972                                           NumCastsRemoved);
6973       }
6974     }
6975     break;
6976   case Instruction::ZExt:
6977   case Instruction::SExt:
6978   case Instruction::Trunc:
6979     // If this is the same kind of case as our original (e.g. zext+zext), we
6980     // can safely replace it.  Note that replacing it does not reduce the number
6981     // of casts in the input.
6982     if (I->getOpcode() == CastOpc)
6983       return true;
6984     break;
6985   case Instruction::Select: {
6986     SelectInst *SI = cast<SelectInst>(I);
6987     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
6988                                       NumCastsRemoved) &&
6989            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
6990                                       NumCastsRemoved);
6991   }
6992   case Instruction::PHI: {
6993     // We can change a phi if we can change all operands.
6994     PHINode *PN = cast<PHINode>(I);
6995     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6996       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6997                                       NumCastsRemoved))
6998         return false;
6999     return true;
7000   }
7001   default:
7002     // TODO: Can handle more cases here.
7003     break;
7004   }
7005   
7006   return false;
7007 }
7008
7009 /// EvaluateInDifferentType - Given an expression that 
7010 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7011 /// evaluate the expression.
7012 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7013                                              bool isSigned) {
7014   if (Constant *C = dyn_cast<Constant>(V))
7015     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7016
7017   // Otherwise, it must be an instruction.
7018   Instruction *I = cast<Instruction>(V);
7019   Instruction *Res = 0;
7020   switch (I->getOpcode()) {
7021   case Instruction::Add:
7022   case Instruction::Sub:
7023   case Instruction::Mul:
7024   case Instruction::And:
7025   case Instruction::Or:
7026   case Instruction::Xor:
7027   case Instruction::AShr:
7028   case Instruction::LShr:
7029   case Instruction::Shl: {
7030     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7031     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7032     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7033                                  LHS, RHS);
7034     break;
7035   }    
7036   case Instruction::Trunc:
7037   case Instruction::ZExt:
7038   case Instruction::SExt:
7039     // If the source type of the cast is the type we're trying for then we can
7040     // just return the source.  There's no need to insert it because it is not
7041     // new.
7042     if (I->getOperand(0)->getType() == Ty)
7043       return I->getOperand(0);
7044     
7045     // Otherwise, must be the same type of cast, so just reinsert a new one.
7046     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7047                            Ty);
7048     break;
7049   case Instruction::Select: {
7050     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7051     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7052     Res = SelectInst::Create(I->getOperand(0), True, False);
7053     break;
7054   }
7055   case Instruction::PHI: {
7056     PHINode *OPN = cast<PHINode>(I);
7057     PHINode *NPN = PHINode::Create(Ty);
7058     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7059       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7060       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7061     }
7062     Res = NPN;
7063     break;
7064   }
7065   default: 
7066     // TODO: Can handle more cases here.
7067     assert(0 && "Unreachable!");
7068     break;
7069   }
7070   
7071   Res->takeName(I);
7072   return InsertNewInstBefore(Res, *I);
7073 }
7074
7075 /// @brief Implement the transforms common to all CastInst visitors.
7076 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7077   Value *Src = CI.getOperand(0);
7078
7079   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7080   // eliminate it now.
7081   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7082     if (Instruction::CastOps opc = 
7083         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7084       // The first cast (CSrc) is eliminable so we need to fix up or replace
7085       // the second cast (CI). CSrc will then have a good chance of being dead.
7086       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7087     }
7088   }
7089
7090   // If we are casting a select then fold the cast into the select
7091   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7092     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7093       return NV;
7094
7095   // If we are casting a PHI then fold the cast into the PHI
7096   if (isa<PHINode>(Src))
7097     if (Instruction *NV = FoldOpIntoPhi(CI))
7098       return NV;
7099   
7100   return 0;
7101 }
7102
7103 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7104 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7105   Value *Src = CI.getOperand(0);
7106   
7107   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7108     // If casting the result of a getelementptr instruction with no offset, turn
7109     // this into a cast of the original pointer!
7110     if (GEP->hasAllZeroIndices()) {
7111       // Changing the cast operand is usually not a good idea but it is safe
7112       // here because the pointer operand is being replaced with another 
7113       // pointer operand so the opcode doesn't need to change.
7114       AddToWorkList(GEP);
7115       CI.setOperand(0, GEP->getOperand(0));
7116       return &CI;
7117     }
7118     
7119     // If the GEP has a single use, and the base pointer is a bitcast, and the
7120     // GEP computes a constant offset, see if we can convert these three
7121     // instructions into fewer.  This typically happens with unions and other
7122     // non-type-safe code.
7123     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7124       if (GEP->hasAllConstantIndices()) {
7125         // We are guaranteed to get a constant from EmitGEPOffset.
7126         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7127         int64_t Offset = OffsetV->getSExtValue();
7128         
7129         // Get the base pointer input of the bitcast, and the type it points to.
7130         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7131         const Type *GEPIdxTy =
7132           cast<PointerType>(OrigBase->getType())->getElementType();
7133         if (GEPIdxTy->isSized()) {
7134           SmallVector<Value*, 8> NewIndices;
7135           
7136           // Start with the index over the outer type.  Note that the type size
7137           // might be zero (even if the offset isn't zero) if the indexed type
7138           // is something like [0 x {int, int}]
7139           const Type *IntPtrTy = TD->getIntPtrType();
7140           int64_t FirstIdx = 0;
7141           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7142             FirstIdx = Offset/TySize;
7143             Offset %= TySize;
7144           
7145             // Handle silly modulus not returning values values [0..TySize).
7146             if (Offset < 0) {
7147               --FirstIdx;
7148               Offset += TySize;
7149               assert(Offset >= 0);
7150             }
7151             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7152           }
7153           
7154           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7155
7156           // Index into the types.  If we fail, set OrigBase to null.
7157           while (Offset) {
7158             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7159               const StructLayout *SL = TD->getStructLayout(STy);
7160               if (Offset < (int64_t)SL->getSizeInBytes()) {
7161                 unsigned Elt = SL->getElementContainingOffset(Offset);
7162                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7163               
7164                 Offset -= SL->getElementOffset(Elt);
7165                 GEPIdxTy = STy->getElementType(Elt);
7166               } else {
7167                 // Otherwise, we can't index into this, bail out.
7168                 Offset = 0;
7169                 OrigBase = 0;
7170               }
7171             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7172               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7173               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7174                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7175                 Offset %= EltSize;
7176               } else {
7177                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7178               }
7179               GEPIdxTy = STy->getElementType();
7180             } else {
7181               // Otherwise, we can't index into this, bail out.
7182               Offset = 0;
7183               OrigBase = 0;
7184             }
7185           }
7186           if (OrigBase) {
7187             // If we were able to index down into an element, create the GEP
7188             // and bitcast the result.  This eliminates one bitcast, potentially
7189             // two.
7190             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7191                                                           NewIndices.begin(),
7192                                                           NewIndices.end(), "");
7193             InsertNewInstBefore(NGEP, CI);
7194             NGEP->takeName(GEP);
7195             
7196             if (isa<BitCastInst>(CI))
7197               return new BitCastInst(NGEP, CI.getType());
7198             assert(isa<PtrToIntInst>(CI));
7199             return new PtrToIntInst(NGEP, CI.getType());
7200           }
7201         }
7202       }      
7203     }
7204   }
7205     
7206   return commonCastTransforms(CI);
7207 }
7208
7209
7210
7211 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7212 /// integer types. This function implements the common transforms for all those
7213 /// cases.
7214 /// @brief Implement the transforms common to CastInst with integer operands
7215 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7216   if (Instruction *Result = commonCastTransforms(CI))
7217     return Result;
7218
7219   Value *Src = CI.getOperand(0);
7220   const Type *SrcTy = Src->getType();
7221   const Type *DestTy = CI.getType();
7222   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7223   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7224
7225   // See if we can simplify any instructions used by the LHS whose sole 
7226   // purpose is to compute bits we don't care about.
7227   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7228   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7229                            KnownZero, KnownOne))
7230     return &CI;
7231
7232   // If the source isn't an instruction or has more than one use then we
7233   // can't do anything more. 
7234   Instruction *SrcI = dyn_cast<Instruction>(Src);
7235   if (!SrcI || !Src->hasOneUse())
7236     return 0;
7237
7238   // Attempt to propagate the cast into the instruction for int->int casts.
7239   int NumCastsRemoved = 0;
7240   if (!isa<BitCastInst>(CI) &&
7241       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7242                                  CI.getOpcode(), NumCastsRemoved)) {
7243     // If this cast is a truncate, evaluting in a different type always
7244     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7245     // we need to do an AND to maintain the clear top-part of the computation,
7246     // so we require that the input have eliminated at least one cast.  If this
7247     // is a sign extension, we insert two new casts (to do the extension) so we
7248     // require that two casts have been eliminated.
7249     bool DoXForm;
7250     switch (CI.getOpcode()) {
7251     default:
7252       // All the others use floating point so we shouldn't actually 
7253       // get here because of the check above.
7254       assert(0 && "Unknown cast type");
7255     case Instruction::Trunc:
7256       DoXForm = true;
7257       break;
7258     case Instruction::ZExt:
7259       DoXForm = NumCastsRemoved >= 1;
7260       break;
7261     case Instruction::SExt:
7262       DoXForm = NumCastsRemoved >= 2;
7263       break;
7264     }
7265     
7266     if (DoXForm) {
7267       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7268                                            CI.getOpcode() == Instruction::SExt);
7269       assert(Res->getType() == DestTy);
7270       switch (CI.getOpcode()) {
7271       default: assert(0 && "Unknown cast type!");
7272       case Instruction::Trunc:
7273       case Instruction::BitCast:
7274         // Just replace this cast with the result.
7275         return ReplaceInstUsesWith(CI, Res);
7276       case Instruction::ZExt: {
7277         // We need to emit an AND to clear the high bits.
7278         assert(SrcBitSize < DestBitSize && "Not a zext?");
7279         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7280                                                             SrcBitSize));
7281         return BinaryOperator::CreateAnd(Res, C);
7282       }
7283       case Instruction::SExt:
7284         // We need to emit a cast to truncate, then a cast to sext.
7285         return CastInst::Create(Instruction::SExt,
7286             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7287                              CI), DestTy);
7288       }
7289     }
7290   }
7291   
7292   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7293   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7294
7295   switch (SrcI->getOpcode()) {
7296   case Instruction::Add:
7297   case Instruction::Mul:
7298   case Instruction::And:
7299   case Instruction::Or:
7300   case Instruction::Xor:
7301     // If we are discarding information, rewrite.
7302     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7303       // Don't insert two casts if they cannot be eliminated.  We allow 
7304       // two casts to be inserted if the sizes are the same.  This could 
7305       // only be converting signedness, which is a noop.
7306       if (DestBitSize == SrcBitSize || 
7307           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7308           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7309         Instruction::CastOps opcode = CI.getOpcode();
7310         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7311         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7312         return BinaryOperator::Create(
7313             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7314       }
7315     }
7316
7317     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7318     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7319         SrcI->getOpcode() == Instruction::Xor &&
7320         Op1 == ConstantInt::getTrue() &&
7321         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7322       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7323       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7324     }
7325     break;
7326   case Instruction::SDiv:
7327   case Instruction::UDiv:
7328   case Instruction::SRem:
7329   case Instruction::URem:
7330     // If we are just changing the sign, rewrite.
7331     if (DestBitSize == SrcBitSize) {
7332       // Don't insert two casts if they cannot be eliminated.  We allow 
7333       // two casts to be inserted if the sizes are the same.  This could 
7334       // only be converting signedness, which is a noop.
7335       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7336           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7337         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7338                                               Op0, DestTy, SrcI);
7339         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7340                                               Op1, DestTy, SrcI);
7341         return BinaryOperator::Create(
7342           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7343       }
7344     }
7345     break;
7346
7347   case Instruction::Shl:
7348     // Allow changing the sign of the source operand.  Do not allow 
7349     // changing the size of the shift, UNLESS the shift amount is a 
7350     // constant.  We must not change variable sized shifts to a smaller 
7351     // size, because it is undefined to shift more bits out than exist 
7352     // in the value.
7353     if (DestBitSize == SrcBitSize ||
7354         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7355       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7356           Instruction::BitCast : Instruction::Trunc);
7357       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7358       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7359       return BinaryOperator::CreateShl(Op0c, Op1c);
7360     }
7361     break;
7362   case Instruction::AShr:
7363     // If this is a signed shr, and if all bits shifted in are about to be
7364     // truncated off, turn it into an unsigned shr to allow greater
7365     // simplifications.
7366     if (DestBitSize < SrcBitSize &&
7367         isa<ConstantInt>(Op1)) {
7368       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7369       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7370         // Insert the new logical shift right.
7371         return BinaryOperator::CreateLShr(Op0, Op1);
7372       }
7373     }
7374     break;
7375   }
7376   return 0;
7377 }
7378
7379 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7380   if (Instruction *Result = commonIntCastTransforms(CI))
7381     return Result;
7382   
7383   Value *Src = CI.getOperand(0);
7384   const Type *Ty = CI.getType();
7385   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7386   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7387   
7388   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7389     switch (SrcI->getOpcode()) {
7390     default: break;
7391     case Instruction::LShr:
7392       // We can shrink lshr to something smaller if we know the bits shifted in
7393       // are already zeros.
7394       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7395         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7396         
7397         // Get a mask for the bits shifting in.
7398         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7399         Value* SrcIOp0 = SrcI->getOperand(0);
7400         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7401           if (ShAmt >= DestBitWidth)        // All zeros.
7402             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7403
7404           // Okay, we can shrink this.  Truncate the input, then return a new
7405           // shift.
7406           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7407           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7408                                        Ty, CI);
7409           return BinaryOperator::CreateLShr(V1, V2);
7410         }
7411       } else {     // This is a variable shr.
7412         
7413         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7414         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7415         // loop-invariant and CSE'd.
7416         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7417           Value *One = ConstantInt::get(SrcI->getType(), 1);
7418
7419           Value *V = InsertNewInstBefore(
7420               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7421                                      "tmp"), CI);
7422           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7423                                                             SrcI->getOperand(0),
7424                                                             "tmp"), CI);
7425           Value *Zero = Constant::getNullValue(V->getType());
7426           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7427         }
7428       }
7429       break;
7430     }
7431   }
7432   
7433   return 0;
7434 }
7435
7436 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7437 /// in order to eliminate the icmp.
7438 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7439                                              bool DoXform) {
7440   // If we are just checking for a icmp eq of a single bit and zext'ing it
7441   // to an integer, then shift the bit to the appropriate place and then
7442   // cast to integer to avoid the comparison.
7443   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7444     const APInt &Op1CV = Op1C->getValue();
7445       
7446     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7447     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7448     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7449         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7450       if (!DoXform) return ICI;
7451
7452       Value *In = ICI->getOperand(0);
7453       Value *Sh = ConstantInt::get(In->getType(),
7454                                    In->getType()->getPrimitiveSizeInBits()-1);
7455       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7456                                                         In->getName()+".lobit"),
7457                                CI);
7458       if (In->getType() != CI.getType())
7459         In = CastInst::CreateIntegerCast(In, CI.getType(),
7460                                          false/*ZExt*/, "tmp", &CI);
7461
7462       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7463         Constant *One = ConstantInt::get(In->getType(), 1);
7464         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7465                                                          In->getName()+".not"),
7466                                  CI);
7467       }
7468
7469       return ReplaceInstUsesWith(CI, In);
7470     }
7471       
7472       
7473       
7474     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7475     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7476     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7477     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7478     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7479     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7480     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7481     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7482     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7483         // This only works for EQ and NE
7484         ICI->isEquality()) {
7485       // If Op1C some other power of two, convert:
7486       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7487       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7488       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7489       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7490         
7491       APInt KnownZeroMask(~KnownZero);
7492       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7493         if (!DoXform) return ICI;
7494
7495         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7496         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7497           // (X&4) == 2 --> false
7498           // (X&4) != 2 --> true
7499           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7500           Res = ConstantExpr::getZExt(Res, CI.getType());
7501           return ReplaceInstUsesWith(CI, Res);
7502         }
7503           
7504         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7505         Value *In = ICI->getOperand(0);
7506         if (ShiftAmt) {
7507           // Perform a logical shr by shiftamt.
7508           // Insert the shift to put the result in the low bit.
7509           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7510                                   ConstantInt::get(In->getType(), ShiftAmt),
7511                                                    In->getName()+".lobit"), CI);
7512         }
7513           
7514         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7515           Constant *One = ConstantInt::get(In->getType(), 1);
7516           In = BinaryOperator::CreateXor(In, One, "tmp");
7517           InsertNewInstBefore(cast<Instruction>(In), CI);
7518         }
7519           
7520         if (CI.getType() == In->getType())
7521           return ReplaceInstUsesWith(CI, In);
7522         else
7523           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7524       }
7525     }
7526   }
7527
7528   return 0;
7529 }
7530
7531 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7532   // If one of the common conversion will work ..
7533   if (Instruction *Result = commonIntCastTransforms(CI))
7534     return Result;
7535
7536   Value *Src = CI.getOperand(0);
7537
7538   // If this is a cast of a cast
7539   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7540     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7541     // types and if the sizes are just right we can convert this into a logical
7542     // 'and' which will be much cheaper than the pair of casts.
7543     if (isa<TruncInst>(CSrc)) {
7544       // Get the sizes of the types involved
7545       Value *A = CSrc->getOperand(0);
7546       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7547       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7548       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7549       // If we're actually extending zero bits and the trunc is a no-op
7550       if (MidSize < DstSize && SrcSize == DstSize) {
7551         // Replace both of the casts with an And of the type mask.
7552         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7553         Constant *AndConst = ConstantInt::get(AndValue);
7554         Instruction *And = 
7555           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7556         // Unfortunately, if the type changed, we need to cast it back.
7557         if (And->getType() != CI.getType()) {
7558           And->setName(CSrc->getName()+".mask");
7559           InsertNewInstBefore(And, CI);
7560           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7561         }
7562         return And;
7563       }
7564     }
7565   }
7566
7567   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7568     return transformZExtICmp(ICI, CI);
7569
7570   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7571   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7572     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7573     // of the (zext icmp) will be transformed.
7574     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7575     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7576     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7577         (transformZExtICmp(LHS, CI, false) ||
7578          transformZExtICmp(RHS, CI, false))) {
7579       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7580       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7581       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7582     }
7583   }
7584
7585   return 0;
7586 }
7587
7588 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7589   if (Instruction *I = commonIntCastTransforms(CI))
7590     return I;
7591   
7592   Value *Src = CI.getOperand(0);
7593   
7594   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7595   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7596   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7597     // If we are just checking for a icmp eq of a single bit and zext'ing it
7598     // to an integer, then shift the bit to the appropriate place and then
7599     // cast to integer to avoid the comparison.
7600     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7601       const APInt &Op1CV = Op1C->getValue();
7602       
7603       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7604       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7605       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7606           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7607         Value *In = ICI->getOperand(0);
7608         Value *Sh = ConstantInt::get(In->getType(),
7609                                      In->getType()->getPrimitiveSizeInBits()-1);
7610         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7611                                                         In->getName()+".lobit"),
7612                                  CI);
7613         if (In->getType() != CI.getType())
7614           In = CastInst::CreateIntegerCast(In, CI.getType(),
7615                                            true/*SExt*/, "tmp", &CI);
7616         
7617         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7618           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7619                                      In->getName()+".not"), CI);
7620         
7621         return ReplaceInstUsesWith(CI, In);
7622       }
7623     }
7624   }
7625
7626   // See if the value being truncated is already sign extended.  If so, just
7627   // eliminate the trunc/sext pair.
7628   if (getOpcode(Src) == Instruction::Trunc) {
7629     Value *Op = cast<User>(Src)->getOperand(0);
7630     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7631     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7632     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7633     unsigned NumSignBits = ComputeNumSignBits(Op);
7634
7635     if (OpBits == DestBits) {
7636       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7637       // bits, it is already ready.
7638       if (NumSignBits > DestBits-MidBits)
7639         return ReplaceInstUsesWith(CI, Op);
7640     } else if (OpBits < DestBits) {
7641       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7642       // bits, just sext from i32.
7643       if (NumSignBits > OpBits-MidBits)
7644         return new SExtInst(Op, CI.getType(), "tmp");
7645     } else {
7646       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7647       // bits, just truncate to i32.
7648       if (NumSignBits > OpBits-MidBits)
7649         return new TruncInst(Op, CI.getType(), "tmp");
7650     }
7651   }
7652       
7653   return 0;
7654 }
7655
7656 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7657 /// in the specified FP type without changing its value.
7658 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7659   APFloat F = CFP->getValueAPF();
7660   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7661     return ConstantFP::get(F);
7662   return 0;
7663 }
7664
7665 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7666 /// through it until we get the source value.
7667 static Value *LookThroughFPExtensions(Value *V) {
7668   if (Instruction *I = dyn_cast<Instruction>(V))
7669     if (I->getOpcode() == Instruction::FPExt)
7670       return LookThroughFPExtensions(I->getOperand(0));
7671   
7672   // If this value is a constant, return the constant in the smallest FP type
7673   // that can accurately represent it.  This allows us to turn
7674   // (float)((double)X+2.0) into x+2.0f.
7675   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7676     if (CFP->getType() == Type::PPC_FP128Ty)
7677       return V;  // No constant folding of this.
7678     // See if the value can be truncated to float and then reextended.
7679     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7680       return V;
7681     if (CFP->getType() == Type::DoubleTy)
7682       return V;  // Won't shrink.
7683     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7684       return V;
7685     // Don't try to shrink to various long double types.
7686   }
7687   
7688   return V;
7689 }
7690
7691 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7692   if (Instruction *I = commonCastTransforms(CI))
7693     return I;
7694   
7695   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7696   // smaller than the destination type, we can eliminate the truncate by doing
7697   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7698   // many builtins (sqrt, etc).
7699   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7700   if (OpI && OpI->hasOneUse()) {
7701     switch (OpI->getOpcode()) {
7702     default: break;
7703     case Instruction::Add:
7704     case Instruction::Sub:
7705     case Instruction::Mul:
7706     case Instruction::FDiv:
7707     case Instruction::FRem:
7708       const Type *SrcTy = OpI->getType();
7709       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7710       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7711       if (LHSTrunc->getType() != SrcTy && 
7712           RHSTrunc->getType() != SrcTy) {
7713         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7714         // If the source types were both smaller than the destination type of
7715         // the cast, do this xform.
7716         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7717             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7718           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7719                                       CI.getType(), CI);
7720           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7721                                       CI.getType(), CI);
7722           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7723         }
7724       }
7725       break;  
7726     }
7727   }
7728   return 0;
7729 }
7730
7731 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7732   return commonCastTransforms(CI);
7733 }
7734
7735 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7736   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7737   // mantissa to accurately represent all values of X.  For example, do not
7738   // do this with i64->float->i64.
7739   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7740     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7741         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7742                     SrcI->getType()->getFPMantissaWidth())
7743       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7744
7745   return commonCastTransforms(FI);
7746 }
7747
7748 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7749   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7750   // mantissa to accurately represent all values of X.  For example, do not
7751   // do this with i64->float->i64.
7752   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7753     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7754         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7755                     SrcI->getType()->getFPMantissaWidth())
7756       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7757   
7758   return commonCastTransforms(FI);
7759 }
7760
7761 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7762   return commonCastTransforms(CI);
7763 }
7764
7765 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7766   return commonCastTransforms(CI);
7767 }
7768
7769 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7770   return commonPointerCastTransforms(CI);
7771 }
7772
7773 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7774   if (Instruction *I = commonCastTransforms(CI))
7775     return I;
7776   
7777   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7778   if (!DestPointee->isSized()) return 0;
7779
7780   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7781   ConstantInt *Cst;
7782   Value *X;
7783   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7784                                     m_ConstantInt(Cst)))) {
7785     // If the source and destination operands have the same type, see if this
7786     // is a single-index GEP.
7787     if (X->getType() == CI.getType()) {
7788       // Get the size of the pointee type.
7789       uint64_t Size = TD->getABITypeSize(DestPointee);
7790
7791       // Convert the constant to intptr type.
7792       APInt Offset = Cst->getValue();
7793       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7794
7795       // If Offset is evenly divisible by Size, we can do this xform.
7796       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7797         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7798         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7799       }
7800     }
7801     // TODO: Could handle other cases, e.g. where add is indexing into field of
7802     // struct etc.
7803   } else if (CI.getOperand(0)->hasOneUse() &&
7804              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7805     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7806     // "inttoptr+GEP" instead of "add+intptr".
7807     
7808     // Get the size of the pointee type.
7809     uint64_t Size = TD->getABITypeSize(DestPointee);
7810     
7811     // Convert the constant to intptr type.
7812     APInt Offset = Cst->getValue();
7813     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7814     
7815     // If Offset is evenly divisible by Size, we can do this xform.
7816     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7817       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7818       
7819       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7820                                                             "tmp"), CI);
7821       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7822     }
7823   }
7824   return 0;
7825 }
7826
7827 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7828   // If the operands are integer typed then apply the integer transforms,
7829   // otherwise just apply the common ones.
7830   Value *Src = CI.getOperand(0);
7831   const Type *SrcTy = Src->getType();
7832   const Type *DestTy = CI.getType();
7833
7834   if (SrcTy->isInteger() && DestTy->isInteger()) {
7835     if (Instruction *Result = commonIntCastTransforms(CI))
7836       return Result;
7837   } else if (isa<PointerType>(SrcTy)) {
7838     if (Instruction *I = commonPointerCastTransforms(CI))
7839       return I;
7840   } else {
7841     if (Instruction *Result = commonCastTransforms(CI))
7842       return Result;
7843   }
7844
7845
7846   // Get rid of casts from one type to the same type. These are useless and can
7847   // be replaced by the operand.
7848   if (DestTy == Src->getType())
7849     return ReplaceInstUsesWith(CI, Src);
7850
7851   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7852     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7853     const Type *DstElTy = DstPTy->getElementType();
7854     const Type *SrcElTy = SrcPTy->getElementType();
7855     
7856     // If the address spaces don't match, don't eliminate the bitcast, which is
7857     // required for changing types.
7858     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7859       return 0;
7860     
7861     // If we are casting a malloc or alloca to a pointer to a type of the same
7862     // size, rewrite the allocation instruction to allocate the "right" type.
7863     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7864       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7865         return V;
7866     
7867     // If the source and destination are pointers, and this cast is equivalent
7868     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7869     // This can enhance SROA and other transforms that want type-safe pointers.
7870     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7871     unsigned NumZeros = 0;
7872     while (SrcElTy != DstElTy && 
7873            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7874            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7875       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7876       ++NumZeros;
7877     }
7878
7879     // If we found a path from the src to dest, create the getelementptr now.
7880     if (SrcElTy == DstElTy) {
7881       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7882       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7883                                        ((Instruction*) NULL));
7884     }
7885   }
7886
7887   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7888     if (SVI->hasOneUse()) {
7889       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7890       // a bitconvert to a vector with the same # elts.
7891       if (isa<VectorType>(DestTy) && 
7892           cast<VectorType>(DestTy)->getNumElements() == 
7893                 SVI->getType()->getNumElements()) {
7894         CastInst *Tmp;
7895         // If either of the operands is a cast from CI.getType(), then
7896         // evaluating the shuffle in the casted destination's type will allow
7897         // us to eliminate at least one cast.
7898         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7899              Tmp->getOperand(0)->getType() == DestTy) ||
7900             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7901              Tmp->getOperand(0)->getType() == DestTy)) {
7902           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7903                                                SVI->getOperand(0), DestTy, &CI);
7904           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7905                                                SVI->getOperand(1), DestTy, &CI);
7906           // Return a new shuffle vector.  Use the same element ID's, as we
7907           // know the vector types match #elts.
7908           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7909         }
7910       }
7911     }
7912   }
7913   return 0;
7914 }
7915
7916 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7917 ///   %C = or %A, %B
7918 ///   %D = select %cond, %C, %A
7919 /// into:
7920 ///   %C = select %cond, %B, 0
7921 ///   %D = or %A, %C
7922 ///
7923 /// Assuming that the specified instruction is an operand to the select, return
7924 /// a bitmask indicating which operands of this instruction are foldable if they
7925 /// equal the other incoming value of the select.
7926 ///
7927 static unsigned GetSelectFoldableOperands(Instruction *I) {
7928   switch (I->getOpcode()) {
7929   case Instruction::Add:
7930   case Instruction::Mul:
7931   case Instruction::And:
7932   case Instruction::Or:
7933   case Instruction::Xor:
7934     return 3;              // Can fold through either operand.
7935   case Instruction::Sub:   // Can only fold on the amount subtracted.
7936   case Instruction::Shl:   // Can only fold on the shift amount.
7937   case Instruction::LShr:
7938   case Instruction::AShr:
7939     return 1;
7940   default:
7941     return 0;              // Cannot fold
7942   }
7943 }
7944
7945 /// GetSelectFoldableConstant - For the same transformation as the previous
7946 /// function, return the identity constant that goes into the select.
7947 static Constant *GetSelectFoldableConstant(Instruction *I) {
7948   switch (I->getOpcode()) {
7949   default: assert(0 && "This cannot happen!"); abort();
7950   case Instruction::Add:
7951   case Instruction::Sub:
7952   case Instruction::Or:
7953   case Instruction::Xor:
7954   case Instruction::Shl:
7955   case Instruction::LShr:
7956   case Instruction::AShr:
7957     return Constant::getNullValue(I->getType());
7958   case Instruction::And:
7959     return Constant::getAllOnesValue(I->getType());
7960   case Instruction::Mul:
7961     return ConstantInt::get(I->getType(), 1);
7962   }
7963 }
7964
7965 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7966 /// have the same opcode and only one use each.  Try to simplify this.
7967 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7968                                           Instruction *FI) {
7969   if (TI->getNumOperands() == 1) {
7970     // If this is a non-volatile load or a cast from the same type,
7971     // merge.
7972     if (TI->isCast()) {
7973       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7974         return 0;
7975     } else {
7976       return 0;  // unknown unary op.
7977     }
7978
7979     // Fold this by inserting a select from the input values.
7980     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7981                                            FI->getOperand(0), SI.getName()+".v");
7982     InsertNewInstBefore(NewSI, SI);
7983     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7984                             TI->getType());
7985   }
7986
7987   // Only handle binary operators here.
7988   if (!isa<BinaryOperator>(TI))
7989     return 0;
7990
7991   // Figure out if the operations have any operands in common.
7992   Value *MatchOp, *OtherOpT, *OtherOpF;
7993   bool MatchIsOpZero;
7994   if (TI->getOperand(0) == FI->getOperand(0)) {
7995     MatchOp  = TI->getOperand(0);
7996     OtherOpT = TI->getOperand(1);
7997     OtherOpF = FI->getOperand(1);
7998     MatchIsOpZero = true;
7999   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8000     MatchOp  = TI->getOperand(1);
8001     OtherOpT = TI->getOperand(0);
8002     OtherOpF = FI->getOperand(0);
8003     MatchIsOpZero = false;
8004   } else if (!TI->isCommutative()) {
8005     return 0;
8006   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8007     MatchOp  = TI->getOperand(0);
8008     OtherOpT = TI->getOperand(1);
8009     OtherOpF = FI->getOperand(0);
8010     MatchIsOpZero = true;
8011   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8012     MatchOp  = TI->getOperand(1);
8013     OtherOpT = TI->getOperand(0);
8014     OtherOpF = FI->getOperand(1);
8015     MatchIsOpZero = true;
8016   } else {
8017     return 0;
8018   }
8019
8020   // If we reach here, they do have operations in common.
8021   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8022                                          OtherOpF, SI.getName()+".v");
8023   InsertNewInstBefore(NewSI, SI);
8024
8025   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8026     if (MatchIsOpZero)
8027       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8028     else
8029       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8030   }
8031   assert(0 && "Shouldn't get here");
8032   return 0;
8033 }
8034
8035 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8036   Value *CondVal = SI.getCondition();
8037   Value *TrueVal = SI.getTrueValue();
8038   Value *FalseVal = SI.getFalseValue();
8039
8040   // select true, X, Y  -> X
8041   // select false, X, Y -> Y
8042   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8043     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8044
8045   // select C, X, X -> X
8046   if (TrueVal == FalseVal)
8047     return ReplaceInstUsesWith(SI, TrueVal);
8048
8049   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8050     return ReplaceInstUsesWith(SI, FalseVal);
8051   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8052     return ReplaceInstUsesWith(SI, TrueVal);
8053   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8054     if (isa<Constant>(TrueVal))
8055       return ReplaceInstUsesWith(SI, TrueVal);
8056     else
8057       return ReplaceInstUsesWith(SI, FalseVal);
8058   }
8059
8060   if (SI.getType() == Type::Int1Ty) {
8061     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8062       if (C->getZExtValue()) {
8063         // Change: A = select B, true, C --> A = or B, C
8064         return BinaryOperator::CreateOr(CondVal, FalseVal);
8065       } else {
8066         // Change: A = select B, false, C --> A = and !B, C
8067         Value *NotCond =
8068           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8069                                              "not."+CondVal->getName()), SI);
8070         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8071       }
8072     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8073       if (C->getZExtValue() == false) {
8074         // Change: A = select B, C, false --> A = and B, C
8075         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8076       } else {
8077         // Change: A = select B, C, true --> A = or !B, C
8078         Value *NotCond =
8079           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8080                                              "not."+CondVal->getName()), SI);
8081         return BinaryOperator::CreateOr(NotCond, TrueVal);
8082       }
8083     }
8084     
8085     // select a, b, a  -> a&b
8086     // select a, a, b  -> a|b
8087     if (CondVal == TrueVal)
8088       return BinaryOperator::CreateOr(CondVal, FalseVal);
8089     else if (CondVal == FalseVal)
8090       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8091   }
8092
8093   // Selecting between two integer constants?
8094   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8095     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8096       // select C, 1, 0 -> zext C to int
8097       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8098         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8099       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8100         // select C, 0, 1 -> zext !C to int
8101         Value *NotCond =
8102           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8103                                                "not."+CondVal->getName()), SI);
8104         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8105       }
8106       
8107       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8108
8109       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8110
8111         // (x <s 0) ? -1 : 0 -> ashr x, 31
8112         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8113           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8114             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8115               // The comparison constant and the result are not neccessarily the
8116               // same width. Make an all-ones value by inserting a AShr.
8117               Value *X = IC->getOperand(0);
8118               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8119               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8120               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8121                                                         ShAmt, "ones");
8122               InsertNewInstBefore(SRA, SI);
8123               
8124               // Finally, convert to the type of the select RHS.  We figure out
8125               // if this requires a SExt, Trunc or BitCast based on the sizes.
8126               Instruction::CastOps opc = Instruction::BitCast;
8127               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8128               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8129               if (SRASize < SISize)
8130                 opc = Instruction::SExt;
8131               else if (SRASize > SISize)
8132                 opc = Instruction::Trunc;
8133               return CastInst::Create(opc, SRA, SI.getType());
8134             }
8135           }
8136
8137
8138         // If one of the constants is zero (we know they can't both be) and we
8139         // have an icmp instruction with zero, and we have an 'and' with the
8140         // non-constant value, eliminate this whole mess.  This corresponds to
8141         // cases like this: ((X & 27) ? 27 : 0)
8142         if (TrueValC->isZero() || FalseValC->isZero())
8143           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8144               cast<Constant>(IC->getOperand(1))->isNullValue())
8145             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8146               if (ICA->getOpcode() == Instruction::And &&
8147                   isa<ConstantInt>(ICA->getOperand(1)) &&
8148                   (ICA->getOperand(1) == TrueValC ||
8149                    ICA->getOperand(1) == FalseValC) &&
8150                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8151                 // Okay, now we know that everything is set up, we just don't
8152                 // know whether we have a icmp_ne or icmp_eq and whether the 
8153                 // true or false val is the zero.
8154                 bool ShouldNotVal = !TrueValC->isZero();
8155                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8156                 Value *V = ICA;
8157                 if (ShouldNotVal)
8158                   V = InsertNewInstBefore(BinaryOperator::Create(
8159                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8160                 return ReplaceInstUsesWith(SI, V);
8161               }
8162       }
8163     }
8164
8165   // See if we are selecting two values based on a comparison of the two values.
8166   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8167     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8168       // Transform (X == Y) ? X : Y  -> Y
8169       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8170         // This is not safe in general for floating point:  
8171         // consider X== -0, Y== +0.
8172         // It becomes safe if either operand is a nonzero constant.
8173         ConstantFP *CFPt, *CFPf;
8174         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8175               !CFPt->getValueAPF().isZero()) ||
8176             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8177              !CFPf->getValueAPF().isZero()))
8178         return ReplaceInstUsesWith(SI, FalseVal);
8179       }
8180       // Transform (X != Y) ? X : Y  -> X
8181       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8182         return ReplaceInstUsesWith(SI, TrueVal);
8183       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8184
8185     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8186       // Transform (X == Y) ? Y : X  -> X
8187       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8188         // This is not safe in general for floating point:  
8189         // consider X== -0, Y== +0.
8190         // It becomes safe if either operand is a nonzero constant.
8191         ConstantFP *CFPt, *CFPf;
8192         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8193               !CFPt->getValueAPF().isZero()) ||
8194             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8195              !CFPf->getValueAPF().isZero()))
8196           return ReplaceInstUsesWith(SI, FalseVal);
8197       }
8198       // Transform (X != Y) ? Y : X  -> Y
8199       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8200         return ReplaceInstUsesWith(SI, TrueVal);
8201       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8202     }
8203   }
8204
8205   // See if we are selecting two values based on a comparison of the two values.
8206   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8207     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8208       // Transform (X == Y) ? X : Y  -> Y
8209       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8210         return ReplaceInstUsesWith(SI, FalseVal);
8211       // Transform (X != Y) ? X : Y  -> X
8212       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8213         return ReplaceInstUsesWith(SI, TrueVal);
8214       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8215
8216     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8217       // Transform (X == Y) ? Y : X  -> X
8218       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8219         return ReplaceInstUsesWith(SI, FalseVal);
8220       // Transform (X != Y) ? Y : X  -> Y
8221       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8222         return ReplaceInstUsesWith(SI, TrueVal);
8223       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8224     }
8225   }
8226
8227   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8228     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8229       if (TI->hasOneUse() && FI->hasOneUse()) {
8230         Instruction *AddOp = 0, *SubOp = 0;
8231
8232         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8233         if (TI->getOpcode() == FI->getOpcode())
8234           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8235             return IV;
8236
8237         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8238         // even legal for FP.
8239         if (TI->getOpcode() == Instruction::Sub &&
8240             FI->getOpcode() == Instruction::Add) {
8241           AddOp = FI; SubOp = TI;
8242         } else if (FI->getOpcode() == Instruction::Sub &&
8243                    TI->getOpcode() == Instruction::Add) {
8244           AddOp = TI; SubOp = FI;
8245         }
8246
8247         if (AddOp) {
8248           Value *OtherAddOp = 0;
8249           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8250             OtherAddOp = AddOp->getOperand(1);
8251           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8252             OtherAddOp = AddOp->getOperand(0);
8253           }
8254
8255           if (OtherAddOp) {
8256             // So at this point we know we have (Y -> OtherAddOp):
8257             //        select C, (add X, Y), (sub X, Z)
8258             Value *NegVal;  // Compute -Z
8259             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8260               NegVal = ConstantExpr::getNeg(C);
8261             } else {
8262               NegVal = InsertNewInstBefore(
8263                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8264             }
8265
8266             Value *NewTrueOp = OtherAddOp;
8267             Value *NewFalseOp = NegVal;
8268             if (AddOp != TI)
8269               std::swap(NewTrueOp, NewFalseOp);
8270             Instruction *NewSel =
8271               SelectInst::Create(CondVal, NewTrueOp,
8272                                  NewFalseOp, SI.getName() + ".p");
8273
8274             NewSel = InsertNewInstBefore(NewSel, SI);
8275             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8276           }
8277         }
8278       }
8279
8280   // See if we can fold the select into one of our operands.
8281   if (SI.getType()->isInteger()) {
8282     // See the comment above GetSelectFoldableOperands for a description of the
8283     // transformation we are doing here.
8284     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8285       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8286           !isa<Constant>(FalseVal))
8287         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8288           unsigned OpToFold = 0;
8289           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8290             OpToFold = 1;
8291           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8292             OpToFold = 2;
8293           }
8294
8295           if (OpToFold) {
8296             Constant *C = GetSelectFoldableConstant(TVI);
8297             Instruction *NewSel =
8298               SelectInst::Create(SI.getCondition(),
8299                                  TVI->getOperand(2-OpToFold), C);
8300             InsertNewInstBefore(NewSel, SI);
8301             NewSel->takeName(TVI);
8302             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8303               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8304             else {
8305               assert(0 && "Unknown instruction!!");
8306             }
8307           }
8308         }
8309
8310     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8311       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8312           !isa<Constant>(TrueVal))
8313         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8314           unsigned OpToFold = 0;
8315           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8316             OpToFold = 1;
8317           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8318             OpToFold = 2;
8319           }
8320
8321           if (OpToFold) {
8322             Constant *C = GetSelectFoldableConstant(FVI);
8323             Instruction *NewSel =
8324               SelectInst::Create(SI.getCondition(), C,
8325                                  FVI->getOperand(2-OpToFold));
8326             InsertNewInstBefore(NewSel, SI);
8327             NewSel->takeName(FVI);
8328             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8329               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8330             else
8331               assert(0 && "Unknown instruction!!");
8332           }
8333         }
8334   }
8335
8336   if (BinaryOperator::isNot(CondVal)) {
8337     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8338     SI.setOperand(1, FalseVal);
8339     SI.setOperand(2, TrueVal);
8340     return &SI;
8341   }
8342
8343   return 0;
8344 }
8345
8346 /// EnforceKnownAlignment - If the specified pointer points to an object that
8347 /// we control, modify the object's alignment to PrefAlign. This isn't
8348 /// often possible though. If alignment is important, a more reliable approach
8349 /// is to simply align all global variables and allocation instructions to
8350 /// their preferred alignment from the beginning.
8351 ///
8352 static unsigned EnforceKnownAlignment(Value *V,
8353                                       unsigned Align, unsigned PrefAlign) {
8354
8355   User *U = dyn_cast<User>(V);
8356   if (!U) return Align;
8357
8358   switch (getOpcode(U)) {
8359   default: break;
8360   case Instruction::BitCast:
8361     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8362   case Instruction::GetElementPtr: {
8363     // If all indexes are zero, it is just the alignment of the base pointer.
8364     bool AllZeroOperands = true;
8365     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8366       if (!isa<Constant>(*i) ||
8367           !cast<Constant>(*i)->isNullValue()) {
8368         AllZeroOperands = false;
8369         break;
8370       }
8371
8372     if (AllZeroOperands) {
8373       // Treat this like a bitcast.
8374       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8375     }
8376     break;
8377   }
8378   }
8379
8380   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8381     // If there is a large requested alignment and we can, bump up the alignment
8382     // of the global.
8383     if (!GV->isDeclaration()) {
8384       GV->setAlignment(PrefAlign);
8385       Align = PrefAlign;
8386     }
8387   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8388     // If there is a requested alignment and if this is an alloca, round up.  We
8389     // don't do this for malloc, because some systems can't respect the request.
8390     if (isa<AllocaInst>(AI)) {
8391       AI->setAlignment(PrefAlign);
8392       Align = PrefAlign;
8393     }
8394   }
8395
8396   return Align;
8397 }
8398
8399 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8400 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8401 /// and it is more than the alignment of the ultimate object, see if we can
8402 /// increase the alignment of the ultimate object, making this check succeed.
8403 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8404                                                   unsigned PrefAlign) {
8405   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8406                       sizeof(PrefAlign) * CHAR_BIT;
8407   APInt Mask = APInt::getAllOnesValue(BitWidth);
8408   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8409   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8410   unsigned TrailZ = KnownZero.countTrailingOnes();
8411   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8412
8413   if (PrefAlign > Align)
8414     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8415   
8416     // We don't need to make any adjustment.
8417   return Align;
8418 }
8419
8420 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8421   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8422   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8423   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8424   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8425
8426   if (CopyAlign < MinAlign) {
8427     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8428     return MI;
8429   }
8430   
8431   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8432   // load/store.
8433   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8434   if (MemOpLength == 0) return 0;
8435   
8436   // Source and destination pointer types are always "i8*" for intrinsic.  See
8437   // if the size is something we can handle with a single primitive load/store.
8438   // A single load+store correctly handles overlapping memory in the memmove
8439   // case.
8440   unsigned Size = MemOpLength->getZExtValue();
8441   if (Size == 0) return MI;  // Delete this mem transfer.
8442   
8443   if (Size > 8 || (Size&(Size-1)))
8444     return 0;  // If not 1/2/4/8 bytes, exit.
8445   
8446   // Use an integer load+store unless we can find something better.
8447   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8448   
8449   // Memcpy forces the use of i8* for the source and destination.  That means
8450   // that if you're using memcpy to move one double around, you'll get a cast
8451   // from double* to i8*.  We'd much rather use a double load+store rather than
8452   // an i64 load+store, here because this improves the odds that the source or
8453   // dest address will be promotable.  See if we can find a better type than the
8454   // integer datatype.
8455   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8456     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8457     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8458       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8459       // down through these levels if so.
8460       while (!SrcETy->isSingleValueType()) {
8461         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8462           if (STy->getNumElements() == 1)
8463             SrcETy = STy->getElementType(0);
8464           else
8465             break;
8466         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8467           if (ATy->getNumElements() == 1)
8468             SrcETy = ATy->getElementType();
8469           else
8470             break;
8471         } else
8472           break;
8473       }
8474       
8475       if (SrcETy->isSingleValueType())
8476         NewPtrTy = PointerType::getUnqual(SrcETy);
8477     }
8478   }
8479   
8480   
8481   // If the memcpy/memmove provides better alignment info than we can
8482   // infer, use it.
8483   SrcAlign = std::max(SrcAlign, CopyAlign);
8484   DstAlign = std::max(DstAlign, CopyAlign);
8485   
8486   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8487   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8488   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8489   InsertNewInstBefore(L, *MI);
8490   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8491
8492   // Set the size of the copy to 0, it will be deleted on the next iteration.
8493   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8494   return MI;
8495 }
8496
8497 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8498   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8499   if (MI->getAlignment()->getZExtValue() < Alignment) {
8500     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8501     return MI;
8502   }
8503   
8504   // Extract the length and alignment and fill if they are constant.
8505   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8506   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8507   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8508     return 0;
8509   uint64_t Len = LenC->getZExtValue();
8510   Alignment = MI->getAlignment()->getZExtValue();
8511   
8512   // If the length is zero, this is a no-op
8513   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8514   
8515   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8516   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8517     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8518     
8519     Value *Dest = MI->getDest();
8520     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8521
8522     // Alignment 0 is identity for alignment 1 for memset, but not store.
8523     if (Alignment == 0) Alignment = 1;
8524     
8525     // Extract the fill value and store.
8526     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8527     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8528                                       Alignment), *MI);
8529     
8530     // Set the size of the copy to 0, it will be deleted on the next iteration.
8531     MI->setLength(Constant::getNullValue(LenC->getType()));
8532     return MI;
8533   }
8534
8535   return 0;
8536 }
8537
8538
8539 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8540 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8541 /// the heavy lifting.
8542 ///
8543 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8544   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8545   if (!II) return visitCallSite(&CI);
8546   
8547   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8548   // visitCallSite.
8549   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8550     bool Changed = false;
8551
8552     // memmove/cpy/set of zero bytes is a noop.
8553     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8554       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8555
8556       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8557         if (CI->getZExtValue() == 1) {
8558           // Replace the instruction with just byte operations.  We would
8559           // transform other cases to loads/stores, but we don't know if
8560           // alignment is sufficient.
8561         }
8562     }
8563
8564     // If we have a memmove and the source operation is a constant global,
8565     // then the source and dest pointers can't alias, so we can change this
8566     // into a call to memcpy.
8567     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8568       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8569         if (GVSrc->isConstant()) {
8570           Module *M = CI.getParent()->getParent()->getParent();
8571           Intrinsic::ID MemCpyID;
8572           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8573             MemCpyID = Intrinsic::memcpy_i32;
8574           else
8575             MemCpyID = Intrinsic::memcpy_i64;
8576           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8577           Changed = true;
8578         }
8579
8580       // memmove(x,x,size) -> noop.
8581       if (MMI->getSource() == MMI->getDest())
8582         return EraseInstFromFunction(CI);
8583     }
8584
8585     // If we can determine a pointer alignment that is bigger than currently
8586     // set, update the alignment.
8587     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8588       if (Instruction *I = SimplifyMemTransfer(MI))
8589         return I;
8590     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8591       if (Instruction *I = SimplifyMemSet(MSI))
8592         return I;
8593     }
8594           
8595     if (Changed) return II;
8596   }
8597   
8598   switch (II->getIntrinsicID()) {
8599   default: break;
8600   case Intrinsic::bswap:
8601     // bswap(bswap(x)) -> x
8602     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8603       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8604         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8605     break;
8606   case Intrinsic::ppc_altivec_lvx:
8607   case Intrinsic::ppc_altivec_lvxl:
8608   case Intrinsic::x86_sse_loadu_ps:
8609   case Intrinsic::x86_sse2_loadu_pd:
8610   case Intrinsic::x86_sse2_loadu_dq:
8611     // Turn PPC lvx     -> load if the pointer is known aligned.
8612     // Turn X86 loadups -> load if the pointer is known aligned.
8613     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8614       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8615                                        PointerType::getUnqual(II->getType()),
8616                                        CI);
8617       return new LoadInst(Ptr);
8618     }
8619     break;
8620   case Intrinsic::ppc_altivec_stvx:
8621   case Intrinsic::ppc_altivec_stvxl:
8622     // Turn stvx -> store if the pointer is known aligned.
8623     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8624       const Type *OpPtrTy = 
8625         PointerType::getUnqual(II->getOperand(1)->getType());
8626       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8627       return new StoreInst(II->getOperand(1), Ptr);
8628     }
8629     break;
8630   case Intrinsic::x86_sse_storeu_ps:
8631   case Intrinsic::x86_sse2_storeu_pd:
8632   case Intrinsic::x86_sse2_storeu_dq:
8633   case Intrinsic::x86_sse2_storel_dq:
8634     // Turn X86 storeu -> store if the pointer is known aligned.
8635     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8636       const Type *OpPtrTy = 
8637         PointerType::getUnqual(II->getOperand(2)->getType());
8638       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8639       return new StoreInst(II->getOperand(2), Ptr);
8640     }
8641     break;
8642     
8643   case Intrinsic::x86_sse_cvttss2si: {
8644     // These intrinsics only demands the 0th element of its input vector.  If
8645     // we can simplify the input based on that, do so now.
8646     uint64_t UndefElts;
8647     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8648                                               UndefElts)) {
8649       II->setOperand(1, V);
8650       return II;
8651     }
8652     break;
8653   }
8654     
8655   case Intrinsic::ppc_altivec_vperm:
8656     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8657     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8658       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8659       
8660       // Check that all of the elements are integer constants or undefs.
8661       bool AllEltsOk = true;
8662       for (unsigned i = 0; i != 16; ++i) {
8663         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8664             !isa<UndefValue>(Mask->getOperand(i))) {
8665           AllEltsOk = false;
8666           break;
8667         }
8668       }
8669       
8670       if (AllEltsOk) {
8671         // Cast the input vectors to byte vectors.
8672         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8673         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8674         Value *Result = UndefValue::get(Op0->getType());
8675         
8676         // Only extract each element once.
8677         Value *ExtractedElts[32];
8678         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8679         
8680         for (unsigned i = 0; i != 16; ++i) {
8681           if (isa<UndefValue>(Mask->getOperand(i)))
8682             continue;
8683           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8684           Idx &= 31;  // Match the hardware behavior.
8685           
8686           if (ExtractedElts[Idx] == 0) {
8687             Instruction *Elt = 
8688               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8689             InsertNewInstBefore(Elt, CI);
8690             ExtractedElts[Idx] = Elt;
8691           }
8692         
8693           // Insert this value into the result vector.
8694           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8695                                              i, "tmp");
8696           InsertNewInstBefore(cast<Instruction>(Result), CI);
8697         }
8698         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8699       }
8700     }
8701     break;
8702
8703   case Intrinsic::stackrestore: {
8704     // If the save is right next to the restore, remove the restore.  This can
8705     // happen when variable allocas are DCE'd.
8706     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8707       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8708         BasicBlock::iterator BI = SS;
8709         if (&*++BI == II)
8710           return EraseInstFromFunction(CI);
8711       }
8712     }
8713     
8714     // Scan down this block to see if there is another stack restore in the
8715     // same block without an intervening call/alloca.
8716     BasicBlock::iterator BI = II;
8717     TerminatorInst *TI = II->getParent()->getTerminator();
8718     bool CannotRemove = false;
8719     for (++BI; &*BI != TI; ++BI) {
8720       if (isa<AllocaInst>(BI)) {
8721         CannotRemove = true;
8722         break;
8723       }
8724       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8725         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8726           // If there is a stackrestore below this one, remove this one.
8727           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8728             return EraseInstFromFunction(CI);
8729           // Otherwise, ignore the intrinsic.
8730         } else {
8731           // If we found a non-intrinsic call, we can't remove the stack
8732           // restore.
8733           CannotRemove = true;
8734           break;
8735         }
8736       }
8737     }
8738     
8739     // If the stack restore is in a return/unwind block and if there are no
8740     // allocas or calls between the restore and the return, nuke the restore.
8741     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8742       return EraseInstFromFunction(CI);
8743     break;
8744   }
8745   }
8746
8747   return visitCallSite(II);
8748 }
8749
8750 // InvokeInst simplification
8751 //
8752 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8753   return visitCallSite(&II);
8754 }
8755
8756 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8757 /// passed through the varargs area, we can eliminate the use of the cast.
8758 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8759                                          const CastInst * const CI,
8760                                          const TargetData * const TD,
8761                                          const int ix) {
8762   if (!CI->isLosslessCast())
8763     return false;
8764
8765   // The size of ByVal arguments is derived from the type, so we
8766   // can't change to a type with a different size.  If the size were
8767   // passed explicitly we could avoid this check.
8768   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8769     return true;
8770
8771   const Type* SrcTy = 
8772             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8773   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8774   if (!SrcTy->isSized() || !DstTy->isSized())
8775     return false;
8776   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8777     return false;
8778   return true;
8779 }
8780
8781 // visitCallSite - Improvements for call and invoke instructions.
8782 //
8783 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8784   bool Changed = false;
8785
8786   // If the callee is a constexpr cast of a function, attempt to move the cast
8787   // to the arguments of the call/invoke.
8788   if (transformConstExprCastCall(CS)) return 0;
8789
8790   Value *Callee = CS.getCalledValue();
8791
8792   if (Function *CalleeF = dyn_cast<Function>(Callee))
8793     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8794       Instruction *OldCall = CS.getInstruction();
8795       // If the call and callee calling conventions don't match, this call must
8796       // be unreachable, as the call is undefined.
8797       new StoreInst(ConstantInt::getTrue(),
8798                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8799                                     OldCall);
8800       if (!OldCall->use_empty())
8801         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8802       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8803         return EraseInstFromFunction(*OldCall);
8804       return 0;
8805     }
8806
8807   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8808     // This instruction is not reachable, just remove it.  We insert a store to
8809     // undef so that we know that this code is not reachable, despite the fact
8810     // that we can't modify the CFG here.
8811     new StoreInst(ConstantInt::getTrue(),
8812                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8813                   CS.getInstruction());
8814
8815     if (!CS.getInstruction()->use_empty())
8816       CS.getInstruction()->
8817         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8818
8819     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8820       // Don't break the CFG, insert a dummy cond branch.
8821       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8822                          ConstantInt::getTrue(), II);
8823     }
8824     return EraseInstFromFunction(*CS.getInstruction());
8825   }
8826
8827   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8828     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8829       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8830         return transformCallThroughTrampoline(CS);
8831
8832   const PointerType *PTy = cast<PointerType>(Callee->getType());
8833   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8834   if (FTy->isVarArg()) {
8835     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8836     // See if we can optimize any arguments passed through the varargs area of
8837     // the call.
8838     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8839            E = CS.arg_end(); I != E; ++I, ++ix) {
8840       CastInst *CI = dyn_cast<CastInst>(*I);
8841       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8842         *I = CI->getOperand(0);
8843         Changed = true;
8844       }
8845     }
8846   }
8847
8848   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8849     // Inline asm calls cannot throw - mark them 'nounwind'.
8850     CS.setDoesNotThrow();
8851     Changed = true;
8852   }
8853
8854   return Changed ? CS.getInstruction() : 0;
8855 }
8856
8857 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8858 // attempt to move the cast to the arguments of the call/invoke.
8859 //
8860 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8861   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8862   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8863   if (CE->getOpcode() != Instruction::BitCast || 
8864       !isa<Function>(CE->getOperand(0)))
8865     return false;
8866   Function *Callee = cast<Function>(CE->getOperand(0));
8867   Instruction *Caller = CS.getInstruction();
8868   const PAListPtr &CallerPAL = CS.getParamAttrs();
8869
8870   // Okay, this is a cast from a function to a different type.  Unless doing so
8871   // would cause a type conversion of one of our arguments, change this call to
8872   // be a direct call with arguments casted to the appropriate types.
8873   //
8874   const FunctionType *FT = Callee->getFunctionType();
8875   const Type *OldRetTy = Caller->getType();
8876   const Type *NewRetTy = FT->getReturnType();
8877
8878   if (isa<StructType>(NewRetTy))
8879     return false; // TODO: Handle multiple return values.
8880
8881   // Check to see if we are changing the return type...
8882   if (OldRetTy != NewRetTy) {
8883     if (Callee->isDeclaration() &&
8884         // Conversion is ok if changing from one pointer type to another or from
8885         // a pointer to an integer of the same size.
8886         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8887           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8888       return false;   // Cannot transform this return value.
8889
8890     if (!Caller->use_empty() &&
8891         // void -> non-void is handled specially
8892         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8893       return false;   // Cannot transform this return value.
8894
8895     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8896       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8897       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8898         return false;   // Attribute not compatible with transformed value.
8899     }
8900
8901     // If the callsite is an invoke instruction, and the return value is used by
8902     // a PHI node in a successor, we cannot change the return type of the call
8903     // because there is no place to put the cast instruction (without breaking
8904     // the critical edge).  Bail out in this case.
8905     if (!Caller->use_empty())
8906       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8907         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8908              UI != E; ++UI)
8909           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8910             if (PN->getParent() == II->getNormalDest() ||
8911                 PN->getParent() == II->getUnwindDest())
8912               return false;
8913   }
8914
8915   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8916   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8917
8918   CallSite::arg_iterator AI = CS.arg_begin();
8919   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8920     const Type *ParamTy = FT->getParamType(i);
8921     const Type *ActTy = (*AI)->getType();
8922
8923     if (!CastInst::isCastable(ActTy, ParamTy))
8924       return false;   // Cannot transform this parameter value.
8925
8926     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8927       return false;   // Attribute not compatible with transformed value.
8928
8929     // Converting from one pointer type to another or between a pointer and an
8930     // integer of the same size is safe even if we do not have a body.
8931     bool isConvertible = ActTy == ParamTy ||
8932       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8933        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8934     if (Callee->isDeclaration() && !isConvertible) return false;
8935   }
8936
8937   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8938       Callee->isDeclaration())
8939     return false;   // Do not delete arguments unless we have a function body.
8940
8941   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8942       !CallerPAL.isEmpty())
8943     // In this case we have more arguments than the new function type, but we
8944     // won't be dropping them.  Check that these extra arguments have attributes
8945     // that are compatible with being a vararg call argument.
8946     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8947       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8948         break;
8949       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8950       if (PAttrs & ParamAttr::VarArgsIncompatible)
8951         return false;
8952     }
8953
8954   // Okay, we decided that this is a safe thing to do: go ahead and start
8955   // inserting cast instructions as necessary...
8956   std::vector<Value*> Args;
8957   Args.reserve(NumActualArgs);
8958   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8959   attrVec.reserve(NumCommonArgs);
8960
8961   // Get any return attributes.
8962   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8963
8964   // If the return value is not being used, the type may not be compatible
8965   // with the existing attributes.  Wipe out any problematic attributes.
8966   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8967
8968   // Add the new return attributes.
8969   if (RAttrs)
8970     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8971
8972   AI = CS.arg_begin();
8973   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8974     const Type *ParamTy = FT->getParamType(i);
8975     if ((*AI)->getType() == ParamTy) {
8976       Args.push_back(*AI);
8977     } else {
8978       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8979           false, ParamTy, false);
8980       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8981       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8982     }
8983
8984     // Add any parameter attributes.
8985     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8986       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8987   }
8988
8989   // If the function takes more arguments than the call was taking, add them
8990   // now...
8991   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8992     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8993
8994   // If we are removing arguments to the function, emit an obnoxious warning...
8995   if (FT->getNumParams() < NumActualArgs) {
8996     if (!FT->isVarArg()) {
8997       cerr << "WARNING: While resolving call to function '"
8998            << Callee->getName() << "' arguments were dropped!\n";
8999     } else {
9000       // Add all of the arguments in their promoted form to the arg list...
9001       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9002         const Type *PTy = getPromotedType((*AI)->getType());
9003         if (PTy != (*AI)->getType()) {
9004           // Must promote to pass through va_arg area!
9005           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9006                                                                 PTy, false);
9007           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9008           InsertNewInstBefore(Cast, *Caller);
9009           Args.push_back(Cast);
9010         } else {
9011           Args.push_back(*AI);
9012         }
9013
9014         // Add any parameter attributes.
9015         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9016           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9017       }
9018     }
9019   }
9020
9021   if (NewRetTy == Type::VoidTy)
9022     Caller->setName("");   // Void type should not have a name.
9023
9024   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9025
9026   Instruction *NC;
9027   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9028     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9029                             Args.begin(), Args.end(),
9030                             Caller->getName(), Caller);
9031     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9032     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9033   } else {
9034     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9035                           Caller->getName(), Caller);
9036     CallInst *CI = cast<CallInst>(Caller);
9037     if (CI->isTailCall())
9038       cast<CallInst>(NC)->setTailCall();
9039     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9040     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9041   }
9042
9043   // Insert a cast of the return type as necessary.
9044   Value *NV = NC;
9045   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9046     if (NV->getType() != Type::VoidTy) {
9047       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9048                                                             OldRetTy, false);
9049       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9050
9051       // If this is an invoke instruction, we should insert it after the first
9052       // non-phi, instruction in the normal successor block.
9053       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9054         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9055         InsertNewInstBefore(NC, *I);
9056       } else {
9057         // Otherwise, it's a call, just insert cast right after the call instr
9058         InsertNewInstBefore(NC, *Caller);
9059       }
9060       AddUsersToWorkList(*Caller);
9061     } else {
9062       NV = UndefValue::get(Caller->getType());
9063     }
9064   }
9065
9066   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9067     Caller->replaceAllUsesWith(NV);
9068   Caller->eraseFromParent();
9069   RemoveFromWorkList(Caller);
9070   return true;
9071 }
9072
9073 // transformCallThroughTrampoline - Turn a call to a function created by the
9074 // init_trampoline intrinsic into a direct call to the underlying function.
9075 //
9076 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9077   Value *Callee = CS.getCalledValue();
9078   const PointerType *PTy = cast<PointerType>(Callee->getType());
9079   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9080   const PAListPtr &Attrs = CS.getParamAttrs();
9081
9082   // If the call already has the 'nest' attribute somewhere then give up -
9083   // otherwise 'nest' would occur twice after splicing in the chain.
9084   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9085     return 0;
9086
9087   IntrinsicInst *Tramp =
9088     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9089
9090   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9091   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9092   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9093
9094   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9095   if (!NestAttrs.isEmpty()) {
9096     unsigned NestIdx = 1;
9097     const Type *NestTy = 0;
9098     ParameterAttributes NestAttr = ParamAttr::None;
9099
9100     // Look for a parameter marked with the 'nest' attribute.
9101     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9102          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9103       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9104         // Record the parameter type and any other attributes.
9105         NestTy = *I;
9106         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9107         break;
9108       }
9109
9110     if (NestTy) {
9111       Instruction *Caller = CS.getInstruction();
9112       std::vector<Value*> NewArgs;
9113       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9114
9115       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9116       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9117
9118       // Insert the nest argument into the call argument list, which may
9119       // mean appending it.  Likewise for attributes.
9120
9121       // Add any function result attributes.
9122       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9123         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9124
9125       {
9126         unsigned Idx = 1;
9127         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9128         do {
9129           if (Idx == NestIdx) {
9130             // Add the chain argument and attributes.
9131             Value *NestVal = Tramp->getOperand(3);
9132             if (NestVal->getType() != NestTy)
9133               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9134             NewArgs.push_back(NestVal);
9135             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9136           }
9137
9138           if (I == E)
9139             break;
9140
9141           // Add the original argument and attributes.
9142           NewArgs.push_back(*I);
9143           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9144             NewAttrs.push_back
9145               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9146
9147           ++Idx, ++I;
9148         } while (1);
9149       }
9150
9151       // The trampoline may have been bitcast to a bogus type (FTy).
9152       // Handle this by synthesizing a new function type, equal to FTy
9153       // with the chain parameter inserted.
9154
9155       std::vector<const Type*> NewTypes;
9156       NewTypes.reserve(FTy->getNumParams()+1);
9157
9158       // Insert the chain's type into the list of parameter types, which may
9159       // mean appending it.
9160       {
9161         unsigned Idx = 1;
9162         FunctionType::param_iterator I = FTy->param_begin(),
9163           E = FTy->param_end();
9164
9165         do {
9166           if (Idx == NestIdx)
9167             // Add the chain's type.
9168             NewTypes.push_back(NestTy);
9169
9170           if (I == E)
9171             break;
9172
9173           // Add the original type.
9174           NewTypes.push_back(*I);
9175
9176           ++Idx, ++I;
9177         } while (1);
9178       }
9179
9180       // Replace the trampoline call with a direct call.  Let the generic
9181       // code sort out any function type mismatches.
9182       FunctionType *NewFTy =
9183         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9184       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9185         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9186       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9187
9188       Instruction *NewCaller;
9189       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9190         NewCaller = InvokeInst::Create(NewCallee,
9191                                        II->getNormalDest(), II->getUnwindDest(),
9192                                        NewArgs.begin(), NewArgs.end(),
9193                                        Caller->getName(), Caller);
9194         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9195         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9196       } else {
9197         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9198                                      Caller->getName(), Caller);
9199         if (cast<CallInst>(Caller)->isTailCall())
9200           cast<CallInst>(NewCaller)->setTailCall();
9201         cast<CallInst>(NewCaller)->
9202           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9203         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9204       }
9205       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9206         Caller->replaceAllUsesWith(NewCaller);
9207       Caller->eraseFromParent();
9208       RemoveFromWorkList(Caller);
9209       return 0;
9210     }
9211   }
9212
9213   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9214   // parameter, there is no need to adjust the argument list.  Let the generic
9215   // code sort out any function type mismatches.
9216   Constant *NewCallee =
9217     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9218   CS.setCalledFunction(NewCallee);
9219   return CS.getInstruction();
9220 }
9221
9222 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9223 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9224 /// and a single binop.
9225 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9226   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9227   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9228          isa<CmpInst>(FirstInst));
9229   unsigned Opc = FirstInst->getOpcode();
9230   Value *LHSVal = FirstInst->getOperand(0);
9231   Value *RHSVal = FirstInst->getOperand(1);
9232     
9233   const Type *LHSType = LHSVal->getType();
9234   const Type *RHSType = RHSVal->getType();
9235   
9236   // Scan to see if all operands are the same opcode, all have one use, and all
9237   // kill their operands (i.e. the operands have one use).
9238   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9239     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9240     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9241         // Verify type of the LHS matches so we don't fold cmp's of different
9242         // types or GEP's with different index types.
9243         I->getOperand(0)->getType() != LHSType ||
9244         I->getOperand(1)->getType() != RHSType)
9245       return 0;
9246
9247     // If they are CmpInst instructions, check their predicates
9248     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9249       if (cast<CmpInst>(I)->getPredicate() !=
9250           cast<CmpInst>(FirstInst)->getPredicate())
9251         return 0;
9252     
9253     // Keep track of which operand needs a phi node.
9254     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9255     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9256   }
9257   
9258   // Otherwise, this is safe to transform, determine if it is profitable.
9259
9260   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9261   // Indexes are often folded into load/store instructions, so we don't want to
9262   // hide them behind a phi.
9263   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9264     return 0;
9265   
9266   Value *InLHS = FirstInst->getOperand(0);
9267   Value *InRHS = FirstInst->getOperand(1);
9268   PHINode *NewLHS = 0, *NewRHS = 0;
9269   if (LHSVal == 0) {
9270     NewLHS = PHINode::Create(LHSType,
9271                              FirstInst->getOperand(0)->getName() + ".pn");
9272     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9273     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9274     InsertNewInstBefore(NewLHS, PN);
9275     LHSVal = NewLHS;
9276   }
9277   
9278   if (RHSVal == 0) {
9279     NewRHS = PHINode::Create(RHSType,
9280                              FirstInst->getOperand(1)->getName() + ".pn");
9281     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9282     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9283     InsertNewInstBefore(NewRHS, PN);
9284     RHSVal = NewRHS;
9285   }
9286   
9287   // Add all operands to the new PHIs.
9288   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9289     if (NewLHS) {
9290       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9291       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9292     }
9293     if (NewRHS) {
9294       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9295       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9296     }
9297   }
9298     
9299   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9300     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9301   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9302     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9303                            RHSVal);
9304   else {
9305     assert(isa<GetElementPtrInst>(FirstInst));
9306     return GetElementPtrInst::Create(LHSVal, RHSVal);
9307   }
9308 }
9309
9310 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9311 /// of the block that defines it.  This means that it must be obvious the value
9312 /// of the load is not changed from the point of the load to the end of the
9313 /// block it is in.
9314 ///
9315 /// Finally, it is safe, but not profitable, to sink a load targetting a
9316 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9317 /// to a register.
9318 static bool isSafeToSinkLoad(LoadInst *L) {
9319   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9320   
9321   for (++BBI; BBI != E; ++BBI)
9322     if (BBI->mayWriteToMemory())
9323       return false;
9324   
9325   // Check for non-address taken alloca.  If not address-taken already, it isn't
9326   // profitable to do this xform.
9327   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9328     bool isAddressTaken = false;
9329     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9330          UI != E; ++UI) {
9331       if (isa<LoadInst>(UI)) continue;
9332       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9333         // If storing TO the alloca, then the address isn't taken.
9334         if (SI->getOperand(1) == AI) continue;
9335       }
9336       isAddressTaken = true;
9337       break;
9338     }
9339     
9340     if (!isAddressTaken)
9341       return false;
9342   }
9343   
9344   return true;
9345 }
9346
9347
9348 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9349 // operator and they all are only used by the PHI, PHI together their
9350 // inputs, and do the operation once, to the result of the PHI.
9351 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9352   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9353
9354   // Scan the instruction, looking for input operations that can be folded away.
9355   // If all input operands to the phi are the same instruction (e.g. a cast from
9356   // the same type or "+42") we can pull the operation through the PHI, reducing
9357   // code size and simplifying code.
9358   Constant *ConstantOp = 0;
9359   const Type *CastSrcTy = 0;
9360   bool isVolatile = false;
9361   if (isa<CastInst>(FirstInst)) {
9362     CastSrcTy = FirstInst->getOperand(0)->getType();
9363   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9364     // Can fold binop, compare or shift here if the RHS is a constant, 
9365     // otherwise call FoldPHIArgBinOpIntoPHI.
9366     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9367     if (ConstantOp == 0)
9368       return FoldPHIArgBinOpIntoPHI(PN);
9369   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9370     isVolatile = LI->isVolatile();
9371     // We can't sink the load if the loaded value could be modified between the
9372     // load and the PHI.
9373     if (LI->getParent() != PN.getIncomingBlock(0) ||
9374         !isSafeToSinkLoad(LI))
9375       return 0;
9376     
9377     // If the PHI is of volatile loads and the load block has multiple
9378     // successors, sinking it would remove a load of the volatile value from
9379     // the path through the other successor.
9380     if (isVolatile &&
9381         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9382       return 0;
9383     
9384   } else if (isa<GetElementPtrInst>(FirstInst)) {
9385     if (FirstInst->getNumOperands() == 2)
9386       return FoldPHIArgBinOpIntoPHI(PN);
9387     // Can't handle general GEPs yet.
9388     return 0;
9389   } else {
9390     return 0;  // Cannot fold this operation.
9391   }
9392
9393   // Check to see if all arguments are the same operation.
9394   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9395     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9396     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9397     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9398       return 0;
9399     if (CastSrcTy) {
9400       if (I->getOperand(0)->getType() != CastSrcTy)
9401         return 0;  // Cast operation must match.
9402     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9403       // We can't sink the load if the loaded value could be modified between 
9404       // the load and the PHI.
9405       if (LI->isVolatile() != isVolatile ||
9406           LI->getParent() != PN.getIncomingBlock(i) ||
9407           !isSafeToSinkLoad(LI))
9408         return 0;
9409       
9410       // If the PHI is of volatile loads and the load block has multiple
9411       // successors, sinking it would remove a load of the volatile value from
9412       // the path through the other successor.
9413       if (isVolatile &&
9414           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9415         return 0;
9416
9417       
9418     } else if (I->getOperand(1) != ConstantOp) {
9419       return 0;
9420     }
9421   }
9422
9423   // Okay, they are all the same operation.  Create a new PHI node of the
9424   // correct type, and PHI together all of the LHS's of the instructions.
9425   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9426                                    PN.getName()+".in");
9427   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9428
9429   Value *InVal = FirstInst->getOperand(0);
9430   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9431
9432   // Add all operands to the new PHI.
9433   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9434     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9435     if (NewInVal != InVal)
9436       InVal = 0;
9437     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9438   }
9439
9440   Value *PhiVal;
9441   if (InVal) {
9442     // The new PHI unions all of the same values together.  This is really
9443     // common, so we handle it intelligently here for compile-time speed.
9444     PhiVal = InVal;
9445     delete NewPN;
9446   } else {
9447     InsertNewInstBefore(NewPN, PN);
9448     PhiVal = NewPN;
9449   }
9450
9451   // Insert and return the new operation.
9452   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9453     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9454   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9455     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9456   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9457     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9458                            PhiVal, ConstantOp);
9459   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9460   
9461   // If this was a volatile load that we are merging, make sure to loop through
9462   // and mark all the input loads as non-volatile.  If we don't do this, we will
9463   // insert a new volatile load and the old ones will not be deletable.
9464   if (isVolatile)
9465     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9466       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9467   
9468   return new LoadInst(PhiVal, "", isVolatile);
9469 }
9470
9471 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9472 /// that is dead.
9473 static bool DeadPHICycle(PHINode *PN,
9474                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9475   if (PN->use_empty()) return true;
9476   if (!PN->hasOneUse()) return false;
9477
9478   // Remember this node, and if we find the cycle, return.
9479   if (!PotentiallyDeadPHIs.insert(PN))
9480     return true;
9481   
9482   // Don't scan crazily complex things.
9483   if (PotentiallyDeadPHIs.size() == 16)
9484     return false;
9485
9486   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9487     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9488
9489   return false;
9490 }
9491
9492 /// PHIsEqualValue - Return true if this phi node is always equal to
9493 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9494 ///   z = some value; x = phi (y, z); y = phi (x, z)
9495 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9496                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9497   // See if we already saw this PHI node.
9498   if (!ValueEqualPHIs.insert(PN))
9499     return true;
9500   
9501   // Don't scan crazily complex things.
9502   if (ValueEqualPHIs.size() == 16)
9503     return false;
9504  
9505   // Scan the operands to see if they are either phi nodes or are equal to
9506   // the value.
9507   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9508     Value *Op = PN->getIncomingValue(i);
9509     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9510       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9511         return false;
9512     } else if (Op != NonPhiInVal)
9513       return false;
9514   }
9515   
9516   return true;
9517 }
9518
9519
9520 // PHINode simplification
9521 //
9522 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9523   // If LCSSA is around, don't mess with Phi nodes
9524   if (MustPreserveLCSSA) return 0;
9525   
9526   if (Value *V = PN.hasConstantValue())
9527     return ReplaceInstUsesWith(PN, V);
9528
9529   // If all PHI operands are the same operation, pull them through the PHI,
9530   // reducing code size.
9531   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9532       PN.getIncomingValue(0)->hasOneUse())
9533     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9534       return Result;
9535
9536   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9537   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9538   // PHI)... break the cycle.
9539   if (PN.hasOneUse()) {
9540     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9541     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9542       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9543       PotentiallyDeadPHIs.insert(&PN);
9544       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9545         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9546     }
9547    
9548     // If this phi has a single use, and if that use just computes a value for
9549     // the next iteration of a loop, delete the phi.  This occurs with unused
9550     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9551     // common case here is good because the only other things that catch this
9552     // are induction variable analysis (sometimes) and ADCE, which is only run
9553     // late.
9554     if (PHIUser->hasOneUse() &&
9555         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9556         PHIUser->use_back() == &PN) {
9557       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9558     }
9559   }
9560
9561   // We sometimes end up with phi cycles that non-obviously end up being the
9562   // same value, for example:
9563   //   z = some value; x = phi (y, z); y = phi (x, z)
9564   // where the phi nodes don't necessarily need to be in the same block.  Do a
9565   // quick check to see if the PHI node only contains a single non-phi value, if
9566   // so, scan to see if the phi cycle is actually equal to that value.
9567   {
9568     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9569     // Scan for the first non-phi operand.
9570     while (InValNo != NumOperandVals && 
9571            isa<PHINode>(PN.getIncomingValue(InValNo)))
9572       ++InValNo;
9573
9574     if (InValNo != NumOperandVals) {
9575       Value *NonPhiInVal = PN.getOperand(InValNo);
9576       
9577       // Scan the rest of the operands to see if there are any conflicts, if so
9578       // there is no need to recursively scan other phis.
9579       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9580         Value *OpVal = PN.getIncomingValue(InValNo);
9581         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9582           break;
9583       }
9584       
9585       // If we scanned over all operands, then we have one unique value plus
9586       // phi values.  Scan PHI nodes to see if they all merge in each other or
9587       // the value.
9588       if (InValNo == NumOperandVals) {
9589         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9590         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9591           return ReplaceInstUsesWith(PN, NonPhiInVal);
9592       }
9593     }
9594   }
9595   return 0;
9596 }
9597
9598 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9599                                    Instruction *InsertPoint,
9600                                    InstCombiner *IC) {
9601   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9602   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9603   // We must cast correctly to the pointer type. Ensure that we
9604   // sign extend the integer value if it is smaller as this is
9605   // used for address computation.
9606   Instruction::CastOps opcode = 
9607      (VTySize < PtrSize ? Instruction::SExt :
9608       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9609   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9610 }
9611
9612
9613 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9614   Value *PtrOp = GEP.getOperand(0);
9615   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9616   // If so, eliminate the noop.
9617   if (GEP.getNumOperands() == 1)
9618     return ReplaceInstUsesWith(GEP, PtrOp);
9619
9620   if (isa<UndefValue>(GEP.getOperand(0)))
9621     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9622
9623   bool HasZeroPointerIndex = false;
9624   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9625     HasZeroPointerIndex = C->isNullValue();
9626
9627   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9628     return ReplaceInstUsesWith(GEP, PtrOp);
9629
9630   // Eliminate unneeded casts for indices.
9631   bool MadeChange = false;
9632   
9633   gep_type_iterator GTI = gep_type_begin(GEP);
9634   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9635        i != e; ++i, ++GTI) {
9636     if (isa<SequentialType>(*GTI)) {
9637       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9638         if (CI->getOpcode() == Instruction::ZExt ||
9639             CI->getOpcode() == Instruction::SExt) {
9640           const Type *SrcTy = CI->getOperand(0)->getType();
9641           // We can eliminate a cast from i32 to i64 iff the target 
9642           // is a 32-bit pointer target.
9643           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9644             MadeChange = true;
9645             *i = CI->getOperand(0);
9646           }
9647         }
9648       }
9649       // If we are using a wider index than needed for this platform, shrink it
9650       // to what we need.  If the incoming value needs a cast instruction,
9651       // insert it.  This explicit cast can make subsequent optimizations more
9652       // obvious.
9653       Value *Op = *i;
9654       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9655         if (Constant *C = dyn_cast<Constant>(Op)) {
9656           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9657           MadeChange = true;
9658         } else {
9659           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9660                                 GEP);
9661           *i = Op;
9662           MadeChange = true;
9663         }
9664       }
9665     }
9666   }
9667   if (MadeChange) return &GEP;
9668
9669   // If this GEP instruction doesn't move the pointer, and if the input operand
9670   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9671   // real input to the dest type.
9672   if (GEP.hasAllZeroIndices()) {
9673     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9674       // If the bitcast is of an allocation, and the allocation will be
9675       // converted to match the type of the cast, don't touch this.
9676       if (isa<AllocationInst>(BCI->getOperand(0))) {
9677         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9678         if (Instruction *I = visitBitCast(*BCI)) {
9679           if (I != BCI) {
9680             I->takeName(BCI);
9681             BCI->getParent()->getInstList().insert(BCI, I);
9682             ReplaceInstUsesWith(*BCI, I);
9683           }
9684           return &GEP;
9685         }
9686       }
9687       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9688     }
9689   }
9690   
9691   // Combine Indices - If the source pointer to this getelementptr instruction
9692   // is a getelementptr instruction, combine the indices of the two
9693   // getelementptr instructions into a single instruction.
9694   //
9695   SmallVector<Value*, 8> SrcGEPOperands;
9696   if (User *Src = dyn_castGetElementPtr(PtrOp))
9697     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9698
9699   if (!SrcGEPOperands.empty()) {
9700     // Note that if our source is a gep chain itself that we wait for that
9701     // chain to be resolved before we perform this transformation.  This
9702     // avoids us creating a TON of code in some cases.
9703     //
9704     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9705         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9706       return 0;   // Wait until our source is folded to completion.
9707
9708     SmallVector<Value*, 8> Indices;
9709
9710     // Find out whether the last index in the source GEP is a sequential idx.
9711     bool EndsWithSequential = false;
9712     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9713            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9714       EndsWithSequential = !isa<StructType>(*I);
9715
9716     // Can we combine the two pointer arithmetics offsets?
9717     if (EndsWithSequential) {
9718       // Replace: gep (gep %P, long B), long A, ...
9719       // With:    T = long A+B; gep %P, T, ...
9720       //
9721       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9722       if (SO1 == Constant::getNullValue(SO1->getType())) {
9723         Sum = GO1;
9724       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9725         Sum = SO1;
9726       } else {
9727         // If they aren't the same type, convert both to an integer of the
9728         // target's pointer size.
9729         if (SO1->getType() != GO1->getType()) {
9730           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9731             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9732           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9733             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9734           } else {
9735             unsigned PS = TD->getPointerSizeInBits();
9736             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9737               // Convert GO1 to SO1's type.
9738               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9739
9740             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9741               // Convert SO1 to GO1's type.
9742               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9743             } else {
9744               const Type *PT = TD->getIntPtrType();
9745               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9746               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9747             }
9748           }
9749         }
9750         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9751           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9752         else {
9753           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9754           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9755         }
9756       }
9757
9758       // Recycle the GEP we already have if possible.
9759       if (SrcGEPOperands.size() == 2) {
9760         GEP.setOperand(0, SrcGEPOperands[0]);
9761         GEP.setOperand(1, Sum);
9762         return &GEP;
9763       } else {
9764         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9765                        SrcGEPOperands.end()-1);
9766         Indices.push_back(Sum);
9767         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9768       }
9769     } else if (isa<Constant>(*GEP.idx_begin()) &&
9770                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9771                SrcGEPOperands.size() != 1) {
9772       // Otherwise we can do the fold if the first index of the GEP is a zero
9773       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9774                      SrcGEPOperands.end());
9775       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9776     }
9777
9778     if (!Indices.empty())
9779       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9780                                        Indices.end(), GEP.getName());
9781
9782   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9783     // GEP of global variable.  If all of the indices for this GEP are
9784     // constants, we can promote this to a constexpr instead of an instruction.
9785
9786     // Scan for nonconstants...
9787     SmallVector<Constant*, 8> Indices;
9788     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9789     for (; I != E && isa<Constant>(*I); ++I)
9790       Indices.push_back(cast<Constant>(*I));
9791
9792     if (I == E) {  // If they are all constants...
9793       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9794                                                     &Indices[0],Indices.size());
9795
9796       // Replace all uses of the GEP with the new constexpr...
9797       return ReplaceInstUsesWith(GEP, CE);
9798     }
9799   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9800     if (!isa<PointerType>(X->getType())) {
9801       // Not interesting.  Source pointer must be a cast from pointer.
9802     } else if (HasZeroPointerIndex) {
9803       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9804       // into     : GEP [10 x i8]* X, i32 0, ...
9805       //
9806       // This occurs when the program declares an array extern like "int X[];"
9807       //
9808       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9809       const PointerType *XTy = cast<PointerType>(X->getType());
9810       if (const ArrayType *XATy =
9811           dyn_cast<ArrayType>(XTy->getElementType()))
9812         if (const ArrayType *CATy =
9813             dyn_cast<ArrayType>(CPTy->getElementType()))
9814           if (CATy->getElementType() == XATy->getElementType()) {
9815             // At this point, we know that the cast source type is a pointer
9816             // to an array of the same type as the destination pointer
9817             // array.  Because the array type is never stepped over (there
9818             // is a leading zero) we can fold the cast into this GEP.
9819             GEP.setOperand(0, X);
9820             return &GEP;
9821           }
9822     } else if (GEP.getNumOperands() == 2) {
9823       // Transform things like:
9824       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9825       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9826       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9827       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9828       if (isa<ArrayType>(SrcElTy) &&
9829           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9830           TD->getABITypeSize(ResElTy)) {
9831         Value *Idx[2];
9832         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9833         Idx[1] = GEP.getOperand(1);
9834         Value *V = InsertNewInstBefore(
9835                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9836         // V and GEP are both pointer types --> BitCast
9837         return new BitCastInst(V, GEP.getType());
9838       }
9839       
9840       // Transform things like:
9841       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9842       //   (where tmp = 8*tmp2) into:
9843       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9844       
9845       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9846         uint64_t ArrayEltSize =
9847             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9848         
9849         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9850         // allow either a mul, shift, or constant here.
9851         Value *NewIdx = 0;
9852         ConstantInt *Scale = 0;
9853         if (ArrayEltSize == 1) {
9854           NewIdx = GEP.getOperand(1);
9855           Scale = ConstantInt::get(NewIdx->getType(), 1);
9856         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9857           NewIdx = ConstantInt::get(CI->getType(), 1);
9858           Scale = CI;
9859         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9860           if (Inst->getOpcode() == Instruction::Shl &&
9861               isa<ConstantInt>(Inst->getOperand(1))) {
9862             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9863             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9864             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9865             NewIdx = Inst->getOperand(0);
9866           } else if (Inst->getOpcode() == Instruction::Mul &&
9867                      isa<ConstantInt>(Inst->getOperand(1))) {
9868             Scale = cast<ConstantInt>(Inst->getOperand(1));
9869             NewIdx = Inst->getOperand(0);
9870           }
9871         }
9872         
9873         // If the index will be to exactly the right offset with the scale taken
9874         // out, perform the transformation. Note, we don't know whether Scale is
9875         // signed or not. We'll use unsigned version of division/modulo
9876         // operation after making sure Scale doesn't have the sign bit set.
9877         if (Scale && Scale->getSExtValue() >= 0LL &&
9878             Scale->getZExtValue() % ArrayEltSize == 0) {
9879           Scale = ConstantInt::get(Scale->getType(),
9880                                    Scale->getZExtValue() / ArrayEltSize);
9881           if (Scale->getZExtValue() != 1) {
9882             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9883                                                        false /*ZExt*/);
9884             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9885             NewIdx = InsertNewInstBefore(Sc, GEP);
9886           }
9887
9888           // Insert the new GEP instruction.
9889           Value *Idx[2];
9890           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9891           Idx[1] = NewIdx;
9892           Instruction *NewGEP =
9893             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9894           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9895           // The NewGEP must be pointer typed, so must the old one -> BitCast
9896           return new BitCastInst(NewGEP, GEP.getType());
9897         }
9898       }
9899     }
9900   }
9901
9902   return 0;
9903 }
9904
9905 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9906   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9907   if (AI.isArrayAllocation()) {  // Check C != 1
9908     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9909       const Type *NewTy = 
9910         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9911       AllocationInst *New = 0;
9912
9913       // Create and insert the replacement instruction...
9914       if (isa<MallocInst>(AI))
9915         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9916       else {
9917         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9918         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9919       }
9920
9921       InsertNewInstBefore(New, AI);
9922
9923       // Scan to the end of the allocation instructions, to skip over a block of
9924       // allocas if possible...
9925       //
9926       BasicBlock::iterator It = New;
9927       while (isa<AllocationInst>(*It)) ++It;
9928
9929       // Now that I is pointing to the first non-allocation-inst in the block,
9930       // insert our getelementptr instruction...
9931       //
9932       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9933       Value *Idx[2];
9934       Idx[0] = NullIdx;
9935       Idx[1] = NullIdx;
9936       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9937                                            New->getName()+".sub", It);
9938
9939       // Now make everything use the getelementptr instead of the original
9940       // allocation.
9941       return ReplaceInstUsesWith(AI, V);
9942     } else if (isa<UndefValue>(AI.getArraySize())) {
9943       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9944     }
9945   }
9946
9947   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9948   // Note that we only do this for alloca's, because malloc should allocate and
9949   // return a unique pointer, even for a zero byte allocation.
9950   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9951       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9952     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9953
9954   return 0;
9955 }
9956
9957 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9958   Value *Op = FI.getOperand(0);
9959
9960   // free undef -> unreachable.
9961   if (isa<UndefValue>(Op)) {
9962     // Insert a new store to null because we cannot modify the CFG here.
9963     new StoreInst(ConstantInt::getTrue(),
9964                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9965     return EraseInstFromFunction(FI);
9966   }
9967   
9968   // If we have 'free null' delete the instruction.  This can happen in stl code
9969   // when lots of inlining happens.
9970   if (isa<ConstantPointerNull>(Op))
9971     return EraseInstFromFunction(FI);
9972   
9973   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9974   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9975     FI.setOperand(0, CI->getOperand(0));
9976     return &FI;
9977   }
9978   
9979   // Change free (gep X, 0,0,0,0) into free(X)
9980   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9981     if (GEPI->hasAllZeroIndices()) {
9982       AddToWorkList(GEPI);
9983       FI.setOperand(0, GEPI->getOperand(0));
9984       return &FI;
9985     }
9986   }
9987   
9988   // Change free(malloc) into nothing, if the malloc has a single use.
9989   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9990     if (MI->hasOneUse()) {
9991       EraseInstFromFunction(FI);
9992       return EraseInstFromFunction(*MI);
9993     }
9994
9995   return 0;
9996 }
9997
9998
9999 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10000 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10001                                         const TargetData *TD) {
10002   User *CI = cast<User>(LI.getOperand(0));
10003   Value *CastOp = CI->getOperand(0);
10004
10005   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10006     // Instead of loading constant c string, use corresponding integer value
10007     // directly if string length is small enough.
10008     std::string Str;
10009     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10010       unsigned len = Str.length();
10011       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10012       unsigned numBits = Ty->getPrimitiveSizeInBits();
10013       // Replace LI with immediate integer store.
10014       if ((numBits >> 3) == len + 1) {
10015         APInt StrVal(numBits, 0);
10016         APInt SingleChar(numBits, 0);
10017         if (TD->isLittleEndian()) {
10018           for (signed i = len-1; i >= 0; i--) {
10019             SingleChar = (uint64_t) Str[i];
10020             StrVal = (StrVal << 8) | SingleChar;
10021           }
10022         } else {
10023           for (unsigned i = 0; i < len; i++) {
10024             SingleChar = (uint64_t) Str[i];
10025             StrVal = (StrVal << 8) | SingleChar;
10026           }
10027           // Append NULL at the end.
10028           SingleChar = 0;
10029           StrVal = (StrVal << 8) | SingleChar;
10030         }
10031         Value *NL = ConstantInt::get(StrVal);
10032         return IC.ReplaceInstUsesWith(LI, NL);
10033       }
10034     }
10035   }
10036
10037   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10038   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10039     const Type *SrcPTy = SrcTy->getElementType();
10040
10041     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10042          isa<VectorType>(DestPTy)) {
10043       // If the source is an array, the code below will not succeed.  Check to
10044       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10045       // constants.
10046       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10047         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10048           if (ASrcTy->getNumElements() != 0) {
10049             Value *Idxs[2];
10050             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10051             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10052             SrcTy = cast<PointerType>(CastOp->getType());
10053             SrcPTy = SrcTy->getElementType();
10054           }
10055
10056       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10057             isa<VectorType>(SrcPTy)) &&
10058           // Do not allow turning this into a load of an integer, which is then
10059           // casted to a pointer, this pessimizes pointer analysis a lot.
10060           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10061           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10062                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10063
10064         // Okay, we are casting from one integer or pointer type to another of
10065         // the same size.  Instead of casting the pointer before the load, cast
10066         // the result of the loaded value.
10067         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10068                                                              CI->getName(),
10069                                                          LI.isVolatile()),LI);
10070         // Now cast the result of the load.
10071         return new BitCastInst(NewLoad, LI.getType());
10072       }
10073     }
10074   }
10075   return 0;
10076 }
10077
10078 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10079 /// from this value cannot trap.  If it is not obviously safe to load from the
10080 /// specified pointer, we do a quick local scan of the basic block containing
10081 /// ScanFrom, to determine if the address is already accessed.
10082 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10083   // If it is an alloca it is always safe to load from.
10084   if (isa<AllocaInst>(V)) return true;
10085
10086   // If it is a global variable it is mostly safe to load from.
10087   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10088     // Don't try to evaluate aliases.  External weak GV can be null.
10089     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10090
10091   // Otherwise, be a little bit agressive by scanning the local block where we
10092   // want to check to see if the pointer is already being loaded or stored
10093   // from/to.  If so, the previous load or store would have already trapped,
10094   // so there is no harm doing an extra load (also, CSE will later eliminate
10095   // the load entirely).
10096   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10097
10098   while (BBI != E) {
10099     --BBI;
10100
10101     // If we see a free or a call (which might do a free) the pointer could be
10102     // marked invalid.
10103     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10104       return false;
10105     
10106     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10107       if (LI->getOperand(0) == V) return true;
10108     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10109       if (SI->getOperand(1) == V) return true;
10110     }
10111
10112   }
10113   return false;
10114 }
10115
10116 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10117 /// until we find the underlying object a pointer is referring to or something
10118 /// we don't understand.  Note that the returned pointer may be offset from the
10119 /// input, because we ignore GEP indices.
10120 static Value *GetUnderlyingObject(Value *Ptr) {
10121   while (1) {
10122     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10123       if (CE->getOpcode() == Instruction::BitCast ||
10124           CE->getOpcode() == Instruction::GetElementPtr)
10125         Ptr = CE->getOperand(0);
10126       else
10127         return Ptr;
10128     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10129       Ptr = BCI->getOperand(0);
10130     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10131       Ptr = GEP->getOperand(0);
10132     } else {
10133       return Ptr;
10134     }
10135   }
10136 }
10137
10138 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10139   Value *Op = LI.getOperand(0);
10140
10141   // Attempt to improve the alignment.
10142   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10143   if (KnownAlign >
10144       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10145                                 LI.getAlignment()))
10146     LI.setAlignment(KnownAlign);
10147
10148   // load (cast X) --> cast (load X) iff safe
10149   if (isa<CastInst>(Op))
10150     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10151       return Res;
10152
10153   // None of the following transforms are legal for volatile loads.
10154   if (LI.isVolatile()) return 0;
10155   
10156   if (&LI.getParent()->front() != &LI) {
10157     BasicBlock::iterator BBI = &LI; --BBI;
10158     // If the instruction immediately before this is a store to the same
10159     // address, do a simple form of store->load forwarding.
10160     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10161       if (SI->getOperand(1) == LI.getOperand(0))
10162         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10163     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10164       if (LIB->getOperand(0) == LI.getOperand(0))
10165         return ReplaceInstUsesWith(LI, LIB);
10166   }
10167
10168   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10169     const Value *GEPI0 = GEPI->getOperand(0);
10170     // TODO: Consider a target hook for valid address spaces for this xform.
10171     if (isa<ConstantPointerNull>(GEPI0) &&
10172         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10173       // Insert a new store to null instruction before the load to indicate
10174       // that this code is not reachable.  We do this instead of inserting
10175       // an unreachable instruction directly because we cannot modify the
10176       // CFG.
10177       new StoreInst(UndefValue::get(LI.getType()),
10178                     Constant::getNullValue(Op->getType()), &LI);
10179       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10180     }
10181   } 
10182
10183   if (Constant *C = dyn_cast<Constant>(Op)) {
10184     // load null/undef -> undef
10185     // TODO: Consider a target hook for valid address spaces for this xform.
10186     if (isa<UndefValue>(C) || (C->isNullValue() && 
10187         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10188       // Insert a new store to null instruction before the load to indicate that
10189       // this code is not reachable.  We do this instead of inserting an
10190       // unreachable instruction directly because we cannot modify the CFG.
10191       new StoreInst(UndefValue::get(LI.getType()),
10192                     Constant::getNullValue(Op->getType()), &LI);
10193       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10194     }
10195
10196     // Instcombine load (constant global) into the value loaded.
10197     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10198       if (GV->isConstant() && !GV->isDeclaration())
10199         return ReplaceInstUsesWith(LI, GV->getInitializer());
10200
10201     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10202     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10203       if (CE->getOpcode() == Instruction::GetElementPtr) {
10204         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10205           if (GV->isConstant() && !GV->isDeclaration())
10206             if (Constant *V = 
10207                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10208               return ReplaceInstUsesWith(LI, V);
10209         if (CE->getOperand(0)->isNullValue()) {
10210           // Insert a new store to null instruction before the load to indicate
10211           // that this code is not reachable.  We do this instead of inserting
10212           // an unreachable instruction directly because we cannot modify the
10213           // CFG.
10214           new StoreInst(UndefValue::get(LI.getType()),
10215                         Constant::getNullValue(Op->getType()), &LI);
10216           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10217         }
10218
10219       } else if (CE->isCast()) {
10220         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10221           return Res;
10222       }
10223     }
10224   }
10225     
10226   // If this load comes from anywhere in a constant global, and if the global
10227   // is all undef or zero, we know what it loads.
10228   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10229     if (GV->isConstant() && GV->hasInitializer()) {
10230       if (GV->getInitializer()->isNullValue())
10231         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10232       else if (isa<UndefValue>(GV->getInitializer()))
10233         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10234     }
10235   }
10236
10237   if (Op->hasOneUse()) {
10238     // Change select and PHI nodes to select values instead of addresses: this
10239     // helps alias analysis out a lot, allows many others simplifications, and
10240     // exposes redundancy in the code.
10241     //
10242     // Note that we cannot do the transformation unless we know that the
10243     // introduced loads cannot trap!  Something like this is valid as long as
10244     // the condition is always false: load (select bool %C, int* null, int* %G),
10245     // but it would not be valid if we transformed it to load from null
10246     // unconditionally.
10247     //
10248     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10249       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10250       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10251           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10252         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10253                                      SI->getOperand(1)->getName()+".val"), LI);
10254         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10255                                      SI->getOperand(2)->getName()+".val"), LI);
10256         return SelectInst::Create(SI->getCondition(), V1, V2);
10257       }
10258
10259       // load (select (cond, null, P)) -> load P
10260       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10261         if (C->isNullValue()) {
10262           LI.setOperand(0, SI->getOperand(2));
10263           return &LI;
10264         }
10265
10266       // load (select (cond, P, null)) -> load P
10267       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10268         if (C->isNullValue()) {
10269           LI.setOperand(0, SI->getOperand(1));
10270           return &LI;
10271         }
10272     }
10273   }
10274   return 0;
10275 }
10276
10277 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10278 /// when possible.
10279 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10280   User *CI = cast<User>(SI.getOperand(1));
10281   Value *CastOp = CI->getOperand(0);
10282
10283   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10284   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10285     const Type *SrcPTy = SrcTy->getElementType();
10286
10287     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10288       // If the source is an array, the code below will not succeed.  Check to
10289       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10290       // constants.
10291       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10292         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10293           if (ASrcTy->getNumElements() != 0) {
10294             Value* Idxs[2];
10295             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10296             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10297             SrcTy = cast<PointerType>(CastOp->getType());
10298             SrcPTy = SrcTy->getElementType();
10299           }
10300
10301       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10302           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10303                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10304
10305         // Okay, we are casting from one integer or pointer type to another of
10306         // the same size.  Instead of casting the pointer before 
10307         // the store, cast the value to be stored.
10308         Value *NewCast;
10309         Value *SIOp0 = SI.getOperand(0);
10310         Instruction::CastOps opcode = Instruction::BitCast;
10311         const Type* CastSrcTy = SIOp0->getType();
10312         const Type* CastDstTy = SrcPTy;
10313         if (isa<PointerType>(CastDstTy)) {
10314           if (CastSrcTy->isInteger())
10315             opcode = Instruction::IntToPtr;
10316         } else if (isa<IntegerType>(CastDstTy)) {
10317           if (isa<PointerType>(SIOp0->getType()))
10318             opcode = Instruction::PtrToInt;
10319         }
10320         if (Constant *C = dyn_cast<Constant>(SIOp0))
10321           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10322         else
10323           NewCast = IC.InsertNewInstBefore(
10324             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10325             SI);
10326         return new StoreInst(NewCast, CastOp);
10327       }
10328     }
10329   }
10330   return 0;
10331 }
10332
10333 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10334   Value *Val = SI.getOperand(0);
10335   Value *Ptr = SI.getOperand(1);
10336
10337   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10338     EraseInstFromFunction(SI);
10339     ++NumCombined;
10340     return 0;
10341   }
10342   
10343   // If the RHS is an alloca with a single use, zapify the store, making the
10344   // alloca dead.
10345   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10346     if (isa<AllocaInst>(Ptr)) {
10347       EraseInstFromFunction(SI);
10348       ++NumCombined;
10349       return 0;
10350     }
10351     
10352     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10353       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10354           GEP->getOperand(0)->hasOneUse()) {
10355         EraseInstFromFunction(SI);
10356         ++NumCombined;
10357         return 0;
10358       }
10359   }
10360
10361   // Attempt to improve the alignment.
10362   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10363   if (KnownAlign >
10364       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10365                                 SI.getAlignment()))
10366     SI.setAlignment(KnownAlign);
10367
10368   // Do really simple DSE, to catch cases where there are several consequtive
10369   // stores to the same location, separated by a few arithmetic operations. This
10370   // situation often occurs with bitfield accesses.
10371   BasicBlock::iterator BBI = &SI;
10372   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10373        --ScanInsts) {
10374     --BBI;
10375     
10376     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10377       // Prev store isn't volatile, and stores to the same location?
10378       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10379         ++NumDeadStore;
10380         ++BBI;
10381         EraseInstFromFunction(*PrevSI);
10382         continue;
10383       }
10384       break;
10385     }
10386     
10387     // If this is a load, we have to stop.  However, if the loaded value is from
10388     // the pointer we're loading and is producing the pointer we're storing,
10389     // then *this* store is dead (X = load P; store X -> P).
10390     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10391       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10392         EraseInstFromFunction(SI);
10393         ++NumCombined;
10394         return 0;
10395       }
10396       // Otherwise, this is a load from some other location.  Stores before it
10397       // may not be dead.
10398       break;
10399     }
10400     
10401     // Don't skip over loads or things that can modify memory.
10402     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10403       break;
10404   }
10405   
10406   
10407   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10408
10409   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10410   if (isa<ConstantPointerNull>(Ptr)) {
10411     if (!isa<UndefValue>(Val)) {
10412       SI.setOperand(0, UndefValue::get(Val->getType()));
10413       if (Instruction *U = dyn_cast<Instruction>(Val))
10414         AddToWorkList(U);  // Dropped a use.
10415       ++NumCombined;
10416     }
10417     return 0;  // Do not modify these!
10418   }
10419
10420   // store undef, Ptr -> noop
10421   if (isa<UndefValue>(Val)) {
10422     EraseInstFromFunction(SI);
10423     ++NumCombined;
10424     return 0;
10425   }
10426
10427   // If the pointer destination is a cast, see if we can fold the cast into the
10428   // source instead.
10429   if (isa<CastInst>(Ptr))
10430     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10431       return Res;
10432   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10433     if (CE->isCast())
10434       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10435         return Res;
10436
10437   
10438   // If this store is the last instruction in the basic block, and if the block
10439   // ends with an unconditional branch, try to move it to the successor block.
10440   BBI = &SI; ++BBI;
10441   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10442     if (BI->isUnconditional())
10443       if (SimplifyStoreAtEndOfBlock(SI))
10444         return 0;  // xform done!
10445   
10446   return 0;
10447 }
10448
10449 /// SimplifyStoreAtEndOfBlock - Turn things like:
10450 ///   if () { *P = v1; } else { *P = v2 }
10451 /// into a phi node with a store in the successor.
10452 ///
10453 /// Simplify things like:
10454 ///   *P = v1; if () { *P = v2; }
10455 /// into a phi node with a store in the successor.
10456 ///
10457 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10458   BasicBlock *StoreBB = SI.getParent();
10459   
10460   // Check to see if the successor block has exactly two incoming edges.  If
10461   // so, see if the other predecessor contains a store to the same location.
10462   // if so, insert a PHI node (if needed) and move the stores down.
10463   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10464   
10465   // Determine whether Dest has exactly two predecessors and, if so, compute
10466   // the other predecessor.
10467   pred_iterator PI = pred_begin(DestBB);
10468   BasicBlock *OtherBB = 0;
10469   if (*PI != StoreBB)
10470     OtherBB = *PI;
10471   ++PI;
10472   if (PI == pred_end(DestBB))
10473     return false;
10474   
10475   if (*PI != StoreBB) {
10476     if (OtherBB)
10477       return false;
10478     OtherBB = *PI;
10479   }
10480   if (++PI != pred_end(DestBB))
10481     return false;
10482
10483   // Bail out if all the relevant blocks aren't distinct (this can happen,
10484   // for example, if SI is in an infinite loop)
10485   if (StoreBB == DestBB || OtherBB == DestBB)
10486     return false;
10487
10488   // Verify that the other block ends in a branch and is not otherwise empty.
10489   BasicBlock::iterator BBI = OtherBB->getTerminator();
10490   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10491   if (!OtherBr || BBI == OtherBB->begin())
10492     return false;
10493   
10494   // If the other block ends in an unconditional branch, check for the 'if then
10495   // else' case.  there is an instruction before the branch.
10496   StoreInst *OtherStore = 0;
10497   if (OtherBr->isUnconditional()) {
10498     // If this isn't a store, or isn't a store to the same location, bail out.
10499     --BBI;
10500     OtherStore = dyn_cast<StoreInst>(BBI);
10501     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10502       return false;
10503   } else {
10504     // Otherwise, the other block ended with a conditional branch. If one of the
10505     // destinations is StoreBB, then we have the if/then case.
10506     if (OtherBr->getSuccessor(0) != StoreBB && 
10507         OtherBr->getSuccessor(1) != StoreBB)
10508       return false;
10509     
10510     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10511     // if/then triangle.  See if there is a store to the same ptr as SI that
10512     // lives in OtherBB.
10513     for (;; --BBI) {
10514       // Check to see if we find the matching store.
10515       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10516         if (OtherStore->getOperand(1) != SI.getOperand(1))
10517           return false;
10518         break;
10519       }
10520       // If we find something that may be using or overwriting the stored
10521       // value, or if we run out of instructions, we can't do the xform.
10522       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10523           BBI == OtherBB->begin())
10524         return false;
10525     }
10526     
10527     // In order to eliminate the store in OtherBr, we have to
10528     // make sure nothing reads or overwrites the stored value in
10529     // StoreBB.
10530     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10531       // FIXME: This should really be AA driven.
10532       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10533         return false;
10534     }
10535   }
10536   
10537   // Insert a PHI node now if we need it.
10538   Value *MergedVal = OtherStore->getOperand(0);
10539   if (MergedVal != SI.getOperand(0)) {
10540     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10541     PN->reserveOperandSpace(2);
10542     PN->addIncoming(SI.getOperand(0), SI.getParent());
10543     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10544     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10545   }
10546   
10547   // Advance to a place where it is safe to insert the new store and
10548   // insert it.
10549   BBI = DestBB->getFirstNonPHI();
10550   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10551                                     OtherStore->isVolatile()), *BBI);
10552   
10553   // Nuke the old stores.
10554   EraseInstFromFunction(SI);
10555   EraseInstFromFunction(*OtherStore);
10556   ++NumCombined;
10557   return true;
10558 }
10559
10560
10561 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10562   // Change br (not X), label True, label False to: br X, label False, True
10563   Value *X = 0;
10564   BasicBlock *TrueDest;
10565   BasicBlock *FalseDest;
10566   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10567       !isa<Constant>(X)) {
10568     // Swap Destinations and condition...
10569     BI.setCondition(X);
10570     BI.setSuccessor(0, FalseDest);
10571     BI.setSuccessor(1, TrueDest);
10572     return &BI;
10573   }
10574
10575   // Cannonicalize fcmp_one -> fcmp_oeq
10576   FCmpInst::Predicate FPred; Value *Y;
10577   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10578                              TrueDest, FalseDest)))
10579     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10580          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10581       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10582       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10583       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10584       NewSCC->takeName(I);
10585       // Swap Destinations and condition...
10586       BI.setCondition(NewSCC);
10587       BI.setSuccessor(0, FalseDest);
10588       BI.setSuccessor(1, TrueDest);
10589       RemoveFromWorkList(I);
10590       I->eraseFromParent();
10591       AddToWorkList(NewSCC);
10592       return &BI;
10593     }
10594
10595   // Cannonicalize icmp_ne -> icmp_eq
10596   ICmpInst::Predicate IPred;
10597   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10598                       TrueDest, FalseDest)))
10599     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10600          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10601          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10602       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10603       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10604       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10605       NewSCC->takeName(I);
10606       // Swap Destinations and condition...
10607       BI.setCondition(NewSCC);
10608       BI.setSuccessor(0, FalseDest);
10609       BI.setSuccessor(1, TrueDest);
10610       RemoveFromWorkList(I);
10611       I->eraseFromParent();;
10612       AddToWorkList(NewSCC);
10613       return &BI;
10614     }
10615
10616   return 0;
10617 }
10618
10619 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10620   Value *Cond = SI.getCondition();
10621   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10622     if (I->getOpcode() == Instruction::Add)
10623       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10624         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10625         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10626           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10627                                                 AddRHS));
10628         SI.setOperand(0, I->getOperand(0));
10629         AddToWorkList(I);
10630         return &SI;
10631       }
10632   }
10633   return 0;
10634 }
10635
10636 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10637   // See if we are trying to extract a known value. If so, use that instead.
10638   if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10639                                      EV.idx_end(), &EV))
10640     return ReplaceInstUsesWith(EV, Elt);
10641
10642   // No changes
10643   return 0;
10644 }
10645
10646 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10647 /// is to leave as a vector operation.
10648 static bool CheapToScalarize(Value *V, bool isConstant) {
10649   if (isa<ConstantAggregateZero>(V)) 
10650     return true;
10651   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10652     if (isConstant) return true;
10653     // If all elts are the same, we can extract.
10654     Constant *Op0 = C->getOperand(0);
10655     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10656       if (C->getOperand(i) != Op0)
10657         return false;
10658     return true;
10659   }
10660   Instruction *I = dyn_cast<Instruction>(V);
10661   if (!I) return false;
10662   
10663   // Insert element gets simplified to the inserted element or is deleted if
10664   // this is constant idx extract element and its a constant idx insertelt.
10665   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10666       isa<ConstantInt>(I->getOperand(2)))
10667     return true;
10668   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10669     return true;
10670   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10671     if (BO->hasOneUse() &&
10672         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10673          CheapToScalarize(BO->getOperand(1), isConstant)))
10674       return true;
10675   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10676     if (CI->hasOneUse() &&
10677         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10678          CheapToScalarize(CI->getOperand(1), isConstant)))
10679       return true;
10680   
10681   return false;
10682 }
10683
10684 /// Read and decode a shufflevector mask.
10685 ///
10686 /// It turns undef elements into values that are larger than the number of
10687 /// elements in the input.
10688 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10689   unsigned NElts = SVI->getType()->getNumElements();
10690   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10691     return std::vector<unsigned>(NElts, 0);
10692   if (isa<UndefValue>(SVI->getOperand(2)))
10693     return std::vector<unsigned>(NElts, 2*NElts);
10694
10695   std::vector<unsigned> Result;
10696   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10697   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10698     if (isa<UndefValue>(*i))
10699       Result.push_back(NElts*2);  // undef -> 8
10700     else
10701       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10702   return Result;
10703 }
10704
10705 /// FindScalarElement - Given a vector and an element number, see if the scalar
10706 /// value is already around as a register, for example if it were inserted then
10707 /// extracted from the vector.
10708 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10709   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10710   const VectorType *PTy = cast<VectorType>(V->getType());
10711   unsigned Width = PTy->getNumElements();
10712   if (EltNo >= Width)  // Out of range access.
10713     return UndefValue::get(PTy->getElementType());
10714   
10715   if (isa<UndefValue>(V))
10716     return UndefValue::get(PTy->getElementType());
10717   else if (isa<ConstantAggregateZero>(V))
10718     return Constant::getNullValue(PTy->getElementType());
10719   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10720     return CP->getOperand(EltNo);
10721   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10722     // If this is an insert to a variable element, we don't know what it is.
10723     if (!isa<ConstantInt>(III->getOperand(2))) 
10724       return 0;
10725     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10726     
10727     // If this is an insert to the element we are looking for, return the
10728     // inserted value.
10729     if (EltNo == IIElt) 
10730       return III->getOperand(1);
10731     
10732     // Otherwise, the insertelement doesn't modify the value, recurse on its
10733     // vector input.
10734     return FindScalarElement(III->getOperand(0), EltNo);
10735   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10736     unsigned InEl = getShuffleMask(SVI)[EltNo];
10737     if (InEl < Width)
10738       return FindScalarElement(SVI->getOperand(0), InEl);
10739     else if (InEl < Width*2)
10740       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10741     else
10742       return UndefValue::get(PTy->getElementType());
10743   }
10744   
10745   // Otherwise, we don't know.
10746   return 0;
10747 }
10748
10749 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10750   // If vector val is undef, replace extract with scalar undef.
10751   if (isa<UndefValue>(EI.getOperand(0)))
10752     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10753
10754   // If vector val is constant 0, replace extract with scalar 0.
10755   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10756     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10757   
10758   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10759     // If vector val is constant with all elements the same, replace EI with
10760     // that element. When the elements are not identical, we cannot replace yet
10761     // (we do that below, but only when the index is constant).
10762     Constant *op0 = C->getOperand(0);
10763     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10764       if (C->getOperand(i) != op0) {
10765         op0 = 0; 
10766         break;
10767       }
10768     if (op0)
10769       return ReplaceInstUsesWith(EI, op0);
10770   }
10771   
10772   // If extracting a specified index from the vector, see if we can recursively
10773   // find a previously computed scalar that was inserted into the vector.
10774   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10775     unsigned IndexVal = IdxC->getZExtValue();
10776     unsigned VectorWidth = 
10777       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10778       
10779     // If this is extracting an invalid index, turn this into undef, to avoid
10780     // crashing the code below.
10781     if (IndexVal >= VectorWidth)
10782       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10783     
10784     // This instruction only demands the single element from the input vector.
10785     // If the input vector has a single use, simplify it based on this use
10786     // property.
10787     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10788       uint64_t UndefElts;
10789       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10790                                                 1 << IndexVal,
10791                                                 UndefElts)) {
10792         EI.setOperand(0, V);
10793         return &EI;
10794       }
10795     }
10796     
10797     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10798       return ReplaceInstUsesWith(EI, Elt);
10799     
10800     // If the this extractelement is directly using a bitcast from a vector of
10801     // the same number of elements, see if we can find the source element from
10802     // it.  In this case, we will end up needing to bitcast the scalars.
10803     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10804       if (const VectorType *VT = 
10805               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10806         if (VT->getNumElements() == VectorWidth)
10807           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10808             return new BitCastInst(Elt, EI.getType());
10809     }
10810   }
10811   
10812   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10813     if (I->hasOneUse()) {
10814       // Push extractelement into predecessor operation if legal and
10815       // profitable to do so
10816       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10817         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10818         if (CheapToScalarize(BO, isConstantElt)) {
10819           ExtractElementInst *newEI0 = 
10820             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10821                                    EI.getName()+".lhs");
10822           ExtractElementInst *newEI1 =
10823             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10824                                    EI.getName()+".rhs");
10825           InsertNewInstBefore(newEI0, EI);
10826           InsertNewInstBefore(newEI1, EI);
10827           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10828         }
10829       } else if (isa<LoadInst>(I)) {
10830         unsigned AS = 
10831           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10832         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10833                                          PointerType::get(EI.getType(), AS),EI);
10834         GetElementPtrInst *GEP =
10835           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10836         InsertNewInstBefore(GEP, EI);
10837         return new LoadInst(GEP);
10838       }
10839     }
10840     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10841       // Extracting the inserted element?
10842       if (IE->getOperand(2) == EI.getOperand(1))
10843         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10844       // If the inserted and extracted elements are constants, they must not
10845       // be the same value, extract from the pre-inserted value instead.
10846       if (isa<Constant>(IE->getOperand(2)) &&
10847           isa<Constant>(EI.getOperand(1))) {
10848         AddUsesToWorkList(EI);
10849         EI.setOperand(0, IE->getOperand(0));
10850         return &EI;
10851       }
10852     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10853       // If this is extracting an element from a shufflevector, figure out where
10854       // it came from and extract from the appropriate input element instead.
10855       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10856         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10857         Value *Src;
10858         if (SrcIdx < SVI->getType()->getNumElements())
10859           Src = SVI->getOperand(0);
10860         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10861           SrcIdx -= SVI->getType()->getNumElements();
10862           Src = SVI->getOperand(1);
10863         } else {
10864           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10865         }
10866         return new ExtractElementInst(Src, SrcIdx);
10867       }
10868     }
10869   }
10870   return 0;
10871 }
10872
10873 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10874 /// elements from either LHS or RHS, return the shuffle mask and true. 
10875 /// Otherwise, return false.
10876 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10877                                          std::vector<Constant*> &Mask) {
10878   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10879          "Invalid CollectSingleShuffleElements");
10880   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10881
10882   if (isa<UndefValue>(V)) {
10883     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10884     return true;
10885   } else if (V == LHS) {
10886     for (unsigned i = 0; i != NumElts; ++i)
10887       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10888     return true;
10889   } else if (V == RHS) {
10890     for (unsigned i = 0; i != NumElts; ++i)
10891       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10892     return true;
10893   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10894     // If this is an insert of an extract from some other vector, include it.
10895     Value *VecOp    = IEI->getOperand(0);
10896     Value *ScalarOp = IEI->getOperand(1);
10897     Value *IdxOp    = IEI->getOperand(2);
10898     
10899     if (!isa<ConstantInt>(IdxOp))
10900       return false;
10901     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10902     
10903     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10904       // Okay, we can handle this if the vector we are insertinting into is
10905       // transitively ok.
10906       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10907         // If so, update the mask to reflect the inserted undef.
10908         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10909         return true;
10910       }      
10911     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10912       if (isa<ConstantInt>(EI->getOperand(1)) &&
10913           EI->getOperand(0)->getType() == V->getType()) {
10914         unsigned ExtractedIdx =
10915           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10916         
10917         // This must be extracting from either LHS or RHS.
10918         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10919           // Okay, we can handle this if the vector we are insertinting into is
10920           // transitively ok.
10921           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10922             // If so, update the mask to reflect the inserted value.
10923             if (EI->getOperand(0) == LHS) {
10924               Mask[InsertedIdx & (NumElts-1)] = 
10925                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10926             } else {
10927               assert(EI->getOperand(0) == RHS);
10928               Mask[InsertedIdx & (NumElts-1)] = 
10929                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10930               
10931             }
10932             return true;
10933           }
10934         }
10935       }
10936     }
10937   }
10938   // TODO: Handle shufflevector here!
10939   
10940   return false;
10941 }
10942
10943 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10944 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10945 /// that computes V and the LHS value of the shuffle.
10946 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10947                                      Value *&RHS) {
10948   assert(isa<VectorType>(V->getType()) && 
10949          (RHS == 0 || V->getType() == RHS->getType()) &&
10950          "Invalid shuffle!");
10951   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10952
10953   if (isa<UndefValue>(V)) {
10954     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10955     return V;
10956   } else if (isa<ConstantAggregateZero>(V)) {
10957     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10958     return V;
10959   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10960     // If this is an insert of an extract from some other vector, include it.
10961     Value *VecOp    = IEI->getOperand(0);
10962     Value *ScalarOp = IEI->getOperand(1);
10963     Value *IdxOp    = IEI->getOperand(2);
10964     
10965     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10966       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10967           EI->getOperand(0)->getType() == V->getType()) {
10968         unsigned ExtractedIdx =
10969           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10970         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10971         
10972         // Either the extracted from or inserted into vector must be RHSVec,
10973         // otherwise we'd end up with a shuffle of three inputs.
10974         if (EI->getOperand(0) == RHS || RHS == 0) {
10975           RHS = EI->getOperand(0);
10976           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10977           Mask[InsertedIdx & (NumElts-1)] = 
10978             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10979           return V;
10980         }
10981         
10982         if (VecOp == RHS) {
10983           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10984           // Everything but the extracted element is replaced with the RHS.
10985           for (unsigned i = 0; i != NumElts; ++i) {
10986             if (i != InsertedIdx)
10987               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10988           }
10989           return V;
10990         }
10991         
10992         // If this insertelement is a chain that comes from exactly these two
10993         // vectors, return the vector and the effective shuffle.
10994         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10995           return EI->getOperand(0);
10996         
10997       }
10998     }
10999   }
11000   // TODO: Handle shufflevector here!
11001   
11002   // Otherwise, can't do anything fancy.  Return an identity vector.
11003   for (unsigned i = 0; i != NumElts; ++i)
11004     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11005   return V;
11006 }
11007
11008 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11009   Value *VecOp    = IE.getOperand(0);
11010   Value *ScalarOp = IE.getOperand(1);
11011   Value *IdxOp    = IE.getOperand(2);
11012   
11013   // Inserting an undef or into an undefined place, remove this.
11014   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11015     ReplaceInstUsesWith(IE, VecOp);
11016   
11017   // If the inserted element was extracted from some other vector, and if the 
11018   // indexes are constant, try to turn this into a shufflevector operation.
11019   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11020     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11021         EI->getOperand(0)->getType() == IE.getType()) {
11022       unsigned NumVectorElts = IE.getType()->getNumElements();
11023       unsigned ExtractedIdx =
11024         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11025       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11026       
11027       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11028         return ReplaceInstUsesWith(IE, VecOp);
11029       
11030       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11031         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11032       
11033       // If we are extracting a value from a vector, then inserting it right
11034       // back into the same place, just use the input vector.
11035       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11036         return ReplaceInstUsesWith(IE, VecOp);      
11037       
11038       // We could theoretically do this for ANY input.  However, doing so could
11039       // turn chains of insertelement instructions into a chain of shufflevector
11040       // instructions, and right now we do not merge shufflevectors.  As such,
11041       // only do this in a situation where it is clear that there is benefit.
11042       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11043         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11044         // the values of VecOp, except then one read from EIOp0.
11045         // Build a new shuffle mask.
11046         std::vector<Constant*> Mask;
11047         if (isa<UndefValue>(VecOp))
11048           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11049         else {
11050           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11051           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11052                                                        NumVectorElts));
11053         } 
11054         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11055         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11056                                      ConstantVector::get(Mask));
11057       }
11058       
11059       // If this insertelement isn't used by some other insertelement, turn it
11060       // (and any insertelements it points to), into one big shuffle.
11061       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11062         std::vector<Constant*> Mask;
11063         Value *RHS = 0;
11064         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11065         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11066         // We now have a shuffle of LHS, RHS, Mask.
11067         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11068       }
11069     }
11070   }
11071
11072   return 0;
11073 }
11074
11075
11076 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11077   Value *LHS = SVI.getOperand(0);
11078   Value *RHS = SVI.getOperand(1);
11079   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11080
11081   bool MadeChange = false;
11082   
11083   // Undefined shuffle mask -> undefined value.
11084   if (isa<UndefValue>(SVI.getOperand(2)))
11085     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11086   
11087   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11088   // the undef, change them to undefs.
11089   if (isa<UndefValue>(SVI.getOperand(1))) {
11090     // Scan to see if there are any references to the RHS.  If so, replace them
11091     // with undef element refs and set MadeChange to true.
11092     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11093       if (Mask[i] >= e && Mask[i] != 2*e) {
11094         Mask[i] = 2*e;
11095         MadeChange = true;
11096       }
11097     }
11098     
11099     if (MadeChange) {
11100       // Remap any references to RHS to use LHS.
11101       std::vector<Constant*> Elts;
11102       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11103         if (Mask[i] == 2*e)
11104           Elts.push_back(UndefValue::get(Type::Int32Ty));
11105         else
11106           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11107       }
11108       SVI.setOperand(2, ConstantVector::get(Elts));
11109     }
11110   }
11111   
11112   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11113   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11114   if (LHS == RHS || isa<UndefValue>(LHS)) {
11115     if (isa<UndefValue>(LHS) && LHS == RHS) {
11116       // shuffle(undef,undef,mask) -> undef.
11117       return ReplaceInstUsesWith(SVI, LHS);
11118     }
11119     
11120     // Remap any references to RHS to use LHS.
11121     std::vector<Constant*> Elts;
11122     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11123       if (Mask[i] >= 2*e)
11124         Elts.push_back(UndefValue::get(Type::Int32Ty));
11125       else {
11126         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11127             (Mask[i] <  e && isa<UndefValue>(LHS)))
11128           Mask[i] = 2*e;     // Turn into undef.
11129         else
11130           Mask[i] &= (e-1);  // Force to LHS.
11131         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11132       }
11133     }
11134     SVI.setOperand(0, SVI.getOperand(1));
11135     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11136     SVI.setOperand(2, ConstantVector::get(Elts));
11137     LHS = SVI.getOperand(0);
11138     RHS = SVI.getOperand(1);
11139     MadeChange = true;
11140   }
11141   
11142   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11143   bool isLHSID = true, isRHSID = true;
11144     
11145   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11146     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11147     // Is this an identity shuffle of the LHS value?
11148     isLHSID &= (Mask[i] == i);
11149       
11150     // Is this an identity shuffle of the RHS value?
11151     isRHSID &= (Mask[i]-e == i);
11152   }
11153
11154   // Eliminate identity shuffles.
11155   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11156   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11157   
11158   // If the LHS is a shufflevector itself, see if we can combine it with this
11159   // one without producing an unusual shuffle.  Here we are really conservative:
11160   // we are absolutely afraid of producing a shuffle mask not in the input
11161   // program, because the code gen may not be smart enough to turn a merged
11162   // shuffle into two specific shuffles: it may produce worse code.  As such,
11163   // we only merge two shuffles if the result is one of the two input shuffle
11164   // masks.  In this case, merging the shuffles just removes one instruction,
11165   // which we know is safe.  This is good for things like turning:
11166   // (splat(splat)) -> splat.
11167   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11168     if (isa<UndefValue>(RHS)) {
11169       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11170
11171       std::vector<unsigned> NewMask;
11172       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11173         if (Mask[i] >= 2*e)
11174           NewMask.push_back(2*e);
11175         else
11176           NewMask.push_back(LHSMask[Mask[i]]);
11177       
11178       // If the result mask is equal to the src shuffle or this shuffle mask, do
11179       // the replacement.
11180       if (NewMask == LHSMask || NewMask == Mask) {
11181         std::vector<Constant*> Elts;
11182         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11183           if (NewMask[i] >= e*2) {
11184             Elts.push_back(UndefValue::get(Type::Int32Ty));
11185           } else {
11186             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11187           }
11188         }
11189         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11190                                      LHSSVI->getOperand(1),
11191                                      ConstantVector::get(Elts));
11192       }
11193     }
11194   }
11195
11196   return MadeChange ? &SVI : 0;
11197 }
11198
11199
11200
11201
11202 /// TryToSinkInstruction - Try to move the specified instruction from its
11203 /// current block into the beginning of DestBlock, which can only happen if it's
11204 /// safe to move the instruction past all of the instructions between it and the
11205 /// end of its block.
11206 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11207   assert(I->hasOneUse() && "Invariants didn't hold!");
11208
11209   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11210   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11211     return false;
11212
11213   // Do not sink alloca instructions out of the entry block.
11214   if (isa<AllocaInst>(I) && I->getParent() ==
11215         &DestBlock->getParent()->getEntryBlock())
11216     return false;
11217
11218   // We can only sink load instructions if there is nothing between the load and
11219   // the end of block that could change the value.
11220   if (I->mayReadFromMemory()) {
11221     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11222          Scan != E; ++Scan)
11223       if (Scan->mayWriteToMemory())
11224         return false;
11225   }
11226
11227   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11228
11229   I->moveBefore(InsertPos);
11230   ++NumSunkInst;
11231   return true;
11232 }
11233
11234
11235 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11236 /// all reachable code to the worklist.
11237 ///
11238 /// This has a couple of tricks to make the code faster and more powerful.  In
11239 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11240 /// them to the worklist (this significantly speeds up instcombine on code where
11241 /// many instructions are dead or constant).  Additionally, if we find a branch
11242 /// whose condition is a known constant, we only visit the reachable successors.
11243 ///
11244 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11245                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11246                                        InstCombiner &IC,
11247                                        const TargetData *TD) {
11248   std::vector<BasicBlock*> Worklist;
11249   Worklist.push_back(BB);
11250
11251   while (!Worklist.empty()) {
11252     BB = Worklist.back();
11253     Worklist.pop_back();
11254     
11255     // We have now visited this block!  If we've already been here, ignore it.
11256     if (!Visited.insert(BB)) continue;
11257     
11258     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11259       Instruction *Inst = BBI++;
11260       
11261       // DCE instruction if trivially dead.
11262       if (isInstructionTriviallyDead(Inst)) {
11263         ++NumDeadInst;
11264         DOUT << "IC: DCE: " << *Inst;
11265         Inst->eraseFromParent();
11266         continue;
11267       }
11268       
11269       // ConstantProp instruction if trivially constant.
11270       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11271         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11272         Inst->replaceAllUsesWith(C);
11273         ++NumConstProp;
11274         Inst->eraseFromParent();
11275         continue;
11276       }
11277      
11278       IC.AddToWorkList(Inst);
11279     }
11280
11281     // Recursively visit successors.  If this is a branch or switch on a
11282     // constant, only visit the reachable successor.
11283     TerminatorInst *TI = BB->getTerminator();
11284     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11285       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11286         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11287         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11288         Worklist.push_back(ReachableBB);
11289         continue;
11290       }
11291     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11292       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11293         // See if this is an explicit destination.
11294         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11295           if (SI->getCaseValue(i) == Cond) {
11296             BasicBlock *ReachableBB = SI->getSuccessor(i);
11297             Worklist.push_back(ReachableBB);
11298             continue;
11299           }
11300         
11301         // Otherwise it is the default destination.
11302         Worklist.push_back(SI->getSuccessor(0));
11303         continue;
11304       }
11305     }
11306     
11307     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11308       Worklist.push_back(TI->getSuccessor(i));
11309   }
11310 }
11311
11312 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11313   bool Changed = false;
11314   TD = &getAnalysis<TargetData>();
11315   
11316   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11317              << F.getNameStr() << "\n");
11318
11319   {
11320     // Do a depth-first traversal of the function, populate the worklist with
11321     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11322     // track of which blocks we visit.
11323     SmallPtrSet<BasicBlock*, 64> Visited;
11324     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11325
11326     // Do a quick scan over the function.  If we find any blocks that are
11327     // unreachable, remove any instructions inside of them.  This prevents
11328     // the instcombine code from having to deal with some bad special cases.
11329     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11330       if (!Visited.count(BB)) {
11331         Instruction *Term = BB->getTerminator();
11332         while (Term != BB->begin()) {   // Remove instrs bottom-up
11333           BasicBlock::iterator I = Term; --I;
11334
11335           DOUT << "IC: DCE: " << *I;
11336           ++NumDeadInst;
11337
11338           if (!I->use_empty())
11339             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11340           I->eraseFromParent();
11341         }
11342       }
11343   }
11344
11345   while (!Worklist.empty()) {
11346     Instruction *I = RemoveOneFromWorkList();
11347     if (I == 0) continue;  // skip null values.
11348
11349     // Check to see if we can DCE the instruction.
11350     if (isInstructionTriviallyDead(I)) {
11351       // Add operands to the worklist.
11352       if (I->getNumOperands() < 4)
11353         AddUsesToWorkList(*I);
11354       ++NumDeadInst;
11355
11356       DOUT << "IC: DCE: " << *I;
11357
11358       I->eraseFromParent();
11359       RemoveFromWorkList(I);
11360       continue;
11361     }
11362
11363     // Instruction isn't dead, see if we can constant propagate it.
11364     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11365       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11366
11367       // Add operands to the worklist.
11368       AddUsesToWorkList(*I);
11369       ReplaceInstUsesWith(*I, C);
11370
11371       ++NumConstProp;
11372       I->eraseFromParent();
11373       RemoveFromWorkList(I);
11374       continue;
11375     }
11376
11377     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11378       // See if we can constant fold its operands.
11379       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11380         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11381           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11382             i->set(NewC);
11383         }
11384       }
11385     }
11386
11387     // See if we can trivially sink this instruction to a successor basic block.
11388     // FIXME: Remove GetResultInst test when first class support for aggregates
11389     // is implemented.
11390     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11391       BasicBlock *BB = I->getParent();
11392       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11393       if (UserParent != BB) {
11394         bool UserIsSuccessor = false;
11395         // See if the user is one of our successors.
11396         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11397           if (*SI == UserParent) {
11398             UserIsSuccessor = true;
11399             break;
11400           }
11401
11402         // If the user is one of our immediate successors, and if that successor
11403         // only has us as a predecessors (we'd have to split the critical edge
11404         // otherwise), we can keep going.
11405         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11406             next(pred_begin(UserParent)) == pred_end(UserParent))
11407           // Okay, the CFG is simple enough, try to sink this instruction.
11408           Changed |= TryToSinkInstruction(I, UserParent);
11409       }
11410     }
11411
11412     // Now that we have an instruction, try combining it to simplify it...
11413 #ifndef NDEBUG
11414     std::string OrigI;
11415 #endif
11416     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11417     if (Instruction *Result = visit(*I)) {
11418       ++NumCombined;
11419       // Should we replace the old instruction with a new one?
11420       if (Result != I) {
11421         DOUT << "IC: Old = " << *I
11422              << "    New = " << *Result;
11423
11424         // Everything uses the new instruction now.
11425         I->replaceAllUsesWith(Result);
11426
11427         // Push the new instruction and any users onto the worklist.
11428         AddToWorkList(Result);
11429         AddUsersToWorkList(*Result);
11430
11431         // Move the name to the new instruction first.
11432         Result->takeName(I);
11433
11434         // Insert the new instruction into the basic block...
11435         BasicBlock *InstParent = I->getParent();
11436         BasicBlock::iterator InsertPos = I;
11437
11438         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11439           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11440             ++InsertPos;
11441
11442         InstParent->getInstList().insert(InsertPos, Result);
11443
11444         // Make sure that we reprocess all operands now that we reduced their
11445         // use counts.
11446         AddUsesToWorkList(*I);
11447
11448         // Instructions can end up on the worklist more than once.  Make sure
11449         // we do not process an instruction that has been deleted.
11450         RemoveFromWorkList(I);
11451
11452         // Erase the old instruction.
11453         InstParent->getInstList().erase(I);
11454       } else {
11455 #ifndef NDEBUG
11456         DOUT << "IC: Mod = " << OrigI
11457              << "    New = " << *I;
11458 #endif
11459
11460         // If the instruction was modified, it's possible that it is now dead.
11461         // if so, remove it.
11462         if (isInstructionTriviallyDead(I)) {
11463           // Make sure we process all operands now that we are reducing their
11464           // use counts.
11465           AddUsesToWorkList(*I);
11466
11467           // Instructions may end up in the worklist more than once.  Erase all
11468           // occurrences of this instruction.
11469           RemoveFromWorkList(I);
11470           I->eraseFromParent();
11471         } else {
11472           AddToWorkList(I);
11473           AddUsersToWorkList(*I);
11474         }
11475       }
11476       Changed = true;
11477     }
11478   }
11479
11480   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11481     
11482   // Do an explicit clear, this shrinks the map if needed.
11483   WorklistMap.clear();
11484   return Changed;
11485 }
11486
11487
11488 bool InstCombiner::runOnFunction(Function &F) {
11489   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11490   
11491   bool EverMadeChange = false;
11492
11493   // Iterate while there is work to do.
11494   unsigned Iteration = 0;
11495   while (DoOneIteration(F, Iteration++))
11496     EverMadeChange = true;
11497   return EverMadeChange;
11498 }
11499
11500 FunctionPass *llvm::createInstructionCombiningPass() {
11501   return new InstCombiner();
11502 }
11503