Use Instruction::moveBefore instead of manipulating the instruction list
[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())))
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     Instruction *commonRemTransforms(BinaryOperator &I);
176     Instruction *commonIRemTransforms(BinaryOperator &I);
177     Instruction *commonDivTransforms(BinaryOperator &I);
178     Instruction *commonIDivTransforms(BinaryOperator &I);
179     Instruction *visitUDiv(BinaryOperator &I);
180     Instruction *visitSDiv(BinaryOperator &I);
181     Instruction *visitFDiv(BinaryOperator &I);
182     Instruction *visitAnd(BinaryOperator &I);
183     Instruction *visitOr (BinaryOperator &I);
184     Instruction *visitXor(BinaryOperator &I);
185     Instruction *visitShl(BinaryOperator &I);
186     Instruction *visitAShr(BinaryOperator &I);
187     Instruction *visitLShr(BinaryOperator &I);
188     Instruction *commonShiftTransforms(BinaryOperator &I);
189     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190                                       Constant *RHSC);
191     Instruction *visitFCmpInst(FCmpInst &I);
192     Instruction *visitICmpInst(ICmpInst &I);
193     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195                                                 Instruction *LHS,
196                                                 ConstantInt *RHS);
197     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198                                 ConstantInt *DivRHS);
199
200     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201                              ICmpInst::Predicate Cond, Instruction &I);
202     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203                                      BinaryOperator &I);
204     Instruction *commonCastTransforms(CastInst &CI);
205     Instruction *commonIntCastTransforms(CastInst &CI);
206     Instruction *commonPointerCastTransforms(CastInst &CI);
207     Instruction *visitTrunc(TruncInst &CI);
208     Instruction *visitZExt(ZExtInst &CI);
209     Instruction *visitSExt(SExtInst &CI);
210     Instruction *visitFPTrunc(FPTruncInst &CI);
211     Instruction *visitFPExt(CastInst &CI);
212     Instruction *visitFPToUI(FPToUIInst &FI);
213     Instruction *visitFPToSI(FPToSIInst &FI);
214     Instruction *visitUIToFP(CastInst &CI);
215     Instruction *visitSIToFP(CastInst &CI);
216     Instruction *visitPtrToInt(CastInst &CI);
217     Instruction *visitIntToPtr(IntToPtrInst &CI);
218     Instruction *visitBitCast(BitCastInst &CI);
219     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220                                 Instruction *FI);
221     Instruction *visitSelectInst(SelectInst &CI);
222     Instruction *visitCallInst(CallInst &CI);
223     Instruction *visitInvokeInst(InvokeInst &II);
224     Instruction *visitPHINode(PHINode &PN);
225     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226     Instruction *visitAllocationInst(AllocationInst &AI);
227     Instruction *visitFreeInst(FreeInst &FI);
228     Instruction *visitLoadInst(LoadInst &LI);
229     Instruction *visitStoreInst(StoreInst &SI);
230     Instruction *visitBranchInst(BranchInst &BI);
231     Instruction *visitSwitchInst(SwitchInst &SI);
232     Instruction *visitInsertElementInst(InsertElementInst &IE);
233     Instruction *visitExtractElementInst(ExtractElementInst &EI);
234     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235     Instruction *visitExtractValueInst(ExtractValueInst &EV);
236
237     // visitInstruction - Specify what to return for unhandled instructions...
238     Instruction *visitInstruction(Instruction &I) { return 0; }
239
240   private:
241     Instruction *visitCallSite(CallSite CS);
242     bool transformConstExprCastCall(CallSite CS);
243     Instruction *transformCallThroughTrampoline(CallSite CS);
244     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245                                    bool DoXform = true);
246     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247
248   public:
249     // InsertNewInstBefore - insert an instruction New before instruction Old
250     // in the program.  Add the new instruction to the worklist.
251     //
252     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253       assert(New && New->getParent() == 0 &&
254              "New instruction already inserted into a basic block!");
255       BasicBlock *BB = Old.getParent();
256       BB->getInstList().insert(&Old, New);  // Insert inst
257       AddToWorkList(New);
258       return New;
259     }
260
261     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262     /// This also adds the cast to the worklist.  Finally, this returns the
263     /// cast.
264     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265                             Instruction &Pos) {
266       if (V->getType() == Ty) return V;
267
268       if (Constant *CV = dyn_cast<Constant>(V))
269         return ConstantExpr::getCast(opc, CV, Ty);
270       
271       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
272       AddToWorkList(C);
273       return C;
274     }
275         
276     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278     }
279
280
281     // ReplaceInstUsesWith - This method is to be used when an instruction is
282     // found to be dead, replacable with another preexisting expression.  Here
283     // we add all uses of I to the worklist, replace all uses of I with the new
284     // value, then return I, so that the inst combiner will know that I was
285     // modified.
286     //
287     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288       AddUsersToWorkList(I);         // Add all modified instrs to worklist
289       if (&I != V) {
290         I.replaceAllUsesWith(V);
291         return &I;
292       } else {
293         // If we are replacing the instruction with itself, this must be in a
294         // segment of unreachable code, so just clobber the instruction.
295         I.replaceAllUsesWith(UndefValue::get(I.getType()));
296         return &I;
297       }
298     }
299
300     // UpdateValueUsesWith - This method is to be used when an value is
301     // found to be replacable with another preexisting expression or was
302     // updated.  Here we add all uses of I to the worklist, replace all uses of
303     // I with the new value (unless the instruction was just updated), then
304     // return true, so that the inst combiner will know that I was modified.
305     //
306     bool UpdateValueUsesWith(Value *Old, Value *New) {
307       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
308       if (Old != New)
309         Old->replaceAllUsesWith(New);
310       if (Instruction *I = dyn_cast<Instruction>(Old))
311         AddToWorkList(I);
312       if (Instruction *I = dyn_cast<Instruction>(New))
313         AddToWorkList(I);
314       return true;
315     }
316     
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
345     /// casts that are known to not do anything...
346     ///
347     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348                                    Value *V, const Type *DestTy,
349                                    Instruction *InsertBefore);
350
351     /// SimplifyCommutative - This performs a few simplifications for 
352     /// commutative operators.
353     bool SimplifyCommutative(BinaryOperator &I);
354
355     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356     /// most-complex to least-complex order.
357     bool SimplifyCompare(CmpInst &I);
358
359     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360     /// on the demanded bits.
361     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
362                               APInt& KnownZero, APInt& KnownOne,
363                               unsigned Depth = 0);
364
365     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366                                       uint64_t &UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
438 /// expression bitcast,  return the operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441     return I->getOperand(0);
442   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443     if (CE->getOpcode() == Instruction::BitCast)
444       return CE->getOperand(0);
445   return 0;
446 }
447
448 /// This function is a wrapper around CastInst::isEliminableCastPair. It
449 /// simply extracts arguments and returns what that function returns.
450 static Instruction::CastOps 
451 isEliminableCastPair(
452   const CastInst *CI, ///< The first cast instruction
453   unsigned opcode,       ///< The opcode of the second cast instruction
454   const Type *DstTy,     ///< The target type for the second cast instruction
455   TargetData *TD         ///< The target data for pointer size
456 ) {
457   
458   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
459   const Type *MidTy = CI->getType();                  // B from above
460
461   // Get the opcodes of the two Cast instructions
462   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
464
465   return Instruction::CastOps(
466       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467                                      DstTy, TD->getIntPtrType()));
468 }
469
470 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471 /// in any code being generated.  It does not require codegen if V is simple
472 /// enough or if the cast can be folded into other casts.
473 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
474                               const Type *Ty, TargetData *TD) {
475   if (V->getType() == Ty || isa<Constant>(V)) return false;
476   
477   // If this is another cast that can be eliminated, it isn't codegen either.
478   if (const CastInst *CI = dyn_cast<CastInst>(V))
479     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
480       return false;
481   return true;
482 }
483
484 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
486 /// casts that are known to not do anything...
487 ///
488 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489                                              Value *V, const Type *DestTy,
490                                              Instruction *InsertBefore) {
491   if (V->getType() == DestTy) return V;
492   if (Constant *C = dyn_cast<Constant>(V))
493     return ConstantExpr::getCast(opcode, C, DestTy);
494   
495   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
496 }
497
498 // SimplifyCommutative - This performs a few simplifications for commutative
499 // operators:
500 //
501 //  1. Order operands such that they are listed from right (least complex) to
502 //     left (most complex).  This puts constants before unary operators before
503 //     binary operators.
504 //
505 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507 //
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509   bool Changed = false;
510   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511     Changed = !I.swapOperands();
512
513   if (!I.isAssociative()) return Changed;
514   Instruction::BinaryOps Opcode = I.getOpcode();
515   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517       if (isa<Constant>(I.getOperand(1))) {
518         Constant *Folded = ConstantExpr::get(I.getOpcode(),
519                                              cast<Constant>(I.getOperand(1)),
520                                              cast<Constant>(Op->getOperand(1)));
521         I.setOperand(0, Op->getOperand(0));
522         I.setOperand(1, Folded);
523         return true;
524       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526             isOnlyUse(Op) && isOnlyUse(Op1)) {
527           Constant *C1 = cast<Constant>(Op->getOperand(1));
528           Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
532           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
533                                                     Op1->getOperand(0),
534                                                     Op1->getName(), &I);
535           AddToWorkList(New);
536           I.setOperand(0, New);
537           I.setOperand(1, Folded);
538           return true;
539         }
540     }
541   return Changed;
542 }
543
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549     return false;
550   I.swapOperands();
551   // Compare instructions are not associative so there's nothing else we can do.
552   return true;
553 }
554
555 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556 // if the LHS is a constant zero (which is the 'negate' form).
557 //
558 static inline Value *dyn_castNegVal(Value *V) {
559   if (BinaryOperator::isNeg(V))
560     return BinaryOperator::getNegArgument(V);
561
562   // Constants can be considered to be negated values if they can be folded.
563   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564     return ConstantExpr::getNeg(C);
565
566   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567     if (C->getType()->getElementType()->isInteger())
568       return ConstantExpr::getNeg(C);
569
570   return 0;
571 }
572
573 static inline Value *dyn_castNotVal(Value *V) {
574   if (BinaryOperator::isNot(V))
575     return BinaryOperator::getNotArgument(V);
576
577   // Constants can be considered to be not'ed values...
578   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579     return ConstantInt::get(~C->getValue());
580   return 0;
581 }
582
583 // dyn_castFoldableMul - If this value is a multiply that can be folded into
584 // other computations (because it has a constant operand), return the
585 // non-constant operand of the multiply, and set CST to point to the multiplier.
586 // Otherwise, return null.
587 //
588 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589   if (V->hasOneUse() && V->getType()->isInteger())
590     if (Instruction *I = dyn_cast<Instruction>(V)) {
591       if (I->getOpcode() == Instruction::Mul)
592         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593           return I->getOperand(0);
594       if (I->getOpcode() == Instruction::Shl)
595         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596           // The multiplier is really 1 << CST.
597           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600           return I->getOperand(0);
601         }
602     }
603   return 0;
604 }
605
606 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607 /// expression, return it.
608 static User *dyn_castGetElementPtr(Value *V) {
609   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611     if (CE->getOpcode() == Instruction::GetElementPtr)
612       return cast<User>(V);
613   return false;
614 }
615
616 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
617 /// opcode value. Otherwise return UserOp1.
618 static unsigned getOpcode(const Value *V) {
619   if (const Instruction *I = dyn_cast<Instruction>(V))
620     return I->getOpcode();
621   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
622     return CE->getOpcode();
623   // Use UserOp1 to mean there's no opcode.
624   return Instruction::UserOp1;
625 }
626
627 /// AddOne - Add one to a ConstantInt
628 static ConstantInt *AddOne(ConstantInt *C) {
629   APInt Val(C->getValue());
630   return ConstantInt::get(++Val);
631 }
632 /// SubOne - Subtract one from a ConstantInt
633 static ConstantInt *SubOne(ConstantInt *C) {
634   APInt Val(C->getValue());
635   return ConstantInt::get(--Val);
636 }
637 /// Add - Add two ConstantInts together
638 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() + C2->getValue());
640 }
641 /// And - Bitwise AND two ConstantInts together
642 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() & C2->getValue());
644 }
645 /// Subtract - Subtract one ConstantInt from another
646 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() - C2->getValue());
648 }
649 /// Multiply - Multiply two ConstantInts together
650 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651   return ConstantInt::get(C1->getValue() * C2->getValue());
652 }
653 /// MultiplyOverflows - True if the multiply can not be expressed in an int
654 /// this size.
655 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656   uint32_t W = C1->getBitWidth();
657   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658   if (sign) {
659     LHSExt.sext(W * 2);
660     RHSExt.sext(W * 2);
661   } else {
662     LHSExt.zext(W * 2);
663     RHSExt.zext(W * 2);
664   }
665
666   APInt MulExt = LHSExt * RHSExt;
667
668   if (sign) {
669     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671     return MulExt.slt(Min) || MulExt.sgt(Max);
672   } else 
673     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674 }
675
676
677 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
678 /// specified instruction is a constant integer.  If so, check to see if there
679 /// are any bits set in the constant that are not demanded.  If so, shrink the
680 /// constant and return true.
681 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
682                                    APInt Demanded) {
683   assert(I && "No instruction?");
684   assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686   // If the operand is not a constant integer, nothing to do.
687   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688   if (!OpC) return false;
689
690   // If there are no bits set that aren't demanded, nothing to do.
691   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692   if ((~Demanded & OpC->getValue()) == 0)
693     return false;
694
695   // This instruction is producing bits that are not demanded. Shrink the RHS.
696   Demanded &= OpC->getValue();
697   I->setOperand(OpNo, ConstantInt::get(Demanded));
698   return true;
699 }
700
701 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
702 // set of known zero and one bits, compute the maximum and minimum values that
703 // could have the specified known zero and known one bits, returning them in
704 // min/max.
705 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706                                                    const APInt& KnownZero,
707                                                    const APInt& KnownOne,
708                                                    APInt& Min, APInt& Max) {
709   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710   assert(KnownZero.getBitWidth() == BitWidth && 
711          KnownOne.getBitWidth() == BitWidth &&
712          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714   APInt UnknownBits = ~(KnownZero|KnownOne);
715
716   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717   // bit if it is unknown.
718   Min = KnownOne;
719   Max = KnownOne|UnknownBits;
720   
721   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
722     Min.set(BitWidth-1);
723     Max.clear(BitWidth-1);
724   }
725 }
726
727 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728 // a set of known zero and one bits, compute the maximum and minimum values that
729 // could have the specified known zero and known one bits, returning them in
730 // min/max.
731 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
732                                                      const APInt &KnownZero,
733                                                      const APInt &KnownOne,
734                                                      APInt &Min, APInt &Max) {
735   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
736   assert(KnownZero.getBitWidth() == BitWidth && 
737          KnownOne.getBitWidth() == BitWidth &&
738          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740   APInt UnknownBits = ~(KnownZero|KnownOne);
741   
742   // The minimum value is when the unknown bits are all zeros.
743   Min = KnownOne;
744   // The maximum value is when the unknown bits are all ones.
745   Max = KnownOne|UnknownBits;
746 }
747
748 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
749 /// value based on the demanded bits. When this function is called, it is known
750 /// that only the bits set in DemandedMask of the result of V are ever used
751 /// downstream. Consequently, depending on the mask and V, it may be possible
752 /// to replace V with a constant or one of its operands. In such cases, this
753 /// function does the replacement and returns true. In all other cases, it
754 /// returns false after analyzing the expression and setting KnownOne and known
755 /// to be one in the expression. KnownZero contains all the bits that are known
756 /// to be zero in the expression. These are provided to potentially allow the
757 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758 /// the expression. KnownOne and KnownZero always follow the invariant that 
759 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
761 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762 /// and KnownOne must all be the same.
763 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764                                         APInt& KnownZero, APInt& KnownOne,
765                                         unsigned Depth) {
766   assert(V != 0 && "Null pointer of Value???");
767   assert(Depth <= 6 && "Limit Search Depth");
768   uint32_t BitWidth = DemandedMask.getBitWidth();
769   const IntegerType *VTy = cast<IntegerType>(V->getType());
770   assert(VTy->getBitWidth() == BitWidth && 
771          KnownZero.getBitWidth() == BitWidth && 
772          KnownOne.getBitWidth() == BitWidth &&
773          "Value *V, DemandedMask, KnownZero and KnownOne \
774           must have same BitWidth");
775   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776     // We know all of the bits for a constant!
777     KnownOne = CI->getValue() & DemandedMask;
778     KnownZero = ~KnownOne & DemandedMask;
779     return false;
780   }
781   
782   KnownZero.clear(); 
783   KnownOne.clear();
784   if (!V->hasOneUse()) {    // Other users may use these bits.
785     if (Depth != 0) {       // Not at the root.
786       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788       return false;
789     }
790     // If this is the root being simplified, allow it to have multiple uses,
791     // just set the DemandedMask to all bits.
792     DemandedMask = APInt::getAllOnesValue(BitWidth);
793   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
794     if (V != UndefValue::get(VTy))
795       return UpdateValueUsesWith(V, UndefValue::get(VTy));
796     return false;
797   } else if (Depth == 6) {        // Limit search depth.
798     return false;
799   }
800   
801   Instruction *I = dyn_cast<Instruction>(V);
802   if (!I) return false;        // Only analyze instructions.
803
804   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806   switch (I->getOpcode()) {
807   default:
808     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809     break;
810   case Instruction::And:
811     // If either the LHS or the RHS are Zero, the result is zero.
812     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813                              RHSKnownZero, RHSKnownOne, Depth+1))
814       return true;
815     assert((RHSKnownZero & RHSKnownOne) == 0 && 
816            "Bits known to be one AND zero?"); 
817
818     // If something is known zero on the RHS, the bits aren't demanded on the
819     // LHS.
820     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821                              LHSKnownZero, LHSKnownOne, Depth+1))
822       return true;
823     assert((LHSKnownZero & LHSKnownOne) == 0 && 
824            "Bits known to be one AND zero?"); 
825
826     // If all of the demanded bits are known 1 on one side, return the other.
827     // These bits cannot contribute to the result of the 'and'.
828     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
829         (DemandedMask & ~LHSKnownZero))
830       return UpdateValueUsesWith(I, I->getOperand(0));
831     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
832         (DemandedMask & ~RHSKnownZero))
833       return UpdateValueUsesWith(I, I->getOperand(1));
834     
835     // If all of the demanded bits in the inputs are known zeros, return zero.
836     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838       
839     // If the RHS is a constant, see if we can simplify it.
840     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841       return UpdateValueUsesWith(I, I);
842       
843     // Output known-1 bits are only known if set in both the LHS & RHS.
844     RHSKnownOne &= LHSKnownOne;
845     // Output known-0 are known to be clear if zero in either the LHS | RHS.
846     RHSKnownZero |= LHSKnownZero;
847     break;
848   case Instruction::Or:
849     // If either the LHS or the RHS are One, the result is One.
850     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
851                              RHSKnownZero, RHSKnownOne, Depth+1))
852       return true;
853     assert((RHSKnownZero & RHSKnownOne) == 0 && 
854            "Bits known to be one AND zero?"); 
855     // If something is known one on the RHS, the bits aren't demanded on the
856     // LHS.
857     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
858                              LHSKnownZero, LHSKnownOne, Depth+1))
859       return true;
860     assert((LHSKnownZero & LHSKnownOne) == 0 && 
861            "Bits known to be one AND zero?"); 
862     
863     // If all of the demanded bits are known zero on one side, return the other.
864     // These bits cannot contribute to the result of the 'or'.
865     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
866         (DemandedMask & ~LHSKnownOne))
867       return UpdateValueUsesWith(I, I->getOperand(0));
868     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
869         (DemandedMask & ~RHSKnownOne))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871
872     // If all of the potentially set bits on one side are known to be set on
873     // the other side, just use the 'other' side.
874     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
875         (DemandedMask & (~RHSKnownZero)))
876       return UpdateValueUsesWith(I, I->getOperand(0));
877     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
878         (DemandedMask & (~LHSKnownZero)))
879       return UpdateValueUsesWith(I, I->getOperand(1));
880         
881     // If the RHS is a constant, see if we can simplify it.
882     if (ShrinkDemandedConstant(I, 1, DemandedMask))
883       return UpdateValueUsesWith(I, I);
884           
885     // Output known-0 bits are only known if clear in both the LHS & RHS.
886     RHSKnownZero &= LHSKnownZero;
887     // Output known-1 are known to be set if set in either the LHS | RHS.
888     RHSKnownOne |= LHSKnownOne;
889     break;
890   case Instruction::Xor: {
891     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892                              RHSKnownZero, RHSKnownOne, Depth+1))
893       return true;
894     assert((RHSKnownZero & RHSKnownOne) == 0 && 
895            "Bits known to be one AND zero?"); 
896     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
897                              LHSKnownZero, LHSKnownOne, Depth+1))
898       return true;
899     assert((LHSKnownZero & LHSKnownOne) == 0 && 
900            "Bits known to be one AND zero?"); 
901     
902     // If all of the demanded bits are known zero on one side, return the other.
903     // These bits cannot contribute to the result of the 'xor'.
904     if ((DemandedMask & RHSKnownZero) == DemandedMask)
905       return UpdateValueUsesWith(I, I->getOperand(0));
906     if ((DemandedMask & LHSKnownZero) == DemandedMask)
907       return UpdateValueUsesWith(I, I->getOperand(1));
908     
909     // Output known-0 bits are known if clear or set in both the LHS & RHS.
910     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
911                          (RHSKnownOne & LHSKnownOne);
912     // Output known-1 are known to be set if set in only one of the LHS, RHS.
913     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
914                         (RHSKnownOne & LHSKnownZero);
915     
916     // If all of the demanded bits are known to be zero on one side or the
917     // other, turn this into an *inclusive* or.
918     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920       Instruction *Or =
921         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
922                                  I->getName());
923       InsertNewInstBefore(Or, *I);
924       return UpdateValueUsesWith(I, Or);
925     }
926     
927     // If all of the demanded bits on one side are known, and all of the set
928     // bits on that side are also known to be set on the other side, turn this
929     // into an AND, as we know the bits will be cleared.
930     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
932       // all known
933       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935         Instruction *And = 
936           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
937         InsertNewInstBefore(And, *I);
938         return UpdateValueUsesWith(I, And);
939       }
940     }
941     
942     // If the RHS is a constant, see if we can simplify it.
943     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944     if (ShrinkDemandedConstant(I, 1, DemandedMask))
945       return UpdateValueUsesWith(I, I);
946     
947     RHSKnownZero = KnownZeroOut;
948     RHSKnownOne  = KnownOneOut;
949     break;
950   }
951   case Instruction::Select:
952     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953                              RHSKnownZero, RHSKnownOne, Depth+1))
954       return true;
955     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
956                              LHSKnownZero, LHSKnownOne, Depth+1))
957       return true;
958     assert((RHSKnownZero & RHSKnownOne) == 0 && 
959            "Bits known to be one AND zero?"); 
960     assert((LHSKnownZero & LHSKnownOne) == 0 && 
961            "Bits known to be one AND zero?"); 
962     
963     // If the operands are constants, see if we can simplify them.
964     if (ShrinkDemandedConstant(I, 1, DemandedMask))
965       return UpdateValueUsesWith(I, I);
966     if (ShrinkDemandedConstant(I, 2, DemandedMask))
967       return UpdateValueUsesWith(I, I);
968     
969     // Only known if known in both the LHS and RHS.
970     RHSKnownOne &= LHSKnownOne;
971     RHSKnownZero &= LHSKnownZero;
972     break;
973   case Instruction::Trunc: {
974     uint32_t truncBf = 
975       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976     DemandedMask.zext(truncBf);
977     RHSKnownZero.zext(truncBf);
978     RHSKnownOne.zext(truncBf);
979     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
980                              RHSKnownZero, RHSKnownOne, Depth+1))
981       return true;
982     DemandedMask.trunc(BitWidth);
983     RHSKnownZero.trunc(BitWidth);
984     RHSKnownOne.trunc(BitWidth);
985     assert((RHSKnownZero & RHSKnownOne) == 0 && 
986            "Bits known to be one AND zero?"); 
987     break;
988   }
989   case Instruction::BitCast:
990     if (!I->getOperand(0)->getType()->isInteger())
991       return false;
992       
993     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994                              RHSKnownZero, RHSKnownOne, Depth+1))
995       return true;
996     assert((RHSKnownZero & RHSKnownOne) == 0 && 
997            "Bits known to be one AND zero?"); 
998     break;
999   case Instruction::ZExt: {
1000     // Compute the bits in the result that are not present in the input.
1001     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1003     
1004     DemandedMask.trunc(SrcBitWidth);
1005     RHSKnownZero.trunc(SrcBitWidth);
1006     RHSKnownOne.trunc(SrcBitWidth);
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              RHSKnownZero, RHSKnownOne, Depth+1))
1009       return true;
1010     DemandedMask.zext(BitWidth);
1011     RHSKnownZero.zext(BitWidth);
1012     RHSKnownOne.zext(BitWidth);
1013     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1014            "Bits known to be one AND zero?"); 
1015     // The top bits are known to be zero.
1016     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1017     break;
1018   }
1019   case Instruction::SExt: {
1020     // Compute the bits in the result that are not present in the input.
1021     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1023     
1024     APInt InputDemandedBits = DemandedMask & 
1025                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1026
1027     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028     // If any of the sign extended bits are demanded, we know that the sign
1029     // bit is demanded.
1030     if ((NewBits & DemandedMask) != 0)
1031       InputDemandedBits.set(SrcBitWidth-1);
1032       
1033     InputDemandedBits.trunc(SrcBitWidth);
1034     RHSKnownZero.trunc(SrcBitWidth);
1035     RHSKnownOne.trunc(SrcBitWidth);
1036     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037                              RHSKnownZero, RHSKnownOne, Depth+1))
1038       return true;
1039     InputDemandedBits.zext(BitWidth);
1040     RHSKnownZero.zext(BitWidth);
1041     RHSKnownOne.zext(BitWidth);
1042     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1043            "Bits known to be one AND zero?"); 
1044       
1045     // If the sign bit of the input is known set or clear, then we know the
1046     // top bits of the result.
1047
1048     // If the input sign bit is known zero, or if the NewBits are not demanded
1049     // convert this into a zero extension.
1050     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1051     {
1052       // Convert to ZExt cast
1053       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054       return UpdateValueUsesWith(I, NewCast);
1055     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1056       RHSKnownOne |= NewBits;
1057     }
1058     break;
1059   }
1060   case Instruction::Add: {
1061     // Figure out what the input bits are.  If the top bits of the and result
1062     // are not demanded, then the add doesn't demand them from its input
1063     // either.
1064     uint32_t NLZ = DemandedMask.countLeadingZeros();
1065       
1066     // If there is a constant on the RHS, there are a variety of xformations
1067     // we can do.
1068     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069       // If null, this should be simplified elsewhere.  Some of the xforms here
1070       // won't work if the RHS is zero.
1071       if (RHS->isZero())
1072         break;
1073       
1074       // If the top bit of the output is demanded, demand everything from the
1075       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1076       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1077
1078       // Find information about known zero/one bits in the input.
1079       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1080                                LHSKnownZero, LHSKnownOne, Depth+1))
1081         return true;
1082
1083       // If the RHS of the add has bits set that can't affect the input, reduce
1084       // the constant.
1085       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086         return UpdateValueUsesWith(I, I);
1087       
1088       // Avoid excess work.
1089       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090         break;
1091       
1092       // Turn it into OR if input bits are zero.
1093       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094         Instruction *Or =
1095           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1096                                    I->getName());
1097         InsertNewInstBefore(Or, *I);
1098         return UpdateValueUsesWith(I, Or);
1099       }
1100       
1101       // We can say something about the output known-zero and known-one bits,
1102       // depending on potential carries from the input constant and the
1103       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1104       // bits set and the RHS constant is 0x01001, then we know we have a known
1105       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106       
1107       // To compute this, we first compute the potential carry bits.  These are
1108       // the bits which may be modified.  I'm not aware of a better way to do
1109       // this scan.
1110       const APInt& RHSVal = RHS->getValue();
1111       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1112       
1113       // Now that we know which bits have carries, compute the known-1/0 sets.
1114       
1115       // Bits are known one if they are known zero in one operand and one in the
1116       // other, and there is no input carry.
1117       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1118                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119       
1120       // Bits are known zero if they are known zero in both operands and there
1121       // is no input carry.
1122       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123     } else {
1124       // If the high-bits of this ADD are not demanded, then it does not demand
1125       // the high bits of its LHS or RHS.
1126       if (DemandedMask[BitWidth-1] == 0) {
1127         // Right fill the mask of bits for this ADD to demand the most
1128         // significant bit and all those below it.
1129         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131                                  LHSKnownZero, LHSKnownOne, Depth+1))
1132           return true;
1133         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134                                  LHSKnownZero, LHSKnownOne, Depth+1))
1135           return true;
1136       }
1137     }
1138     break;
1139   }
1140   case Instruction::Sub:
1141     // If the high-bits of this SUB are not demanded, then it does not demand
1142     // the high bits of its LHS or RHS.
1143     if (DemandedMask[BitWidth-1] == 0) {
1144       // Right fill the mask of bits for this SUB to demand the most
1145       // significant bit and all those below it.
1146       uint32_t NLZ = DemandedMask.countLeadingZeros();
1147       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149                                LHSKnownZero, LHSKnownOne, Depth+1))
1150         return true;
1151       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152                                LHSKnownZero, LHSKnownOne, Depth+1))
1153         return true;
1154     }
1155     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156     // the known zeros and ones.
1157     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1158     break;
1159   case Instruction::Shl:
1160     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1164                                RHSKnownZero, RHSKnownOne, Depth+1))
1165         return true;
1166       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1167              "Bits known to be one AND zero?"); 
1168       RHSKnownZero <<= ShiftAmt;
1169       RHSKnownOne  <<= ShiftAmt;
1170       // low bits known zero.
1171       if (ShiftAmt)
1172         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1173     }
1174     break;
1175   case Instruction::LShr:
1176     // For a logical shift right
1177     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1179       
1180       // Unsigned shift right.
1181       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183                                RHSKnownZero, RHSKnownOne, Depth+1))
1184         return true;
1185       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1186              "Bits known to be one AND zero?"); 
1187       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1189       if (ShiftAmt) {
1190         // Compute the new bits that are at the top now.
1191         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192         RHSKnownZero |= HighBits;  // high bits known zero.
1193       }
1194     }
1195     break;
1196   case Instruction::AShr:
1197     // If this is an arithmetic shift right and only the low-bit is set, we can
1198     // always convert this into a logical shr, even if the shift amount is
1199     // variable.  The low bit of the shift cannot be an input sign bit unless
1200     // the shift amount is >= the size of the datatype, which is undefined.
1201     if (DemandedMask == 1) {
1202       // Perform the logical shift right.
1203       Value *NewVal = BinaryOperator::CreateLShr(
1204                         I->getOperand(0), I->getOperand(1), I->getName());
1205       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206       return UpdateValueUsesWith(I, NewVal);
1207     }    
1208
1209     // If the sign bit is the only bit demanded by this ashr, then there is no
1210     // need to do it, the shift doesn't change the high bit.
1211     if (DemandedMask.isSignBit())
1212       return UpdateValueUsesWith(I, I->getOperand(0));
1213     
1214     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1216       
1217       // Signed shift right.
1218       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219       // If any of the "high bits" are demanded, we should set the sign bit as
1220       // demanded.
1221       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222         DemandedMaskIn.set(BitWidth-1);
1223       if (SimplifyDemandedBits(I->getOperand(0),
1224                                DemandedMaskIn,
1225                                RHSKnownZero, RHSKnownOne, Depth+1))
1226         return true;
1227       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1228              "Bits known to be one AND zero?"); 
1229       // Compute the new bits that are at the top now.
1230       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233         
1234       // Handle the sign bits.
1235       APInt SignBit(APInt::getSignBit(BitWidth));
1236       // Adjust to where it is now in the mask.
1237       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1238         
1239       // If the input sign bit is known to be zero, or if none of the top bits
1240       // are demanded, turn this into an unsigned shift right.
1241       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1242           (HighBits & ~DemandedMask) == HighBits) {
1243         // Perform the logical shift right.
1244         Value *NewVal = BinaryOperator::CreateLShr(
1245                           I->getOperand(0), SA, I->getName());
1246         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247         return UpdateValueUsesWith(I, NewVal);
1248       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249         RHSKnownOne |= HighBits;
1250       }
1251     }
1252     break;
1253   case Instruction::SRem:
1254     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255       APInt RA = Rem->getValue();
1256       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1257         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1258         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260                                  LHSKnownZero, LHSKnownOne, Depth+1))
1261           return true;
1262
1263         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264           LHSKnownZero |= ~LowBits;
1265         else if (LHSKnownOne[BitWidth-1])
1266           LHSKnownOne |= ~LowBits;
1267
1268         KnownZero |= LHSKnownZero & DemandedMask;
1269         KnownOne |= LHSKnownOne & DemandedMask;
1270
1271         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1272       }
1273     }
1274     break;
1275   case Instruction::URem: {
1276     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277       APInt RA = Rem->getValue();
1278       if (RA.isPowerOf2()) {
1279         APInt LowBits = (RA - 1);
1280         APInt Mask2 = LowBits & DemandedMask;
1281         KnownZero |= ~LowBits & DemandedMask;
1282         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283                                  KnownZero, KnownOne, Depth+1))
1284           return true;
1285
1286         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1287         break;
1288       }
1289     }
1290
1291     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1293     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294                              KnownZero2, KnownOne2, Depth+1))
1295       return true;
1296
1297     uint32_t Leaders = KnownZero2.countLeadingOnes();
1298     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1299                              KnownZero2, KnownOne2, Depth+1))
1300       return true;
1301
1302     Leaders = std::max(Leaders,
1303                        KnownZero2.countLeadingOnes());
1304     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1305     break;
1306   }
1307   case Instruction::Call:
1308     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309       switch (II->getIntrinsicID()) {
1310       default: break;
1311       case Intrinsic::bswap: {
1312         // If the only bits demanded come from one byte of the bswap result,
1313         // just shift the input byte into position to eliminate the bswap.
1314         unsigned NLZ = DemandedMask.countLeadingZeros();
1315         unsigned NTZ = DemandedMask.countTrailingZeros();
1316           
1317         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1318         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1319         // have 14 leading zeros, round to 8.
1320         NLZ &= ~7;
1321         NTZ &= ~7;
1322         // If we need exactly one byte, we can do this transformation.
1323         if (BitWidth-NLZ-NTZ == 8) {
1324           unsigned ResultBit = NTZ;
1325           unsigned InputBit = BitWidth-NTZ-8;
1326           
1327           // Replace this with either a left or right shift to get the byte into
1328           // the right place.
1329           Instruction *NewVal;
1330           if (InputBit > ResultBit)
1331             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1333           else
1334             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1336           NewVal->takeName(I);
1337           InsertNewInstBefore(NewVal, *I);
1338           return UpdateValueUsesWith(I, NewVal);
1339         }
1340           
1341         // TODO: Could compute known zero/one bits based on the input.
1342         break;
1343       }
1344       }
1345     }
1346     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1347     break;
1348   }
1349   
1350   // If the client is only demanding bits that we know, return the known
1351   // constant.
1352   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1353     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1354   return false;
1355 }
1356
1357
1358 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1359 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1360 /// actually used by the caller.  This method analyzes which elements of the
1361 /// operand are undef and returns that information in UndefElts.
1362 ///
1363 /// If the information about demanded elements can be used to simplify the
1364 /// operation, the operation is simplified, then the resultant value is
1365 /// returned.  This returns null if no change was made.
1366 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1367                                                 uint64_t &UndefElts,
1368                                                 unsigned Depth) {
1369   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1370   assert(VWidth <= 64 && "Vector too wide to analyze!");
1371   uint64_t EltMask = ~0ULL >> (64-VWidth);
1372   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1373          "Invalid DemandedElts!");
1374
1375   if (isa<UndefValue>(V)) {
1376     // If the entire vector is undefined, just return this info.
1377     UndefElts = EltMask;
1378     return 0;
1379   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1380     UndefElts = EltMask;
1381     return UndefValue::get(V->getType());
1382   }
1383   
1384   UndefElts = 0;
1385   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1386     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1387     Constant *Undef = UndefValue::get(EltTy);
1388
1389     std::vector<Constant*> Elts;
1390     for (unsigned i = 0; i != VWidth; ++i)
1391       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1392         Elts.push_back(Undef);
1393         UndefElts |= (1ULL << i);
1394       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1395         Elts.push_back(Undef);
1396         UndefElts |= (1ULL << i);
1397       } else {                               // Otherwise, defined.
1398         Elts.push_back(CP->getOperand(i));
1399       }
1400         
1401     // If we changed the constant, return it.
1402     Constant *NewCP = ConstantVector::get(Elts);
1403     return NewCP != CP ? NewCP : 0;
1404   } else if (isa<ConstantAggregateZero>(V)) {
1405     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1406     // set to undef.
1407     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1408     Constant *Zero = Constant::getNullValue(EltTy);
1409     Constant *Undef = UndefValue::get(EltTy);
1410     std::vector<Constant*> Elts;
1411     for (unsigned i = 0; i != VWidth; ++i)
1412       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1413     UndefElts = DemandedElts ^ EltMask;
1414     return ConstantVector::get(Elts);
1415   }
1416   
1417   if (!V->hasOneUse()) {    // Other users may use these bits.
1418     if (Depth != 0) {       // Not at the root.
1419       // TODO: Just compute the UndefElts information recursively.
1420       return false;
1421     }
1422     return false;
1423   } else if (Depth == 10) {        // Limit search depth.
1424     return false;
1425   }
1426   
1427   Instruction *I = dyn_cast<Instruction>(V);
1428   if (!I) return false;        // Only analyze instructions.
1429   
1430   bool MadeChange = false;
1431   uint64_t UndefElts2;
1432   Value *TmpV;
1433   switch (I->getOpcode()) {
1434   default: break;
1435     
1436   case Instruction::InsertElement: {
1437     // If this is a variable index, we don't know which element it overwrites.
1438     // demand exactly the same input as we produce.
1439     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1440     if (Idx == 0) {
1441       // Note that we can't propagate undef elt info, because we don't know
1442       // which elt is getting updated.
1443       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1444                                         UndefElts2, Depth+1);
1445       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1446       break;
1447     }
1448     
1449     // If this is inserting an element that isn't demanded, remove this
1450     // insertelement.
1451     unsigned IdxNo = Idx->getZExtValue();
1452     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1453       return AddSoonDeadInstToWorklist(*I, 0);
1454     
1455     // Otherwise, the element inserted overwrites whatever was there, so the
1456     // input demanded set is simpler than the output set.
1457     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1458                                       DemandedElts & ~(1ULL << IdxNo),
1459                                       UndefElts, Depth+1);
1460     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1461
1462     // The inserted element is defined.
1463     UndefElts |= 1ULL << IdxNo;
1464     break;
1465   }
1466   case Instruction::BitCast: {
1467     // Vector->vector casts only.
1468     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1469     if (!VTy) break;
1470     unsigned InVWidth = VTy->getNumElements();
1471     uint64_t InputDemandedElts = 0;
1472     unsigned Ratio;
1473
1474     if (VWidth == InVWidth) {
1475       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1476       // elements as are demanded of us.
1477       Ratio = 1;
1478       InputDemandedElts = DemandedElts;
1479     } else if (VWidth > InVWidth) {
1480       // Untested so far.
1481       break;
1482       
1483       // If there are more elements in the result than there are in the source,
1484       // then an input element is live if any of the corresponding output
1485       // elements are live.
1486       Ratio = VWidth/InVWidth;
1487       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1488         if (DemandedElts & (1ULL << OutIdx))
1489           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1490       }
1491     } else {
1492       // Untested so far.
1493       break;
1494       
1495       // If there are more elements in the source than there are in the result,
1496       // then an input element is live if the corresponding output element is
1497       // live.
1498       Ratio = InVWidth/VWidth;
1499       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1500         if (DemandedElts & (1ULL << InIdx/Ratio))
1501           InputDemandedElts |= 1ULL << InIdx;
1502     }
1503     
1504     // div/rem demand all inputs, because they don't want divide by zero.
1505     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1506                                       UndefElts2, Depth+1);
1507     if (TmpV) {
1508       I->setOperand(0, TmpV);
1509       MadeChange = true;
1510     }
1511     
1512     UndefElts = UndefElts2;
1513     if (VWidth > InVWidth) {
1514       assert(0 && "Unimp");
1515       // If there are more elements in the result than there are in the source,
1516       // then an output element is undef if the corresponding input element is
1517       // undef.
1518       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1519         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1520           UndefElts |= 1ULL << OutIdx;
1521     } else if (VWidth < InVWidth) {
1522       assert(0 && "Unimp");
1523       // If there are more elements in the source than there are in the result,
1524       // then a result element is undef if all of the corresponding input
1525       // elements are undef.
1526       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1527       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1529           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1530     }
1531     break;
1532   }
1533   case Instruction::And:
1534   case Instruction::Or:
1535   case Instruction::Xor:
1536   case Instruction::Add:
1537   case Instruction::Sub:
1538   case Instruction::Mul:
1539     // div/rem demand all inputs, because they don't want divide by zero.
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1544                                       UndefElts2, Depth+1);
1545     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1546       
1547     // Output elements are undefined if both are undefined.  Consider things
1548     // like undef&0.  The result is known zero, not undef.
1549     UndefElts &= UndefElts2;
1550     break;
1551     
1552   case Instruction::Call: {
1553     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1554     if (!II) break;
1555     switch (II->getIntrinsicID()) {
1556     default: break;
1557       
1558     // Binary vector operations that work column-wise.  A dest element is a
1559     // function of the corresponding input elements from the two inputs.
1560     case Intrinsic::x86_sse_sub_ss:
1561     case Intrinsic::x86_sse_mul_ss:
1562     case Intrinsic::x86_sse_min_ss:
1563     case Intrinsic::x86_sse_max_ss:
1564     case Intrinsic::x86_sse2_sub_sd:
1565     case Intrinsic::x86_sse2_mul_sd:
1566     case Intrinsic::x86_sse2_min_sd:
1567     case Intrinsic::x86_sse2_max_sd:
1568       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1569                                         UndefElts, Depth+1);
1570       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1571       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1572                                         UndefElts2, Depth+1);
1573       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1574
1575       // If only the low elt is demanded and this is a scalarizable intrinsic,
1576       // scalarize it now.
1577       if (DemandedElts == 1) {
1578         switch (II->getIntrinsicID()) {
1579         default: break;
1580         case Intrinsic::x86_sse_sub_ss:
1581         case Intrinsic::x86_sse_mul_ss:
1582         case Intrinsic::x86_sse2_sub_sd:
1583         case Intrinsic::x86_sse2_mul_sd:
1584           // TODO: Lower MIN/MAX/ABS/etc
1585           Value *LHS = II->getOperand(1);
1586           Value *RHS = II->getOperand(2);
1587           // Extract the element as scalars.
1588           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1589           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1590           
1591           switch (II->getIntrinsicID()) {
1592           default: assert(0 && "Case stmts out of sync!");
1593           case Intrinsic::x86_sse_sub_ss:
1594           case Intrinsic::x86_sse2_sub_sd:
1595             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1596                                                         II->getName()), *II);
1597             break;
1598           case Intrinsic::x86_sse_mul_ss:
1599           case Intrinsic::x86_sse2_mul_sd:
1600             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1601                                                          II->getName()), *II);
1602             break;
1603           }
1604           
1605           Instruction *New =
1606             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1607                                       II->getName());
1608           InsertNewInstBefore(New, *II);
1609           AddSoonDeadInstToWorklist(*II, 0);
1610           return New;
1611         }            
1612       }
1613         
1614       // Output elements are undefined if both are undefined.  Consider things
1615       // like undef&0.  The result is known zero, not undef.
1616       UndefElts &= UndefElts2;
1617       break;
1618     }
1619     break;
1620   }
1621   }
1622   return MadeChange ? I : 0;
1623 }
1624
1625
1626 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1627 /// function is designed to check a chain of associative operators for a
1628 /// potential to apply a certain optimization.  Since the optimization may be
1629 /// applicable if the expression was reassociated, this checks the chain, then
1630 /// reassociates the expression as necessary to expose the optimization
1631 /// opportunity.  This makes use of a special Functor, which must define
1632 /// 'shouldApply' and 'apply' methods.
1633 ///
1634 template<typename Functor>
1635 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1636   unsigned Opcode = Root.getOpcode();
1637   Value *LHS = Root.getOperand(0);
1638
1639   // Quick check, see if the immediate LHS matches...
1640   if (F.shouldApply(LHS))
1641     return F.apply(Root);
1642
1643   // Otherwise, if the LHS is not of the same opcode as the root, return.
1644   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1645   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1646     // Should we apply this transform to the RHS?
1647     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1648
1649     // If not to the RHS, check to see if we should apply to the LHS...
1650     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1651       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1652       ShouldApply = true;
1653     }
1654
1655     // If the functor wants to apply the optimization to the RHS of LHSI,
1656     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1657     if (ShouldApply) {
1658       BasicBlock *BB = Root.getParent();
1659
1660       // Now all of the instructions are in the current basic block, go ahead
1661       // and perform the reassociation.
1662       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1663
1664       // First move the selected RHS to the LHS of the root...
1665       Root.setOperand(0, LHSI->getOperand(1));
1666
1667       // Make what used to be the LHS of the root be the user of the root...
1668       Value *ExtraOperand = TmpLHSI->getOperand(1);
1669       if (&Root == TmpLHSI) {
1670         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1671         return 0;
1672       }
1673       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1674       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1675       BasicBlock::iterator ARI = &Root; ++ARI;
1676       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1677       ARI = Root;
1678
1679       // Now propagate the ExtraOperand down the chain of instructions until we
1680       // get to LHSI.
1681       while (TmpLHSI != LHSI) {
1682         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1683         // Move the instruction to immediately before the chain we are
1684         // constructing to avoid breaking dominance properties.
1685         NextLHSI->moveBefore(ARI);
1686         ARI = NextLHSI;
1687
1688         Value *NextOp = NextLHSI->getOperand(1);
1689         NextLHSI->setOperand(1, ExtraOperand);
1690         TmpLHSI = NextLHSI;
1691         ExtraOperand = NextOp;
1692       }
1693
1694       // Now that the instructions are reassociated, have the functor perform
1695       // the transformation...
1696       return F.apply(Root);
1697     }
1698
1699     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1700   }
1701   return 0;
1702 }
1703
1704 namespace {
1705
1706 // AddRHS - Implements: X + X --> X << 1
1707 struct AddRHS {
1708   Value *RHS;
1709   AddRHS(Value *rhs) : RHS(rhs) {}
1710   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1711   Instruction *apply(BinaryOperator &Add) const {
1712     return BinaryOperator::CreateShl(Add.getOperand(0),
1713                                      ConstantInt::get(Add.getType(), 1));
1714   }
1715 };
1716
1717 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1718 //                 iff C1&C2 == 0
1719 struct AddMaskingAnd {
1720   Constant *C2;
1721   AddMaskingAnd(Constant *c) : C2(c) {}
1722   bool shouldApply(Value *LHS) const {
1723     ConstantInt *C1;
1724     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1725            ConstantExpr::getAnd(C1, C2)->isNullValue();
1726   }
1727   Instruction *apply(BinaryOperator &Add) const {
1728     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1729   }
1730 };
1731
1732 }
1733
1734 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1735                                              InstCombiner *IC) {
1736   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1737     if (Constant *SOC = dyn_cast<Constant>(SO))
1738       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1739
1740     return IC->InsertNewInstBefore(CastInst::Create(
1741           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1742   }
1743
1744   // Figure out if the constant is the left or the right argument.
1745   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1746   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1747
1748   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1749     if (ConstIsRHS)
1750       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1751     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1752   }
1753
1754   Value *Op0 = SO, *Op1 = ConstOperand;
1755   if (!ConstIsRHS)
1756     std::swap(Op0, Op1);
1757   Instruction *New;
1758   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1759     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1760   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1761     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1762                           SO->getName()+".cmp");
1763   else {
1764     assert(0 && "Unknown binary instruction type!");
1765     abort();
1766   }
1767   return IC->InsertNewInstBefore(New, I);
1768 }
1769
1770 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1771 // constant as the other operand, try to fold the binary operator into the
1772 // select arguments.  This also works for Cast instructions, which obviously do
1773 // not have a second operand.
1774 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1775                                      InstCombiner *IC) {
1776   // Don't modify shared select instructions
1777   if (!SI->hasOneUse()) return 0;
1778   Value *TV = SI->getOperand(1);
1779   Value *FV = SI->getOperand(2);
1780
1781   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1782     // Bool selects with constant operands can be folded to logical ops.
1783     if (SI->getType() == Type::Int1Ty) return 0;
1784
1785     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1786     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1787
1788     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1789                               SelectFalseVal);
1790   }
1791   return 0;
1792 }
1793
1794
1795 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1796 /// node as operand #0, see if we can fold the instruction into the PHI (which
1797 /// is only possible if all operands to the PHI are constants).
1798 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1799   PHINode *PN = cast<PHINode>(I.getOperand(0));
1800   unsigned NumPHIValues = PN->getNumIncomingValues();
1801   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1802
1803   // Check to see if all of the operands of the PHI are constants.  If there is
1804   // one non-constant value, remember the BB it is.  If there is more than one
1805   // or if *it* is a PHI, bail out.
1806   BasicBlock *NonConstBB = 0;
1807   for (unsigned i = 0; i != NumPHIValues; ++i)
1808     if (!isa<Constant>(PN->getIncomingValue(i))) {
1809       if (NonConstBB) return 0;  // More than one non-const value.
1810       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1811       NonConstBB = PN->getIncomingBlock(i);
1812       
1813       // If the incoming non-constant value is in I's block, we have an infinite
1814       // loop.
1815       if (NonConstBB == I.getParent())
1816         return 0;
1817     }
1818   
1819   // If there is exactly one non-constant value, we can insert a copy of the
1820   // operation in that block.  However, if this is a critical edge, we would be
1821   // inserting the computation one some other paths (e.g. inside a loop).  Only
1822   // do this if the pred block is unconditionally branching into the phi block.
1823   if (NonConstBB) {
1824     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1825     if (!BI || !BI->isUnconditional()) return 0;
1826   }
1827
1828   // Okay, we can do the transformation: create the new PHI node.
1829   PHINode *NewPN = PHINode::Create(I.getType(), "");
1830   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1831   InsertNewInstBefore(NewPN, *PN);
1832   NewPN->takeName(PN);
1833
1834   // Next, add all of the operands to the PHI.
1835   if (I.getNumOperands() == 2) {
1836     Constant *C = cast<Constant>(I.getOperand(1));
1837     for (unsigned i = 0; i != NumPHIValues; ++i) {
1838       Value *InV = 0;
1839       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1840         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1841           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1842         else
1843           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1844       } else {
1845         assert(PN->getIncomingBlock(i) == NonConstBB);
1846         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1847           InV = BinaryOperator::Create(BO->getOpcode(),
1848                                        PN->getIncomingValue(i), C, "phitmp",
1849                                        NonConstBB->getTerminator());
1850         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1851           InV = CmpInst::Create(CI->getOpcode(), 
1852                                 CI->getPredicate(),
1853                                 PN->getIncomingValue(i), C, "phitmp",
1854                                 NonConstBB->getTerminator());
1855         else
1856           assert(0 && "Unknown binop!");
1857         
1858         AddToWorkList(cast<Instruction>(InV));
1859       }
1860       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1861     }
1862   } else { 
1863     CastInst *CI = cast<CastInst>(&I);
1864     const Type *RetTy = CI->getType();
1865     for (unsigned i = 0; i != NumPHIValues; ++i) {
1866       Value *InV;
1867       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1868         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1869       } else {
1870         assert(PN->getIncomingBlock(i) == NonConstBB);
1871         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1872                                I.getType(), "phitmp", 
1873                                NonConstBB->getTerminator());
1874         AddToWorkList(cast<Instruction>(InV));
1875       }
1876       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1877     }
1878   }
1879   return ReplaceInstUsesWith(I, NewPN);
1880 }
1881
1882
1883 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1884 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1885 /// This basically requires proving that the add in the original type would not
1886 /// overflow to change the sign bit or have a carry out.
1887 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1888   // There are different heuristics we can use for this.  Here are some simple
1889   // ones.
1890   
1891   // Add has the property that adding any two 2's complement numbers can only 
1892   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1893   // have at least two sign bits, we know that the addition of the two values will
1894   // sign extend fine.
1895   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1896     return true;
1897   
1898   
1899   // If one of the operands only has one non-zero bit, and if the other operand
1900   // has a known-zero bit in a more significant place than it (not including the
1901   // sign bit) the ripple may go up to and fill the zero, but won't change the
1902   // sign.  For example, (X & ~4) + 1.
1903   
1904   // TODO: Implement.
1905   
1906   return false;
1907 }
1908
1909
1910 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1911   bool Changed = SimplifyCommutative(I);
1912   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1913
1914   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1915     // X + undef -> undef
1916     if (isa<UndefValue>(RHS))
1917       return ReplaceInstUsesWith(I, RHS);
1918
1919     // X + 0 --> X
1920     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1921       if (RHSC->isNullValue())
1922         return ReplaceInstUsesWith(I, LHS);
1923     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1924       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1925                               (I.getType())->getValueAPF()))
1926         return ReplaceInstUsesWith(I, LHS);
1927     }
1928
1929     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1930       // X + (signbit) --> X ^ signbit
1931       const APInt& Val = CI->getValue();
1932       uint32_t BitWidth = Val.getBitWidth();
1933       if (Val == APInt::getSignBit(BitWidth))
1934         return BinaryOperator::CreateXor(LHS, RHS);
1935       
1936       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1937       // (X & 254)+1 -> (X&254)|1
1938       if (!isa<VectorType>(I.getType())) {
1939         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1940         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1941                                  KnownZero, KnownOne))
1942           return &I;
1943       }
1944     }
1945
1946     if (isa<PHINode>(LHS))
1947       if (Instruction *NV = FoldOpIntoPhi(I))
1948         return NV;
1949     
1950     ConstantInt *XorRHS = 0;
1951     Value *XorLHS = 0;
1952     if (isa<ConstantInt>(RHSC) &&
1953         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1954       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1955       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1956       
1957       uint32_t Size = TySizeBits / 2;
1958       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1959       APInt CFF80Val(-C0080Val);
1960       do {
1961         if (TySizeBits > Size) {
1962           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1963           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1964           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1965               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1966             // This is a sign extend if the top bits are known zero.
1967             if (!MaskedValueIsZero(XorLHS, 
1968                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1969               Size = 0;  // Not a sign ext, but can't be any others either.
1970             break;
1971           }
1972         }
1973         Size >>= 1;
1974         C0080Val = APIntOps::lshr(C0080Val, Size);
1975         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1976       } while (Size >= 1);
1977       
1978       // FIXME: This shouldn't be necessary. When the backends can handle types
1979       // with funny bit widths then this switch statement should be removed. It
1980       // is just here to get the size of the "middle" type back up to something
1981       // that the back ends can handle.
1982       const Type *MiddleType = 0;
1983       switch (Size) {
1984         default: break;
1985         case 32: MiddleType = Type::Int32Ty; break;
1986         case 16: MiddleType = Type::Int16Ty; break;
1987         case  8: MiddleType = Type::Int8Ty; break;
1988       }
1989       if (MiddleType) {
1990         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1991         InsertNewInstBefore(NewTrunc, I);
1992         return new SExtInst(NewTrunc, I.getType(), I.getName());
1993       }
1994     }
1995   }
1996
1997   if (I.getType() == Type::Int1Ty)
1998     return BinaryOperator::CreateXor(LHS, RHS);
1999
2000   // X + X --> X << 1
2001   if (I.getType()->isInteger()) {
2002     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2003
2004     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2005       if (RHSI->getOpcode() == Instruction::Sub)
2006         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2007           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2008     }
2009     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2010       if (LHSI->getOpcode() == Instruction::Sub)
2011         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2012           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2013     }
2014   }
2015
2016   // -A + B  -->  B - A
2017   // -A + -B  -->  -(A + B)
2018   if (Value *LHSV = dyn_castNegVal(LHS)) {
2019     if (LHS->getType()->isIntOrIntVector()) {
2020       if (Value *RHSV = dyn_castNegVal(RHS)) {
2021         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2022         InsertNewInstBefore(NewAdd, I);
2023         return BinaryOperator::CreateNeg(NewAdd);
2024       }
2025     }
2026     
2027     return BinaryOperator::CreateSub(RHS, LHSV);
2028   }
2029
2030   // A + -B  -->  A - B
2031   if (!isa<Constant>(RHS))
2032     if (Value *V = dyn_castNegVal(RHS))
2033       return BinaryOperator::CreateSub(LHS, V);
2034
2035
2036   ConstantInt *C2;
2037   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2038     if (X == RHS)   // X*C + X --> X * (C+1)
2039       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2040
2041     // X*C1 + X*C2 --> X * (C1+C2)
2042     ConstantInt *C1;
2043     if (X == dyn_castFoldableMul(RHS, C1))
2044       return BinaryOperator::CreateMul(X, Add(C1, C2));
2045   }
2046
2047   // X + X*C --> X * (C+1)
2048   if (dyn_castFoldableMul(RHS, C2) == LHS)
2049     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2050
2051   // X + ~X --> -1   since   ~X = -X-1
2052   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2053     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2054   
2055
2056   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2057   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2058     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2059       return R;
2060   
2061   // A+B --> A|B iff A and B have no bits set in common.
2062   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2063     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2064     APInt LHSKnownOne(IT->getBitWidth(), 0);
2065     APInt LHSKnownZero(IT->getBitWidth(), 0);
2066     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2067     if (LHSKnownZero != 0) {
2068       APInt RHSKnownOne(IT->getBitWidth(), 0);
2069       APInt RHSKnownZero(IT->getBitWidth(), 0);
2070       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2071       
2072       // No bits in common -> bitwise or.
2073       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2074         return BinaryOperator::CreateOr(LHS, RHS);
2075     }
2076   }
2077
2078   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2079   if (I.getType()->isIntOrIntVector()) {
2080     Value *W, *X, *Y, *Z;
2081     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2082         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2083       if (W != Y) {
2084         if (W == Z) {
2085           std::swap(Y, Z);
2086         } else if (Y == X) {
2087           std::swap(W, X);
2088         } else if (X == Z) {
2089           std::swap(Y, Z);
2090           std::swap(W, X);
2091         }
2092       }
2093
2094       if (W == Y) {
2095         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2096                                                             LHS->getName()), I);
2097         return BinaryOperator::CreateMul(W, NewAdd);
2098       }
2099     }
2100   }
2101
2102   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2103     Value *X = 0;
2104     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2105       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2106
2107     // (X & FF00) + xx00  -> (X+xx00) & FF00
2108     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2109       Constant *Anded = And(CRHS, C2);
2110       if (Anded == CRHS) {
2111         // See if all bits from the first bit set in the Add RHS up are included
2112         // in the mask.  First, get the rightmost bit.
2113         const APInt& AddRHSV = CRHS->getValue();
2114
2115         // Form a mask of all bits from the lowest bit added through the top.
2116         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2117
2118         // See if the and mask includes all of these bits.
2119         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2120
2121         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2122           // Okay, the xform is safe.  Insert the new add pronto.
2123           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2124                                                             LHS->getName()), I);
2125           return BinaryOperator::CreateAnd(NewAdd, C2);
2126         }
2127       }
2128     }
2129
2130     // Try to fold constant add into select arguments.
2131     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2132       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2133         return R;
2134   }
2135
2136   // add (cast *A to intptrtype) B -> 
2137   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2138   {
2139     CastInst *CI = dyn_cast<CastInst>(LHS);
2140     Value *Other = RHS;
2141     if (!CI) {
2142       CI = dyn_cast<CastInst>(RHS);
2143       Other = LHS;
2144     }
2145     if (CI && CI->getType()->isSized() && 
2146         (CI->getType()->getPrimitiveSizeInBits() == 
2147          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2148         && isa<PointerType>(CI->getOperand(0)->getType())) {
2149       unsigned AS =
2150         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2151       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2152                                       PointerType::get(Type::Int8Ty, AS), I);
2153       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2154       return new PtrToIntInst(I2, CI->getType());
2155     }
2156   }
2157   
2158   // add (select X 0 (sub n A)) A  -->  select X A n
2159   {
2160     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2161     Value *Other = RHS;
2162     if (!SI) {
2163       SI = dyn_cast<SelectInst>(RHS);
2164       Other = LHS;
2165     }
2166     if (SI && SI->hasOneUse()) {
2167       Value *TV = SI->getTrueValue();
2168       Value *FV = SI->getFalseValue();
2169       Value *A, *N;
2170
2171       // Can we fold the add into the argument of the select?
2172       // We check both true and false select arguments for a matching subtract.
2173       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2174           A == Other)  // Fold the add into the true select value.
2175         return SelectInst::Create(SI->getCondition(), N, A);
2176       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2177           A == Other)  // Fold the add into the false select value.
2178         return SelectInst::Create(SI->getCondition(), A, N);
2179     }
2180   }
2181   
2182   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2183   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2184     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2185       return ReplaceInstUsesWith(I, LHS);
2186
2187   // Check for (add (sext x), y), see if we can merge this into an
2188   // integer add followed by a sext.
2189   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2190     // (add (sext x), cst) --> (sext (add x, cst'))
2191     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2192       Constant *CI = 
2193         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2194       if (LHSConv->hasOneUse() &&
2195           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2196           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2197         // Insert the new, smaller add.
2198         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2199                                                         CI, "addconv");
2200         InsertNewInstBefore(NewAdd, I);
2201         return new SExtInst(NewAdd, I.getType());
2202       }
2203     }
2204     
2205     // (add (sext x), (sext y)) --> (sext (add int x, y))
2206     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2207       // Only do this if x/y have the same type, if at last one of them has a
2208       // single use (so we don't increase the number of sexts), and if the
2209       // integer add will not overflow.
2210       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2211           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2212           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2213                                    RHSConv->getOperand(0))) {
2214         // Insert the new integer add.
2215         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2216                                                         RHSConv->getOperand(0),
2217                                                         "addconv");
2218         InsertNewInstBefore(NewAdd, I);
2219         return new SExtInst(NewAdd, I.getType());
2220       }
2221     }
2222   }
2223   
2224   // Check for (add double (sitofp x), y), see if we can merge this into an
2225   // integer add followed by a promotion.
2226   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2227     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2228     // ... if the constant fits in the integer value.  This is useful for things
2229     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2230     // requires a constant pool load, and generally allows the add to be better
2231     // instcombined.
2232     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2233       Constant *CI = 
2234       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2235       if (LHSConv->hasOneUse() &&
2236           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2237           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2238         // Insert the new integer add.
2239         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2240                                                         CI, "addconv");
2241         InsertNewInstBefore(NewAdd, I);
2242         return new SIToFPInst(NewAdd, I.getType());
2243       }
2244     }
2245     
2246     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2247     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2248       // Only do this if x/y have the same type, if at last one of them has a
2249       // single use (so we don't increase the number of int->fp conversions),
2250       // and if the integer add will not overflow.
2251       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2252           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2253           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2254                                    RHSConv->getOperand(0))) {
2255         // Insert the new integer add.
2256         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2257                                                         RHSConv->getOperand(0),
2258                                                         "addconv");
2259         InsertNewInstBefore(NewAdd, I);
2260         return new SIToFPInst(NewAdd, I.getType());
2261       }
2262     }
2263   }
2264   
2265   return Changed ? &I : 0;
2266 }
2267
2268 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2269   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2270
2271   if (Op0 == Op1)         // sub X, X  -> 0
2272     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2273
2274   // If this is a 'B = x-(-A)', change to B = x+A...
2275   if (Value *V = dyn_castNegVal(Op1))
2276     return BinaryOperator::CreateAdd(Op0, V);
2277
2278   if (isa<UndefValue>(Op0))
2279     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2280   if (isa<UndefValue>(Op1))
2281     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2282
2283   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2284     // Replace (-1 - A) with (~A)...
2285     if (C->isAllOnesValue())
2286       return BinaryOperator::CreateNot(Op1);
2287
2288     // C - ~X == X + (1+C)
2289     Value *X = 0;
2290     if (match(Op1, m_Not(m_Value(X))))
2291       return BinaryOperator::CreateAdd(X, AddOne(C));
2292
2293     // -(X >>u 31) -> (X >>s 31)
2294     // -(X >>s 31) -> (X >>u 31)
2295     if (C->isZero()) {
2296       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2297         if (SI->getOpcode() == Instruction::LShr) {
2298           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2299             // Check to see if we are shifting out everything but the sign bit.
2300             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2301                 SI->getType()->getPrimitiveSizeInBits()-1) {
2302               // Ok, the transformation is safe.  Insert AShr.
2303               return BinaryOperator::Create(Instruction::AShr, 
2304                                           SI->getOperand(0), CU, SI->getName());
2305             }
2306           }
2307         }
2308         else if (SI->getOpcode() == Instruction::AShr) {
2309           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2310             // Check to see if we are shifting out everything but the sign bit.
2311             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2312                 SI->getType()->getPrimitiveSizeInBits()-1) {
2313               // Ok, the transformation is safe.  Insert LShr. 
2314               return BinaryOperator::CreateLShr(
2315                                           SI->getOperand(0), CU, SI->getName());
2316             }
2317           }
2318         }
2319       }
2320     }
2321
2322     // Try to fold constant sub into select arguments.
2323     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2324       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2325         return R;
2326
2327     if (isa<PHINode>(Op0))
2328       if (Instruction *NV = FoldOpIntoPhi(I))
2329         return NV;
2330   }
2331
2332   if (I.getType() == Type::Int1Ty)
2333     return BinaryOperator::CreateXor(Op0, Op1);
2334
2335   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2336     if (Op1I->getOpcode() == Instruction::Add &&
2337         !Op0->getType()->isFPOrFPVector()) {
2338       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2339         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2340       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2341         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2342       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2343         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2344           // C1-(X+C2) --> (C1-C2)-X
2345           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2346                                            Op1I->getOperand(0));
2347       }
2348     }
2349
2350     if (Op1I->hasOneUse()) {
2351       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2352       // is not used by anyone else...
2353       //
2354       if (Op1I->getOpcode() == Instruction::Sub &&
2355           !Op1I->getType()->isFPOrFPVector()) {
2356         // Swap the two operands of the subexpr...
2357         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2358         Op1I->setOperand(0, IIOp1);
2359         Op1I->setOperand(1, IIOp0);
2360
2361         // Create the new top level add instruction...
2362         return BinaryOperator::CreateAdd(Op0, Op1);
2363       }
2364
2365       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2366       //
2367       if (Op1I->getOpcode() == Instruction::And &&
2368           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2369         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2370
2371         Value *NewNot =
2372           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2373         return BinaryOperator::CreateAnd(Op0, NewNot);
2374       }
2375
2376       // 0 - (X sdiv C)  -> (X sdiv -C)
2377       if (Op1I->getOpcode() == Instruction::SDiv)
2378         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2379           if (CSI->isZero())
2380             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2381               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2382                                                ConstantExpr::getNeg(DivRHS));
2383
2384       // X - X*C --> X * (1-C)
2385       ConstantInt *C2 = 0;
2386       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2387         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2388         return BinaryOperator::CreateMul(Op0, CP1);
2389       }
2390
2391       // X - ((X / Y) * Y) --> X % Y
2392       if (Op1I->getOpcode() == Instruction::Mul)
2393         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2394           if (Op0 == I->getOperand(0) &&
2395               Op1I->getOperand(1) == I->getOperand(1)) {
2396             if (I->getOpcode() == Instruction::SDiv)
2397               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2398             if (I->getOpcode() == Instruction::UDiv)
2399               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2400           }
2401     }
2402   }
2403
2404   if (!Op0->getType()->isFPOrFPVector())
2405     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2406       if (Op0I->getOpcode() == Instruction::Add) {
2407         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2408           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2409         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2410           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2411       } else if (Op0I->getOpcode() == Instruction::Sub) {
2412         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2413           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2414       }
2415     }
2416
2417   ConstantInt *C1;
2418   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2419     if (X == Op1)  // X*C - X --> X * (C-1)
2420       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2421
2422     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2423     if (X == dyn_castFoldableMul(Op1, C2))
2424       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2425   }
2426   return 0;
2427 }
2428
2429 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2430 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2431 /// TrueIfSigned if the result of the comparison is true when the input value is
2432 /// signed.
2433 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2434                            bool &TrueIfSigned) {
2435   switch (pred) {
2436   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2437     TrueIfSigned = true;
2438     return RHS->isZero();
2439   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2440     TrueIfSigned = true;
2441     return RHS->isAllOnesValue();
2442   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2443     TrueIfSigned = false;
2444     return RHS->isAllOnesValue();
2445   case ICmpInst::ICMP_UGT:
2446     // True if LHS u> RHS and RHS == high-bit-mask - 1
2447     TrueIfSigned = true;
2448     return RHS->getValue() ==
2449       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2450   case ICmpInst::ICMP_UGE: 
2451     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2452     TrueIfSigned = true;
2453     return RHS->getValue().isSignBit();
2454   default:
2455     return false;
2456   }
2457 }
2458
2459 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2460   bool Changed = SimplifyCommutative(I);
2461   Value *Op0 = I.getOperand(0);
2462
2463   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2464     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2465
2466   // Simplify mul instructions with a constant RHS...
2467   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2468     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2469
2470       // ((X << C1)*C2) == (X * (C2 << C1))
2471       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2472         if (SI->getOpcode() == Instruction::Shl)
2473           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2474             return BinaryOperator::CreateMul(SI->getOperand(0),
2475                                              ConstantExpr::getShl(CI, ShOp));
2476
2477       if (CI->isZero())
2478         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2479       if (CI->equalsInt(1))                  // X * 1  == X
2480         return ReplaceInstUsesWith(I, Op0);
2481       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2482         return BinaryOperator::CreateNeg(Op0, I.getName());
2483
2484       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2485       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2486         return BinaryOperator::CreateShl(Op0,
2487                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2488       }
2489     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2490       if (Op1F->isNullValue())
2491         return ReplaceInstUsesWith(I, Op1);
2492
2493       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2494       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2495       // We need a better interface for long double here.
2496       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2497         if (Op1F->isExactlyValue(1.0))
2498           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2499     }
2500     
2501     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2502       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2503           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2504         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2505         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2506                                                      Op1, "tmp");
2507         InsertNewInstBefore(Add, I);
2508         Value *C1C2 = ConstantExpr::getMul(Op1, 
2509                                            cast<Constant>(Op0I->getOperand(1)));
2510         return BinaryOperator::CreateAdd(Add, C1C2);
2511         
2512       }
2513
2514     // Try to fold constant mul into select arguments.
2515     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2516       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2517         return R;
2518
2519     if (isa<PHINode>(Op0))
2520       if (Instruction *NV = FoldOpIntoPhi(I))
2521         return NV;
2522   }
2523
2524   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2525     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2526       return BinaryOperator::CreateMul(Op0v, Op1v);
2527
2528   if (I.getType() == Type::Int1Ty)
2529     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2530
2531   // If one of the operands of the multiply is a cast from a boolean value, then
2532   // we know the bool is either zero or one, so this is a 'masking' multiply.
2533   // See if we can simplify things based on how the boolean was originally
2534   // formed.
2535   CastInst *BoolCast = 0;
2536   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2537     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2538       BoolCast = CI;
2539   if (!BoolCast)
2540     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2541       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2542         BoolCast = CI;
2543   if (BoolCast) {
2544     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2545       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2546       const Type *SCOpTy = SCIOp0->getType();
2547       bool TIS = false;
2548       
2549       // If the icmp is true iff the sign bit of X is set, then convert this
2550       // multiply into a shift/and combination.
2551       if (isa<ConstantInt>(SCIOp1) &&
2552           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2553           TIS) {
2554         // Shift the X value right to turn it into "all signbits".
2555         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2556                                           SCOpTy->getPrimitiveSizeInBits()-1);
2557         Value *V =
2558           InsertNewInstBefore(
2559             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2560                                             BoolCast->getOperand(0)->getName()+
2561                                             ".mask"), I);
2562
2563         // If the multiply type is not the same as the source type, sign extend
2564         // or truncate to the multiply type.
2565         if (I.getType() != V->getType()) {
2566           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2567           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2568           Instruction::CastOps opcode = 
2569             (SrcBits == DstBits ? Instruction::BitCast : 
2570              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2571           V = InsertCastBefore(opcode, V, I.getType(), I);
2572         }
2573
2574         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2575         return BinaryOperator::CreateAnd(V, OtherOp);
2576       }
2577     }
2578   }
2579
2580   return Changed ? &I : 0;
2581 }
2582
2583 /// This function implements the transforms on div instructions that work
2584 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2585 /// used by the visitors to those instructions.
2586 /// @brief Transforms common to all three div instructions
2587 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2588   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2589
2590   // undef / X -> 0        for integer.
2591   // undef / X -> undef    for FP (the undef could be a snan).
2592   if (isa<UndefValue>(Op0)) {
2593     if (Op0->getType()->isFPOrFPVector())
2594       return ReplaceInstUsesWith(I, Op0);
2595     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2596   }
2597
2598   // X / undef -> undef
2599   if (isa<UndefValue>(Op1))
2600     return ReplaceInstUsesWith(I, Op1);
2601
2602   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2603   // This does not apply for fdiv.
2604   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2605     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2606     // the same basic block, then we replace the select with Y, and the
2607     // condition of the select with false (if the cond value is in the same BB).
2608     // If the select has uses other than the div, this allows them to be
2609     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2610     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2611       if (ST->isNullValue()) {
2612         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2613         if (CondI && CondI->getParent() == I.getParent())
2614           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2615         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2616           I.setOperand(1, SI->getOperand(2));
2617         else
2618           UpdateValueUsesWith(SI, SI->getOperand(2));
2619         return &I;
2620       }
2621
2622     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2623     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2624       if (ST->isNullValue()) {
2625         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2626         if (CondI && CondI->getParent() == I.getParent())
2627           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2628         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2629           I.setOperand(1, SI->getOperand(1));
2630         else
2631           UpdateValueUsesWith(SI, SI->getOperand(1));
2632         return &I;
2633       }
2634   }
2635
2636   return 0;
2637 }
2638
2639 /// This function implements the transforms common to both integer division
2640 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2641 /// division instructions.
2642 /// @brief Common integer divide transforms
2643 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2644   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2645
2646   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2647   if (Op0 == Op1) {
2648     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2649       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2650       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2651       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2652     }
2653
2654     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2655     return ReplaceInstUsesWith(I, CI);
2656   }
2657   
2658   if (Instruction *Common = commonDivTransforms(I))
2659     return Common;
2660
2661   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2662     // div X, 1 == X
2663     if (RHS->equalsInt(1))
2664       return ReplaceInstUsesWith(I, Op0);
2665
2666     // (X / C1) / C2  -> X / (C1*C2)
2667     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2668       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2669         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2670           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2671             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2672           else 
2673             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2674                                           Multiply(RHS, LHSRHS));
2675         }
2676
2677     if (!RHS->isZero()) { // avoid X udiv 0
2678       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2679         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2680           return R;
2681       if (isa<PHINode>(Op0))
2682         if (Instruction *NV = FoldOpIntoPhi(I))
2683           return NV;
2684     }
2685   }
2686
2687   // 0 / X == 0, we don't need to preserve faults!
2688   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2689     if (LHS->equalsInt(0))
2690       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2691
2692   // It can't be division by zero, hence it must be division by one.
2693   if (I.getType() == Type::Int1Ty)
2694     return ReplaceInstUsesWith(I, Op0);
2695
2696   return 0;
2697 }
2698
2699 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2700   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2701
2702   // Handle the integer div common cases
2703   if (Instruction *Common = commonIDivTransforms(I))
2704     return Common;
2705
2706   // X udiv C^2 -> X >> C
2707   // Check to see if this is an unsigned division with an exact power of 2,
2708   // if so, convert to a right shift.
2709   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2710     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2711       return BinaryOperator::CreateLShr(Op0, 
2712                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2713   }
2714
2715   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2716   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2717     if (RHSI->getOpcode() == Instruction::Shl &&
2718         isa<ConstantInt>(RHSI->getOperand(0))) {
2719       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2720       if (C1.isPowerOf2()) {
2721         Value *N = RHSI->getOperand(1);
2722         const Type *NTy = N->getType();
2723         if (uint32_t C2 = C1.logBase2()) {
2724           Constant *C2V = ConstantInt::get(NTy, C2);
2725           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2726         }
2727         return BinaryOperator::CreateLShr(Op0, N);
2728       }
2729     }
2730   }
2731   
2732   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2733   // where C1&C2 are powers of two.
2734   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2735     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2736       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2737         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2738         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2739           // Compute the shift amounts
2740           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2741           // Construct the "on true" case of the select
2742           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2743           Instruction *TSI = BinaryOperator::CreateLShr(
2744                                                  Op0, TC, SI->getName()+".t");
2745           TSI = InsertNewInstBefore(TSI, I);
2746   
2747           // Construct the "on false" case of the select
2748           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2749           Instruction *FSI = BinaryOperator::CreateLShr(
2750                                                  Op0, FC, SI->getName()+".f");
2751           FSI = InsertNewInstBefore(FSI, I);
2752
2753           // construct the select instruction and return it.
2754           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2755         }
2756       }
2757   return 0;
2758 }
2759
2760 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2761   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2762
2763   // Handle the integer div common cases
2764   if (Instruction *Common = commonIDivTransforms(I))
2765     return Common;
2766
2767   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2768     // sdiv X, -1 == -X
2769     if (RHS->isAllOnesValue())
2770       return BinaryOperator::CreateNeg(Op0);
2771
2772     // -X/C -> X/-C
2773     if (Value *LHSNeg = dyn_castNegVal(Op0))
2774       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2775   }
2776
2777   // If the sign bits of both operands are zero (i.e. we can prove they are
2778   // unsigned inputs), turn this into a udiv.
2779   if (I.getType()->isInteger()) {
2780     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2781     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2782       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2783       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2784     }
2785   }      
2786   
2787   return 0;
2788 }
2789
2790 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2791   return commonDivTransforms(I);
2792 }
2793
2794 /// This function implements the transforms on rem instructions that work
2795 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2796 /// is used by the visitors to those instructions.
2797 /// @brief Transforms common to all three rem instructions
2798 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2799   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2800
2801   // 0 % X == 0 for integer, we don't need to preserve faults!
2802   if (Constant *LHS = dyn_cast<Constant>(Op0))
2803     if (LHS->isNullValue())
2804       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2805
2806   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2807     if (I.getType()->isFPOrFPVector())
2808       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2809     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2810   }
2811   if (isa<UndefValue>(Op1))
2812     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2813
2814   // Handle cases involving: rem X, (select Cond, Y, Z)
2815   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2816     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2817     // the same basic block, then we replace the select with Y, and the
2818     // condition of the select with false (if the cond value is in the same
2819     // BB).  If the select has uses other than the div, this allows them to be
2820     // simplified also.
2821     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2822       if (ST->isNullValue()) {
2823         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2824         if (CondI && CondI->getParent() == I.getParent())
2825           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2826         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2827           I.setOperand(1, SI->getOperand(2));
2828         else
2829           UpdateValueUsesWith(SI, SI->getOperand(2));
2830         return &I;
2831       }
2832     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2833     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2834       if (ST->isNullValue()) {
2835         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2836         if (CondI && CondI->getParent() == I.getParent())
2837           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2838         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2839           I.setOperand(1, SI->getOperand(1));
2840         else
2841           UpdateValueUsesWith(SI, SI->getOperand(1));
2842         return &I;
2843       }
2844   }
2845
2846   return 0;
2847 }
2848
2849 /// This function implements the transforms common to both integer remainder
2850 /// instructions (urem and srem). It is called by the visitors to those integer
2851 /// remainder instructions.
2852 /// @brief Common integer remainder transforms
2853 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2854   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2855
2856   if (Instruction *common = commonRemTransforms(I))
2857     return common;
2858
2859   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2860     // X % 0 == undef, we don't need to preserve faults!
2861     if (RHS->equalsInt(0))
2862       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2863     
2864     if (RHS->equalsInt(1))  // X % 1 == 0
2865       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2866
2867     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2868       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2869         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2870           return R;
2871       } else if (isa<PHINode>(Op0I)) {
2872         if (Instruction *NV = FoldOpIntoPhi(I))
2873           return NV;
2874       }
2875
2876       // See if we can fold away this rem instruction.
2877       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2878       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2879       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2880                                KnownZero, KnownOne))
2881         return &I;
2882     }
2883   }
2884
2885   return 0;
2886 }
2887
2888 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2889   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2890
2891   if (Instruction *common = commonIRemTransforms(I))
2892     return common;
2893   
2894   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2895     // X urem C^2 -> X and C
2896     // Check to see if this is an unsigned remainder with an exact power of 2,
2897     // if so, convert to a bitwise and.
2898     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2899       if (C->getValue().isPowerOf2())
2900         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2901   }
2902
2903   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2904     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2905     if (RHSI->getOpcode() == Instruction::Shl &&
2906         isa<ConstantInt>(RHSI->getOperand(0))) {
2907       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2908         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2909         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2910                                                                    "tmp"), I);
2911         return BinaryOperator::CreateAnd(Op0, Add);
2912       }
2913     }
2914   }
2915
2916   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2917   // where C1&C2 are powers of two.
2918   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2919     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2920       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2921         // STO == 0 and SFO == 0 handled above.
2922         if ((STO->getValue().isPowerOf2()) && 
2923             (SFO->getValue().isPowerOf2())) {
2924           Value *TrueAnd = InsertNewInstBefore(
2925             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2926           Value *FalseAnd = InsertNewInstBefore(
2927             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2928           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2929         }
2930       }
2931   }
2932   
2933   return 0;
2934 }
2935
2936 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2937   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2938
2939   // Handle the integer rem common cases
2940   if (Instruction *common = commonIRemTransforms(I))
2941     return common;
2942   
2943   if (Value *RHSNeg = dyn_castNegVal(Op1))
2944     if (!isa<ConstantInt>(RHSNeg) || 
2945         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2946       // X % -Y -> X % Y
2947       AddUsesToWorkList(I);
2948       I.setOperand(1, RHSNeg);
2949       return &I;
2950     }
2951  
2952   // If the sign bits of both operands are zero (i.e. we can prove they are
2953   // unsigned inputs), turn this into a urem.
2954   if (I.getType()->isInteger()) {
2955     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2956     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2957       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2958       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2959     }
2960   }
2961
2962   return 0;
2963 }
2964
2965 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2966   return commonRemTransforms(I);
2967 }
2968
2969 // isMaxValueMinusOne - return true if this is Max-1
2970 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2971   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2972   if (!isSigned)
2973     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2974   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2975 }
2976
2977 // isMinValuePlusOne - return true if this is Min+1
2978 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2979   if (!isSigned)
2980     return C->getValue() == 1; // unsigned
2981     
2982   // Calculate 1111111111000000000000
2983   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2984   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2985 }
2986
2987 // isOneBitSet - Return true if there is exactly one bit set in the specified
2988 // constant.
2989 static bool isOneBitSet(const ConstantInt *CI) {
2990   return CI->getValue().isPowerOf2();
2991 }
2992
2993 // isHighOnes - Return true if the constant is of the form 1+0+.
2994 // This is the same as lowones(~X).
2995 static bool isHighOnes(const ConstantInt *CI) {
2996   return (~CI->getValue() + 1).isPowerOf2();
2997 }
2998
2999 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3000 /// are carefully arranged to allow folding of expressions such as:
3001 ///
3002 ///      (A < B) | (A > B) --> (A != B)
3003 ///
3004 /// Note that this is only valid if the first and second predicates have the
3005 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3006 ///
3007 /// Three bits are used to represent the condition, as follows:
3008 ///   0  A > B
3009 ///   1  A == B
3010 ///   2  A < B
3011 ///
3012 /// <=>  Value  Definition
3013 /// 000     0   Always false
3014 /// 001     1   A >  B
3015 /// 010     2   A == B
3016 /// 011     3   A >= B
3017 /// 100     4   A <  B
3018 /// 101     5   A != B
3019 /// 110     6   A <= B
3020 /// 111     7   Always true
3021 ///  
3022 static unsigned getICmpCode(const ICmpInst *ICI) {
3023   switch (ICI->getPredicate()) {
3024     // False -> 0
3025   case ICmpInst::ICMP_UGT: return 1;  // 001
3026   case ICmpInst::ICMP_SGT: return 1;  // 001
3027   case ICmpInst::ICMP_EQ:  return 2;  // 010
3028   case ICmpInst::ICMP_UGE: return 3;  // 011
3029   case ICmpInst::ICMP_SGE: return 3;  // 011
3030   case ICmpInst::ICMP_ULT: return 4;  // 100
3031   case ICmpInst::ICMP_SLT: return 4;  // 100
3032   case ICmpInst::ICMP_NE:  return 5;  // 101
3033   case ICmpInst::ICMP_ULE: return 6;  // 110
3034   case ICmpInst::ICMP_SLE: return 6;  // 110
3035     // True -> 7
3036   default:
3037     assert(0 && "Invalid ICmp predicate!");
3038     return 0;
3039   }
3040 }
3041
3042 /// getICmpValue - This is the complement of getICmpCode, which turns an
3043 /// opcode and two operands into either a constant true or false, or a brand 
3044 /// new ICmp instruction. The sign is passed in to determine which kind
3045 /// of predicate to use in new icmp instructions.
3046 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3047   switch (code) {
3048   default: assert(0 && "Illegal ICmp code!");
3049   case  0: return ConstantInt::getFalse();
3050   case  1: 
3051     if (sign)
3052       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3053     else
3054       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3055   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3056   case  3: 
3057     if (sign)
3058       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3059     else
3060       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3061   case  4: 
3062     if (sign)
3063       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3064     else
3065       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3066   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3067   case  6: 
3068     if (sign)
3069       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3070     else
3071       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3072   case  7: return ConstantInt::getTrue();
3073   }
3074 }
3075
3076 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3077   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3078     (ICmpInst::isSignedPredicate(p1) && 
3079      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3080     (ICmpInst::isSignedPredicate(p2) && 
3081      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3082 }
3083
3084 namespace { 
3085 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3086 struct FoldICmpLogical {
3087   InstCombiner &IC;
3088   Value *LHS, *RHS;
3089   ICmpInst::Predicate pred;
3090   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3091     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3092       pred(ICI->getPredicate()) {}
3093   bool shouldApply(Value *V) const {
3094     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3095       if (PredicatesFoldable(pred, ICI->getPredicate()))
3096         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3097                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3098     return false;
3099   }
3100   Instruction *apply(Instruction &Log) const {
3101     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3102     if (ICI->getOperand(0) != LHS) {
3103       assert(ICI->getOperand(1) == LHS);
3104       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3105     }
3106
3107     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3108     unsigned LHSCode = getICmpCode(ICI);
3109     unsigned RHSCode = getICmpCode(RHSICI);
3110     unsigned Code;
3111     switch (Log.getOpcode()) {
3112     case Instruction::And: Code = LHSCode & RHSCode; break;
3113     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3114     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3115     default: assert(0 && "Illegal logical opcode!"); return 0;
3116     }
3117
3118     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3119                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3120       
3121     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3122     if (Instruction *I = dyn_cast<Instruction>(RV))
3123       return I;
3124     // Otherwise, it's a constant boolean value...
3125     return IC.ReplaceInstUsesWith(Log, RV);
3126   }
3127 };
3128 } // end anonymous namespace
3129
3130 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3131 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3132 // guaranteed to be a binary operator.
3133 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3134                                     ConstantInt *OpRHS,
3135                                     ConstantInt *AndRHS,
3136                                     BinaryOperator &TheAnd) {
3137   Value *X = Op->getOperand(0);
3138   Constant *Together = 0;
3139   if (!Op->isShift())
3140     Together = And(AndRHS, OpRHS);
3141
3142   switch (Op->getOpcode()) {
3143   case Instruction::Xor:
3144     if (Op->hasOneUse()) {
3145       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3146       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3147       InsertNewInstBefore(And, TheAnd);
3148       And->takeName(Op);
3149       return BinaryOperator::CreateXor(And, Together);
3150     }
3151     break;
3152   case Instruction::Or:
3153     if (Together == AndRHS) // (X | C) & C --> C
3154       return ReplaceInstUsesWith(TheAnd, AndRHS);
3155
3156     if (Op->hasOneUse() && Together != OpRHS) {
3157       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3158       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3159       InsertNewInstBefore(Or, TheAnd);
3160       Or->takeName(Op);
3161       return BinaryOperator::CreateAnd(Or, AndRHS);
3162     }
3163     break;
3164   case Instruction::Add:
3165     if (Op->hasOneUse()) {
3166       // Adding a one to a single bit bit-field should be turned into an XOR
3167       // of the bit.  First thing to check is to see if this AND is with a
3168       // single bit constant.
3169       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3170
3171       // If there is only one bit set...
3172       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3173         // Ok, at this point, we know that we are masking the result of the
3174         // ADD down to exactly one bit.  If the constant we are adding has
3175         // no bits set below this bit, then we can eliminate the ADD.
3176         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3177
3178         // Check to see if any bits below the one bit set in AndRHSV are set.
3179         if ((AddRHS & (AndRHSV-1)) == 0) {
3180           // If not, the only thing that can effect the output of the AND is
3181           // the bit specified by AndRHSV.  If that bit is set, the effect of
3182           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3183           // no effect.
3184           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3185             TheAnd.setOperand(0, X);
3186             return &TheAnd;
3187           } else {
3188             // Pull the XOR out of the AND.
3189             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3190             InsertNewInstBefore(NewAnd, TheAnd);
3191             NewAnd->takeName(Op);
3192             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3193           }
3194         }
3195       }
3196     }
3197     break;
3198
3199   case Instruction::Shl: {
3200     // We know that the AND will not produce any of the bits shifted in, so if
3201     // the anded constant includes them, clear them now!
3202     //
3203     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3204     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3205     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3206     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3207
3208     if (CI->getValue() == ShlMask) { 
3209     // Masking out bits that the shift already masks
3210       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3211     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3212       TheAnd.setOperand(1, CI);
3213       return &TheAnd;
3214     }
3215     break;
3216   }
3217   case Instruction::LShr:
3218   {
3219     // We know that the AND will not produce any of the bits shifted in, so if
3220     // the anded constant includes them, clear them now!  This only applies to
3221     // unsigned shifts, because a signed shr may bring in set bits!
3222     //
3223     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3224     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3225     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3226     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3227
3228     if (CI->getValue() == ShrMask) {   
3229     // Masking out bits that the shift already masks.
3230       return ReplaceInstUsesWith(TheAnd, Op);
3231     } else if (CI != AndRHS) {
3232       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3233       return &TheAnd;
3234     }
3235     break;
3236   }
3237   case Instruction::AShr:
3238     // Signed shr.
3239     // See if this is shifting in some sign extension, then masking it out
3240     // with an and.
3241     if (Op->hasOneUse()) {
3242       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3243       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3244       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3245       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3246       if (C == AndRHS) {          // Masking out bits shifted in.
3247         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3248         // Make the argument unsigned.
3249         Value *ShVal = Op->getOperand(0);
3250         ShVal = InsertNewInstBefore(
3251             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3252                                    Op->getName()), TheAnd);
3253         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3254       }
3255     }
3256     break;
3257   }
3258   return 0;
3259 }
3260
3261
3262 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3263 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3264 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3265 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3266 /// insert new instructions.
3267 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3268                                            bool isSigned, bool Inside, 
3269                                            Instruction &IB) {
3270   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3271             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3272          "Lo is not <= Hi in range emission code!");
3273     
3274   if (Inside) {
3275     if (Lo == Hi)  // Trivially false.
3276       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3277
3278     // V >= Min && V < Hi --> V < Hi
3279     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3280       ICmpInst::Predicate pred = (isSigned ? 
3281         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3282       return new ICmpInst(pred, V, Hi);
3283     }
3284
3285     // Emit V-Lo <u Hi-Lo
3286     Constant *NegLo = ConstantExpr::getNeg(Lo);
3287     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3288     InsertNewInstBefore(Add, IB);
3289     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3290     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3291   }
3292
3293   if (Lo == Hi)  // Trivially true.
3294     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3295
3296   // V < Min || V >= Hi -> V > Hi-1
3297   Hi = SubOne(cast<ConstantInt>(Hi));
3298   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3299     ICmpInst::Predicate pred = (isSigned ? 
3300         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3301     return new ICmpInst(pred, V, Hi);
3302   }
3303
3304   // Emit V-Lo >u Hi-1-Lo
3305   // Note that Hi has already had one subtracted from it, above.
3306   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3307   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3308   InsertNewInstBefore(Add, IB);
3309   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3310   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3311 }
3312
3313 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3314 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3315 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3316 // not, since all 1s are not contiguous.
3317 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3318   const APInt& V = Val->getValue();
3319   uint32_t BitWidth = Val->getType()->getBitWidth();
3320   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3321
3322   // look for the first zero bit after the run of ones
3323   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3324   // look for the first non-zero bit
3325   ME = V.getActiveBits(); 
3326   return true;
3327 }
3328
3329 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3330 /// where isSub determines whether the operator is a sub.  If we can fold one of
3331 /// the following xforms:
3332 /// 
3333 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3334 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3335 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3336 ///
3337 /// return (A +/- B).
3338 ///
3339 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3340                                         ConstantInt *Mask, bool isSub,
3341                                         Instruction &I) {
3342   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3343   if (!LHSI || LHSI->getNumOperands() != 2 ||
3344       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3345
3346   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3347
3348   switch (LHSI->getOpcode()) {
3349   default: return 0;
3350   case Instruction::And:
3351     if (And(N, Mask) == Mask) {
3352       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3353       if ((Mask->getValue().countLeadingZeros() + 
3354            Mask->getValue().countPopulation()) == 
3355           Mask->getValue().getBitWidth())
3356         break;
3357
3358       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3359       // part, we don't need any explicit masks to take them out of A.  If that
3360       // is all N is, ignore it.
3361       uint32_t MB = 0, ME = 0;
3362       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3363         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3364         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3365         if (MaskedValueIsZero(RHS, Mask))
3366           break;
3367       }
3368     }
3369     return 0;
3370   case Instruction::Or:
3371   case Instruction::Xor:
3372     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3373     if ((Mask->getValue().countLeadingZeros() + 
3374          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3375         && And(N, Mask)->isZero())
3376       break;
3377     return 0;
3378   }
3379   
3380   Instruction *New;
3381   if (isSub)
3382     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3383   else
3384     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3385   return InsertNewInstBefore(New, I);
3386 }
3387
3388 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3389   bool Changed = SimplifyCommutative(I);
3390   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3391
3392   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3393     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3394
3395   // and X, X = X
3396   if (Op0 == Op1)
3397     return ReplaceInstUsesWith(I, Op1);
3398
3399   // See if we can simplify any instructions used by the instruction whose sole 
3400   // purpose is to compute bits we don't care about.
3401   if (!isa<VectorType>(I.getType())) {
3402     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3403     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3404     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3405                              KnownZero, KnownOne))
3406       return &I;
3407   } else {
3408     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3409       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3410         return ReplaceInstUsesWith(I, I.getOperand(0));
3411     } else if (isa<ConstantAggregateZero>(Op1)) {
3412       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3413     }
3414   }
3415   
3416   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3417     const APInt& AndRHSMask = AndRHS->getValue();
3418     APInt NotAndRHS(~AndRHSMask);
3419
3420     // Optimize a variety of ((val OP C1) & C2) combinations...
3421     if (isa<BinaryOperator>(Op0)) {
3422       Instruction *Op0I = cast<Instruction>(Op0);
3423       Value *Op0LHS = Op0I->getOperand(0);
3424       Value *Op0RHS = Op0I->getOperand(1);
3425       switch (Op0I->getOpcode()) {
3426       case Instruction::Xor:
3427       case Instruction::Or:
3428         // If the mask is only needed on one incoming arm, push it up.
3429         if (Op0I->hasOneUse()) {
3430           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3431             // Not masking anything out for the LHS, move to RHS.
3432             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3433                                                    Op0RHS->getName()+".masked");
3434             InsertNewInstBefore(NewRHS, I);
3435             return BinaryOperator::Create(
3436                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3437           }
3438           if (!isa<Constant>(Op0RHS) &&
3439               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3440             // Not masking anything out for the RHS, move to LHS.
3441             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3442                                                    Op0LHS->getName()+".masked");
3443             InsertNewInstBefore(NewLHS, I);
3444             return BinaryOperator::Create(
3445                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3446           }
3447         }
3448
3449         break;
3450       case Instruction::Add:
3451         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3452         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3453         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3454         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3455           return BinaryOperator::CreateAnd(V, AndRHS);
3456         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3457           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3458         break;
3459
3460       case Instruction::Sub:
3461         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3462         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3463         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3464         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3465           return BinaryOperator::CreateAnd(V, AndRHS);
3466         break;
3467       }
3468
3469       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3470         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3471           return Res;
3472     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3473       // If this is an integer truncation or change from signed-to-unsigned, and
3474       // if the source is an and/or with immediate, transform it.  This
3475       // frequently occurs for bitfield accesses.
3476       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3477         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3478             CastOp->getNumOperands() == 2)
3479           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3480             if (CastOp->getOpcode() == Instruction::And) {
3481               // Change: and (cast (and X, C1) to T), C2
3482               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3483               // This will fold the two constants together, which may allow 
3484               // other simplifications.
3485               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3486                 CastOp->getOperand(0), I.getType(), 
3487                 CastOp->getName()+".shrunk");
3488               NewCast = InsertNewInstBefore(NewCast, I);
3489               // trunc_or_bitcast(C1)&C2
3490               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3491               C3 = ConstantExpr::getAnd(C3, AndRHS);
3492               return BinaryOperator::CreateAnd(NewCast, C3);
3493             } else if (CastOp->getOpcode() == Instruction::Or) {
3494               // Change: and (cast (or X, C1) to T), C2
3495               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3496               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3497               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3498                 return ReplaceInstUsesWith(I, AndRHS);
3499             }
3500           }
3501       }
3502     }
3503
3504     // Try to fold constant and into select arguments.
3505     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3506       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3507         return R;
3508     if (isa<PHINode>(Op0))
3509       if (Instruction *NV = FoldOpIntoPhi(I))
3510         return NV;
3511   }
3512
3513   Value *Op0NotVal = dyn_castNotVal(Op0);
3514   Value *Op1NotVal = dyn_castNotVal(Op1);
3515
3516   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3517     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3518
3519   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3520   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3521     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3522                                                I.getName()+".demorgan");
3523     InsertNewInstBefore(Or, I);
3524     return BinaryOperator::CreateNot(Or);
3525   }
3526   
3527   {
3528     Value *A = 0, *B = 0, *C = 0, *D = 0;
3529     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3530       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3531         return ReplaceInstUsesWith(I, Op1);
3532     
3533       // (A|B) & ~(A&B) -> A^B
3534       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3535         if ((A == C && B == D) || (A == D && B == C))
3536           return BinaryOperator::CreateXor(A, B);
3537       }
3538     }
3539     
3540     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3541       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3542         return ReplaceInstUsesWith(I, Op0);
3543
3544       // ~(A&B) & (A|B) -> A^B
3545       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3546         if ((A == C && B == D) || (A == D && B == C))
3547           return BinaryOperator::CreateXor(A, B);
3548       }
3549     }
3550     
3551     if (Op0->hasOneUse() &&
3552         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3553       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3554         I.swapOperands();     // Simplify below
3555         std::swap(Op0, Op1);
3556       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3557         cast<BinaryOperator>(Op0)->swapOperands();
3558         I.swapOperands();     // Simplify below
3559         std::swap(Op0, Op1);
3560       }
3561     }
3562     if (Op1->hasOneUse() &&
3563         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3564       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3565         cast<BinaryOperator>(Op1)->swapOperands();
3566         std::swap(A, B);
3567       }
3568       if (A == Op0) {                                // A&(A^B) -> A & ~B
3569         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3570         InsertNewInstBefore(NotB, I);
3571         return BinaryOperator::CreateAnd(A, NotB);
3572       }
3573     }
3574   }
3575   
3576   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3577     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3578     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3579       return R;
3580
3581     Value *LHSVal, *RHSVal;
3582     ConstantInt *LHSCst, *RHSCst;
3583     ICmpInst::Predicate LHSCC, RHSCC;
3584     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3585       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3586         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3587             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3588             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3589             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3590             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3591             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3592             
3593             // Don't try to fold ICMP_SLT + ICMP_ULT.
3594             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3595              ICmpInst::isSignedPredicate(LHSCC) == 
3596                  ICmpInst::isSignedPredicate(RHSCC))) {
3597           // Ensure that the larger constant is on the RHS.
3598           ICmpInst::Predicate GT;
3599           if (ICmpInst::isSignedPredicate(LHSCC) ||
3600               (ICmpInst::isEquality(LHSCC) && 
3601                ICmpInst::isSignedPredicate(RHSCC)))
3602             GT = ICmpInst::ICMP_SGT;
3603           else
3604             GT = ICmpInst::ICMP_UGT;
3605           
3606           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3607           ICmpInst *LHS = cast<ICmpInst>(Op0);
3608           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3609             std::swap(LHS, RHS);
3610             std::swap(LHSCst, RHSCst);
3611             std::swap(LHSCC, RHSCC);
3612           }
3613
3614           // At this point, we know we have have two icmp instructions
3615           // comparing a value against two constants and and'ing the result
3616           // together.  Because of the above check, we know that we only have
3617           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3618           // (from the FoldICmpLogical check above), that the two constants 
3619           // are not equal and that the larger constant is on the RHS
3620           assert(LHSCst != RHSCst && "Compares not folded above?");
3621
3622           switch (LHSCC) {
3623           default: assert(0 && "Unknown integer condition code!");
3624           case ICmpInst::ICMP_EQ:
3625             switch (RHSCC) {
3626             default: assert(0 && "Unknown integer condition code!");
3627             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3628             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3629             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3630               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3631             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3632             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3633             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3634               return ReplaceInstUsesWith(I, LHS);
3635             }
3636           case ICmpInst::ICMP_NE:
3637             switch (RHSCC) {
3638             default: assert(0 && "Unknown integer condition code!");
3639             case ICmpInst::ICMP_ULT:
3640               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3641                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3642               break;                        // (X != 13 & X u< 15) -> no change
3643             case ICmpInst::ICMP_SLT:
3644               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3645                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3646               break;                        // (X != 13 & X s< 15) -> no change
3647             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3648             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3649             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3650               return ReplaceInstUsesWith(I, RHS);
3651             case ICmpInst::ICMP_NE:
3652               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3653                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3654                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3655                                                       LHSVal->getName()+".off");
3656                 InsertNewInstBefore(Add, I);
3657                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3658                                     ConstantInt::get(Add->getType(), 1));
3659               }
3660               break;                        // (X != 13 & X != 15) -> no change
3661             }
3662             break;
3663           case ICmpInst::ICMP_ULT:
3664             switch (RHSCC) {
3665             default: assert(0 && "Unknown integer condition code!");
3666             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3667             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3668               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3669             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3670               break;
3671             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3672             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3673               return ReplaceInstUsesWith(I, LHS);
3674             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3675               break;
3676             }
3677             break;
3678           case ICmpInst::ICMP_SLT:
3679             switch (RHSCC) {
3680             default: assert(0 && "Unknown integer condition code!");
3681             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3682             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3683               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3684             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3685               break;
3686             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3687             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3688               return ReplaceInstUsesWith(I, LHS);
3689             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3690               break;
3691             }
3692             break;
3693           case ICmpInst::ICMP_UGT:
3694             switch (RHSCC) {
3695             default: assert(0 && "Unknown integer condition code!");
3696             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3697               return ReplaceInstUsesWith(I, LHS);
3698             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3699               return ReplaceInstUsesWith(I, RHS);
3700             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3701               break;
3702             case ICmpInst::ICMP_NE:
3703               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3704                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3705               break;                        // (X u> 13 & X != 15) -> no change
3706             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3707               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3708                                      true, I);
3709             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3710               break;
3711             }
3712             break;
3713           case ICmpInst::ICMP_SGT:
3714             switch (RHSCC) {
3715             default: assert(0 && "Unknown integer condition code!");
3716             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3717             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3718               return ReplaceInstUsesWith(I, RHS);
3719             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3720               break;
3721             case ICmpInst::ICMP_NE:
3722               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3723                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3724               break;                        // (X s> 13 & X != 15) -> no change
3725             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3726               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3727                                      true, I);
3728             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3729               break;
3730             }
3731             break;
3732           }
3733         }
3734   }
3735
3736   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3737   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3738     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3739       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3740         const Type *SrcTy = Op0C->getOperand(0)->getType();
3741         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3742             // Only do this if the casts both really cause code to be generated.
3743             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3744                               I.getType(), TD) &&
3745             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3746                               I.getType(), TD)) {
3747           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3748                                                          Op1C->getOperand(0),
3749                                                          I.getName());
3750           InsertNewInstBefore(NewOp, I);
3751           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3752         }
3753       }
3754     
3755   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3756   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3757     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3758       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3759           SI0->getOperand(1) == SI1->getOperand(1) &&
3760           (SI0->hasOneUse() || SI1->hasOneUse())) {
3761         Instruction *NewOp =
3762           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3763                                                         SI1->getOperand(0),
3764                                                         SI0->getName()), I);
3765         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3766                                       SI1->getOperand(1));
3767       }
3768   }
3769
3770   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3771   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3772     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3773       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3774           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3775         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3776           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3777             // If either of the constants are nans, then the whole thing returns
3778             // false.
3779             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3780               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3781             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3782                                 RHS->getOperand(0));
3783           }
3784     }
3785   }
3786       
3787   return Changed ? &I : 0;
3788 }
3789
3790 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3791 /// in the result.  If it does, and if the specified byte hasn't been filled in
3792 /// yet, fill it in and return false.
3793 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3794   Instruction *I = dyn_cast<Instruction>(V);
3795   if (I == 0) return true;
3796
3797   // If this is an or instruction, it is an inner node of the bswap.
3798   if (I->getOpcode() == Instruction::Or)
3799     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3800            CollectBSwapParts(I->getOperand(1), ByteValues);
3801   
3802   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3803   // If this is a shift by a constant int, and it is "24", then its operand
3804   // defines a byte.  We only handle unsigned types here.
3805   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3806     // Not shifting the entire input by N-1 bytes?
3807     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3808         8*(ByteValues.size()-1))
3809       return true;
3810     
3811     unsigned DestNo;
3812     if (I->getOpcode() == Instruction::Shl) {
3813       // X << 24 defines the top byte with the lowest of the input bytes.
3814       DestNo = ByteValues.size()-1;
3815     } else {
3816       // X >>u 24 defines the low byte with the highest of the input bytes.
3817       DestNo = 0;
3818     }
3819     
3820     // If the destination byte value is already defined, the values are or'd
3821     // together, which isn't a bswap (unless it's an or of the same bits).
3822     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3823       return true;
3824     ByteValues[DestNo] = I->getOperand(0);
3825     return false;
3826   }
3827   
3828   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3829   // don't have this.
3830   Value *Shift = 0, *ShiftLHS = 0;
3831   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3832   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3833       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3834     return true;
3835   Instruction *SI = cast<Instruction>(Shift);
3836
3837   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3838   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3839       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3840     return true;
3841   
3842   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3843   unsigned DestByte;
3844   if (AndAmt->getValue().getActiveBits() > 64)
3845     return true;
3846   uint64_t AndAmtVal = AndAmt->getZExtValue();
3847   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3848     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3849       break;
3850   // Unknown mask for bswap.
3851   if (DestByte == ByteValues.size()) return true;
3852   
3853   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3854   unsigned SrcByte;
3855   if (SI->getOpcode() == Instruction::Shl)
3856     SrcByte = DestByte - ShiftBytes;
3857   else
3858     SrcByte = DestByte + ShiftBytes;
3859   
3860   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3861   if (SrcByte != ByteValues.size()-DestByte-1)
3862     return true;
3863   
3864   // If the destination byte value is already defined, the values are or'd
3865   // together, which isn't a bswap (unless it's an or of the same bits).
3866   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3867     return true;
3868   ByteValues[DestByte] = SI->getOperand(0);
3869   return false;
3870 }
3871
3872 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3873 /// If so, insert the new bswap intrinsic and return it.
3874 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3875   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3876   if (!ITy || ITy->getBitWidth() % 16) 
3877     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3878   
3879   /// ByteValues - For each byte of the result, we keep track of which value
3880   /// defines each byte.
3881   SmallVector<Value*, 8> ByteValues;
3882   ByteValues.resize(ITy->getBitWidth()/8);
3883     
3884   // Try to find all the pieces corresponding to the bswap.
3885   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3886       CollectBSwapParts(I.getOperand(1), ByteValues))
3887     return 0;
3888   
3889   // Check to see if all of the bytes come from the same value.
3890   Value *V = ByteValues[0];
3891   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3892   
3893   // Check to make sure that all of the bytes come from the same value.
3894   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3895     if (ByteValues[i] != V)
3896       return 0;
3897   const Type *Tys[] = { ITy };
3898   Module *M = I.getParent()->getParent()->getParent();
3899   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3900   return CallInst::Create(F, V);
3901 }
3902
3903
3904 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3905   bool Changed = SimplifyCommutative(I);
3906   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3907
3908   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3909     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3910
3911   // or X, X = X
3912   if (Op0 == Op1)
3913     return ReplaceInstUsesWith(I, Op0);
3914
3915   // See if we can simplify any instructions used by the instruction whose sole 
3916   // purpose is to compute bits we don't care about.
3917   if (!isa<VectorType>(I.getType())) {
3918     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3919     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3920     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3921                              KnownZero, KnownOne))
3922       return &I;
3923   } else if (isa<ConstantAggregateZero>(Op1)) {
3924     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3925   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3926     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3927       return ReplaceInstUsesWith(I, I.getOperand(1));
3928   }
3929     
3930
3931   
3932   // or X, -1 == -1
3933   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3934     ConstantInt *C1 = 0; Value *X = 0;
3935     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3936     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3937       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3938       InsertNewInstBefore(Or, I);
3939       Or->takeName(Op0);
3940       return BinaryOperator::CreateAnd(Or, 
3941                ConstantInt::get(RHS->getValue() | C1->getValue()));
3942     }
3943
3944     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3945     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3946       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3947       InsertNewInstBefore(Or, I);
3948       Or->takeName(Op0);
3949       return BinaryOperator::CreateXor(Or,
3950                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3951     }
3952
3953     // Try to fold constant and into select arguments.
3954     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3955       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3956         return R;
3957     if (isa<PHINode>(Op0))
3958       if (Instruction *NV = FoldOpIntoPhi(I))
3959         return NV;
3960   }
3961
3962   Value *A = 0, *B = 0;
3963   ConstantInt *C1 = 0, *C2 = 0;
3964
3965   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3966     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3967       return ReplaceInstUsesWith(I, Op1);
3968   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3969     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3970       return ReplaceInstUsesWith(I, Op0);
3971
3972   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3973   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3974   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3975       match(Op1, m_Or(m_Value(), m_Value())) ||
3976       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3977        match(Op1, m_Shift(m_Value(), m_Value())))) {
3978     if (Instruction *BSwap = MatchBSwap(I))
3979       return BSwap;
3980   }
3981   
3982   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3983   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3984       MaskedValueIsZero(Op1, C1->getValue())) {
3985     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3986     InsertNewInstBefore(NOr, I);
3987     NOr->takeName(Op0);
3988     return BinaryOperator::CreateXor(NOr, C1);
3989   }
3990
3991   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3992   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3993       MaskedValueIsZero(Op0, C1->getValue())) {
3994     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
3995     InsertNewInstBefore(NOr, I);
3996     NOr->takeName(Op0);
3997     return BinaryOperator::CreateXor(NOr, C1);
3998   }
3999
4000   // (A & C)|(B & D)
4001   Value *C = 0, *D = 0;
4002   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4003       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4004     Value *V1 = 0, *V2 = 0, *V3 = 0;
4005     C1 = dyn_cast<ConstantInt>(C);
4006     C2 = dyn_cast<ConstantInt>(D);
4007     if (C1 && C2) {  // (A & C1)|(B & C2)
4008       // If we have: ((V + N) & C1) | (V & C2)
4009       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4010       // replace with V+N.
4011       if (C1->getValue() == ~C2->getValue()) {
4012         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4013             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4014           // Add commutes, try both ways.
4015           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4016             return ReplaceInstUsesWith(I, A);
4017           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4018             return ReplaceInstUsesWith(I, A);
4019         }
4020         // Or commutes, try both ways.
4021         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4022             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4023           // Add commutes, try both ways.
4024           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4025             return ReplaceInstUsesWith(I, B);
4026           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4027             return ReplaceInstUsesWith(I, B);
4028         }
4029       }
4030       V1 = 0; V2 = 0; V3 = 0;
4031     }
4032     
4033     // Check to see if we have any common things being and'ed.  If so, find the
4034     // terms for V1 & (V2|V3).
4035     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4036       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4037         V1 = A, V2 = C, V3 = D;
4038       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4039         V1 = A, V2 = B, V3 = C;
4040       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4041         V1 = C, V2 = A, V3 = D;
4042       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4043         V1 = C, V2 = A, V3 = B;
4044       
4045       if (V1) {
4046         Value *Or =
4047           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4048         return BinaryOperator::CreateAnd(V1, Or);
4049       }
4050     }
4051   }
4052   
4053   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4054   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4055     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4056       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4057           SI0->getOperand(1) == SI1->getOperand(1) &&
4058           (SI0->hasOneUse() || SI1->hasOneUse())) {
4059         Instruction *NewOp =
4060         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4061                                                      SI1->getOperand(0),
4062                                                      SI0->getName()), I);
4063         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4064                                       SI1->getOperand(1));
4065       }
4066   }
4067
4068   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4069     if (A == Op1)   // ~A | A == -1
4070       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4071   } else {
4072     A = 0;
4073   }
4074   // Note, A is still live here!
4075   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4076     if (Op0 == B)
4077       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4078
4079     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4080     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4081       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4082                                               I.getName()+".demorgan"), I);
4083       return BinaryOperator::CreateNot(And);
4084     }
4085   }
4086
4087   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4088   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4089     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4090       return R;
4091
4092     Value *LHSVal, *RHSVal;
4093     ConstantInt *LHSCst, *RHSCst;
4094     ICmpInst::Predicate LHSCC, RHSCC;
4095     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4096       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4097         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4098             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4099             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4100             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4101             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4102             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4103             // We can't fold (ugt x, C) | (sgt x, C2).
4104             PredicatesFoldable(LHSCC, RHSCC)) {
4105           // Ensure that the larger constant is on the RHS.
4106           ICmpInst *LHS = cast<ICmpInst>(Op0);
4107           bool NeedsSwap;
4108           if (ICmpInst::isSignedPredicate(LHSCC))
4109             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4110           else
4111             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4112             
4113           if (NeedsSwap) {
4114             std::swap(LHS, RHS);
4115             std::swap(LHSCst, RHSCst);
4116             std::swap(LHSCC, RHSCC);
4117           }
4118
4119           // At this point, we know we have have two icmp instructions
4120           // comparing a value against two constants and or'ing the result
4121           // together.  Because of the above check, we know that we only have
4122           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4123           // FoldICmpLogical check above), that the two constants are not
4124           // equal.
4125           assert(LHSCst != RHSCst && "Compares not folded above?");
4126
4127           switch (LHSCC) {
4128           default: assert(0 && "Unknown integer condition code!");
4129           case ICmpInst::ICMP_EQ:
4130             switch (RHSCC) {
4131             default: assert(0 && "Unknown integer condition code!");
4132             case ICmpInst::ICMP_EQ:
4133               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4134                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4135                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4136                                                       LHSVal->getName()+".off");
4137                 InsertNewInstBefore(Add, I);
4138                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4139                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4140               }
4141               break;                         // (X == 13 | X == 15) -> no change
4142             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4143             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4144               break;
4145             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4146             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4147             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4148               return ReplaceInstUsesWith(I, RHS);
4149             }
4150             break;
4151           case ICmpInst::ICMP_NE:
4152             switch (RHSCC) {
4153             default: assert(0 && "Unknown integer condition code!");
4154             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4155             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4156             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4157               return ReplaceInstUsesWith(I, LHS);
4158             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4159             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4160             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4161               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4162             }
4163             break;
4164           case ICmpInst::ICMP_ULT:
4165             switch (RHSCC) {
4166             default: assert(0 && "Unknown integer condition code!");
4167             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4168               break;
4169             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4170               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4171               // this can cause overflow.
4172               if (RHSCst->isMaxValue(false))
4173                 return ReplaceInstUsesWith(I, LHS);
4174               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4175                                      false, I);
4176             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4177               break;
4178             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4179             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4180               return ReplaceInstUsesWith(I, RHS);
4181             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4182               break;
4183             }
4184             break;
4185           case ICmpInst::ICMP_SLT:
4186             switch (RHSCC) {
4187             default: assert(0 && "Unknown integer condition code!");
4188             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4189               break;
4190             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4191               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4192               // this can cause overflow.
4193               if (RHSCst->isMaxValue(true))
4194                 return ReplaceInstUsesWith(I, LHS);
4195               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4196                                      false, I);
4197             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4198               break;
4199             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4200             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4201               return ReplaceInstUsesWith(I, RHS);
4202             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4203               break;
4204             }
4205             break;
4206           case ICmpInst::ICMP_UGT:
4207             switch (RHSCC) {
4208             default: assert(0 && "Unknown integer condition code!");
4209             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4210             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4211               return ReplaceInstUsesWith(I, LHS);
4212             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4213               break;
4214             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4215             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4216               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4217             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4218               break;
4219             }
4220             break;
4221           case ICmpInst::ICMP_SGT:
4222             switch (RHSCC) {
4223             default: assert(0 && "Unknown integer condition code!");
4224             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4225             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4226               return ReplaceInstUsesWith(I, LHS);
4227             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4228               break;
4229             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4230             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4231               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4232             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4233               break;
4234             }
4235             break;
4236           }
4237         }
4238   }
4239     
4240   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4241   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4242     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4244         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4245             !isa<ICmpInst>(Op1C->getOperand(0))) {
4246           const Type *SrcTy = Op0C->getOperand(0)->getType();
4247           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4248               // Only do this if the casts both really cause code to be
4249               // generated.
4250               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4251                                 I.getType(), TD) &&
4252               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4253                                 I.getType(), TD)) {
4254             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4255                                                           Op1C->getOperand(0),
4256                                                           I.getName());
4257             InsertNewInstBefore(NewOp, I);
4258             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4259           }
4260         }
4261       }
4262   }
4263   
4264     
4265   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4266   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4267     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4268       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4269           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4270           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4271         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4272           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4273             // If either of the constants are nans, then the whole thing returns
4274             // true.
4275             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4276               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4277             
4278             // Otherwise, no need to compare the two constants, compare the
4279             // rest.
4280             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4281                                 RHS->getOperand(0));
4282           }
4283     }
4284   }
4285
4286   return Changed ? &I : 0;
4287 }
4288
4289 namespace {
4290
4291 // XorSelf - Implements: X ^ X --> 0
4292 struct XorSelf {
4293   Value *RHS;
4294   XorSelf(Value *rhs) : RHS(rhs) {}
4295   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4296   Instruction *apply(BinaryOperator &Xor) const {
4297     return &Xor;
4298   }
4299 };
4300
4301 }
4302
4303 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4304   bool Changed = SimplifyCommutative(I);
4305   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4306
4307   if (isa<UndefValue>(Op1)) {
4308     if (isa<UndefValue>(Op0))
4309       // Handle undef ^ undef -> 0 special case. This is a common
4310       // idiom (misuse).
4311       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4312     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4313   }
4314
4315   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4316   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4317     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4318     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4319   }
4320   
4321   // See if we can simplify any instructions used by the instruction whose sole 
4322   // purpose is to compute bits we don't care about.
4323   if (!isa<VectorType>(I.getType())) {
4324     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4325     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4326     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4327                              KnownZero, KnownOne))
4328       return &I;
4329   } else if (isa<ConstantAggregateZero>(Op1)) {
4330     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4331   }
4332
4333   // Is this a ~ operation?
4334   if (Value *NotOp = dyn_castNotVal(&I)) {
4335     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4336     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4337     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4338       if (Op0I->getOpcode() == Instruction::And || 
4339           Op0I->getOpcode() == Instruction::Or) {
4340         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4341         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4342           Instruction *NotY =
4343             BinaryOperator::CreateNot(Op0I->getOperand(1),
4344                                       Op0I->getOperand(1)->getName()+".not");
4345           InsertNewInstBefore(NotY, I);
4346           if (Op0I->getOpcode() == Instruction::And)
4347             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4348           else
4349             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4350         }
4351       }
4352     }
4353   }
4354   
4355   
4356   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4357     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4358     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4359       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4360         return new ICmpInst(ICI->getInversePredicate(),
4361                             ICI->getOperand(0), ICI->getOperand(1));
4362
4363       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4364         return new FCmpInst(FCI->getInversePredicate(),
4365                             FCI->getOperand(0), FCI->getOperand(1));
4366     }
4367
4368     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4369     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4370       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4371         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4372           Instruction::CastOps Opcode = Op0C->getOpcode();
4373           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4374             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4375                                              Op0C->getDestTy())) {
4376               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4377                                      CI->getOpcode(), CI->getInversePredicate(),
4378                                      CI->getOperand(0), CI->getOperand(1)), I);
4379               NewCI->takeName(CI);
4380               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4381             }
4382           }
4383         }
4384       }
4385     }
4386
4387     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4388       // ~(c-X) == X-c-1 == X+(-c-1)
4389       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4390         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4391           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4392           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4393                                               ConstantInt::get(I.getType(), 1));
4394           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4395         }
4396           
4397       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4398         if (Op0I->getOpcode() == Instruction::Add) {
4399           // ~(X-c) --> (-c-1)-X
4400           if (RHS->isAllOnesValue()) {
4401             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4402             return BinaryOperator::CreateSub(
4403                            ConstantExpr::getSub(NegOp0CI,
4404                                              ConstantInt::get(I.getType(), 1)),
4405                                           Op0I->getOperand(0));
4406           } else if (RHS->getValue().isSignBit()) {
4407             // (X + C) ^ signbit -> (X + C + signbit)
4408             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4409             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4410
4411           }
4412         } else if (Op0I->getOpcode() == Instruction::Or) {
4413           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4414           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4415             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4416             // Anything in both C1 and C2 is known to be zero, remove it from
4417             // NewRHS.
4418             Constant *CommonBits = And(Op0CI, RHS);
4419             NewRHS = ConstantExpr::getAnd(NewRHS, 
4420                                           ConstantExpr::getNot(CommonBits));
4421             AddToWorkList(Op0I);
4422             I.setOperand(0, Op0I->getOperand(0));
4423             I.setOperand(1, NewRHS);
4424             return &I;
4425           }
4426         }
4427       }
4428     }
4429
4430     // Try to fold constant and into select arguments.
4431     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4432       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4433         return R;
4434     if (isa<PHINode>(Op0))
4435       if (Instruction *NV = FoldOpIntoPhi(I))
4436         return NV;
4437   }
4438
4439   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4440     if (X == Op1)
4441       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4442
4443   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4444     if (X == Op0)
4445       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4446
4447   
4448   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4449   if (Op1I) {
4450     Value *A, *B;
4451     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4452       if (A == Op0) {              // B^(B|A) == (A|B)^B
4453         Op1I->swapOperands();
4454         I.swapOperands();
4455         std::swap(Op0, Op1);
4456       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4457         I.swapOperands();     // Simplified below.
4458         std::swap(Op0, Op1);
4459       }
4460     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4461       if (Op0 == A)                                          // A^(A^B) == B
4462         return ReplaceInstUsesWith(I, B);
4463       else if (Op0 == B)                                     // A^(B^A) == B
4464         return ReplaceInstUsesWith(I, A);
4465     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4466       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4467         Op1I->swapOperands();
4468         std::swap(A, B);
4469       }
4470       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4471         I.swapOperands();     // Simplified below.
4472         std::swap(Op0, Op1);
4473       }
4474     }
4475   }
4476   
4477   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4478   if (Op0I) {
4479     Value *A, *B;
4480     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4481       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4482         std::swap(A, B);
4483       if (B == Op1) {                                // (A|B)^B == A & ~B
4484         Instruction *NotB =
4485           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4486         return BinaryOperator::CreateAnd(A, NotB);
4487       }
4488     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4489       if (Op1 == A)                                          // (A^B)^A == B
4490         return ReplaceInstUsesWith(I, B);
4491       else if (Op1 == B)                                     // (B^A)^A == B
4492         return ReplaceInstUsesWith(I, A);
4493     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4494       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4495         std::swap(A, B);
4496       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4497           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4498         Instruction *N =
4499           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4500         return BinaryOperator::CreateAnd(N, Op1);
4501       }
4502     }
4503   }
4504   
4505   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4506   if (Op0I && Op1I && Op0I->isShift() && 
4507       Op0I->getOpcode() == Op1I->getOpcode() && 
4508       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4509       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4510     Instruction *NewOp =
4511       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4512                                                     Op1I->getOperand(0),
4513                                                     Op0I->getName()), I);
4514     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4515                                   Op1I->getOperand(1));
4516   }
4517     
4518   if (Op0I && Op1I) {
4519     Value *A, *B, *C, *D;
4520     // (A & B)^(A | B) -> A ^ B
4521     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4522         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4523       if ((A == C && B == D) || (A == D && B == C)) 
4524         return BinaryOperator::CreateXor(A, B);
4525     }
4526     // (A | B)^(A & B) -> A ^ B
4527     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4528         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4529       if ((A == C && B == D) || (A == D && B == C)) 
4530         return BinaryOperator::CreateXor(A, B);
4531     }
4532     
4533     // (A & B)^(C & D)
4534     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4535         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4536         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4537       // (X & Y)^(X & Y) -> (Y^Z) & X
4538       Value *X = 0, *Y = 0, *Z = 0;
4539       if (A == C)
4540         X = A, Y = B, Z = D;
4541       else if (A == D)
4542         X = A, Y = B, Z = C;
4543       else if (B == C)
4544         X = B, Y = A, Z = D;
4545       else if (B == D)
4546         X = B, Y = A, Z = C;
4547       
4548       if (X) {
4549         Instruction *NewOp =
4550         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4551         return BinaryOperator::CreateAnd(NewOp, X);
4552       }
4553     }
4554   }
4555     
4556   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4557   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4558     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4559       return R;
4560
4561   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4562   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4563     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4564       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4565         const Type *SrcTy = Op0C->getOperand(0)->getType();
4566         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4567             // Only do this if the casts both really cause code to be generated.
4568             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4569                               I.getType(), TD) &&
4570             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4571                               I.getType(), TD)) {
4572           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4573                                                          Op1C->getOperand(0),
4574                                                          I.getName());
4575           InsertNewInstBefore(NewOp, I);
4576           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4577         }
4578       }
4579   }
4580
4581   return Changed ? &I : 0;
4582 }
4583
4584 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4585 /// overflowed for this type.
4586 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4587                             ConstantInt *In2, bool IsSigned = false) {
4588   Result = cast<ConstantInt>(Add(In1, In2));
4589
4590   if (IsSigned)
4591     if (In2->getValue().isNegative())
4592       return Result->getValue().sgt(In1->getValue());
4593     else
4594       return Result->getValue().slt(In1->getValue());
4595   else
4596     return Result->getValue().ult(In1->getValue());
4597 }
4598
4599 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4600 /// code necessary to compute the offset from the base pointer (without adding
4601 /// in the base pointer).  Return the result as a signed integer of intptr size.
4602 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4603   TargetData &TD = IC.getTargetData();
4604   gep_type_iterator GTI = gep_type_begin(GEP);
4605   const Type *IntPtrTy = TD.getIntPtrType();
4606   Value *Result = Constant::getNullValue(IntPtrTy);
4607
4608   // Build a mask for high order bits.
4609   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4610   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4611
4612   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4613        ++i, ++GTI) {
4614     Value *Op = *i;
4615     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4616     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4617       if (OpC->isZero()) continue;
4618       
4619       // Handle a struct index, which adds its field offset to the pointer.
4620       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4621         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4622         
4623         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4624           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4625         else
4626           Result = IC.InsertNewInstBefore(
4627                    BinaryOperator::CreateAdd(Result,
4628                                              ConstantInt::get(IntPtrTy, Size),
4629                                              GEP->getName()+".offs"), I);
4630         continue;
4631       }
4632       
4633       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4634       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4635       Scale = ConstantExpr::getMul(OC, Scale);
4636       if (Constant *RC = dyn_cast<Constant>(Result))
4637         Result = ConstantExpr::getAdd(RC, Scale);
4638       else {
4639         // Emit an add instruction.
4640         Result = IC.InsertNewInstBefore(
4641            BinaryOperator::CreateAdd(Result, Scale,
4642                                      GEP->getName()+".offs"), I);
4643       }
4644       continue;
4645     }
4646     // Convert to correct type.
4647     if (Op->getType() != IntPtrTy) {
4648       if (Constant *OpC = dyn_cast<Constant>(Op))
4649         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4650       else
4651         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4652                                                  Op->getName()+".c"), I);
4653     }
4654     if (Size != 1) {
4655       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4656       if (Constant *OpC = dyn_cast<Constant>(Op))
4657         Op = ConstantExpr::getMul(OpC, Scale);
4658       else    // We'll let instcombine(mul) convert this to a shl if possible.
4659         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4660                                                   GEP->getName()+".idx"), I);
4661     }
4662
4663     // Emit an add instruction.
4664     if (isa<Constant>(Op) && isa<Constant>(Result))
4665       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4666                                     cast<Constant>(Result));
4667     else
4668       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4669                                                   GEP->getName()+".offs"), I);
4670   }
4671   return Result;
4672 }
4673
4674
4675 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4676 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4677 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4678 /// complex, and scales are involved.  The above expression would also be legal
4679 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4680 /// later form is less amenable to optimization though, and we are allowed to
4681 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4682 ///
4683 /// If we can't emit an optimized form for this expression, this returns null.
4684 /// 
4685 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4686                                           InstCombiner &IC) {
4687   TargetData &TD = IC.getTargetData();
4688   gep_type_iterator GTI = gep_type_begin(GEP);
4689
4690   // Check to see if this gep only has a single variable index.  If so, and if
4691   // any constant indices are a multiple of its scale, then we can compute this
4692   // in terms of the scale of the variable index.  For example, if the GEP
4693   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4694   // because the expression will cross zero at the same point.
4695   unsigned i, e = GEP->getNumOperands();
4696   int64_t Offset = 0;
4697   for (i = 1; i != e; ++i, ++GTI) {
4698     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4699       // Compute the aggregate offset of constant indices.
4700       if (CI->isZero()) continue;
4701
4702       // Handle a struct index, which adds its field offset to the pointer.
4703       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4704         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4705       } else {
4706         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4707         Offset += Size*CI->getSExtValue();
4708       }
4709     } else {
4710       // Found our variable index.
4711       break;
4712     }
4713   }
4714   
4715   // If there are no variable indices, we must have a constant offset, just
4716   // evaluate it the general way.
4717   if (i == e) return 0;
4718   
4719   Value *VariableIdx = GEP->getOperand(i);
4720   // Determine the scale factor of the variable element.  For example, this is
4721   // 4 if the variable index is into an array of i32.
4722   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4723   
4724   // Verify that there are no other variable indices.  If so, emit the hard way.
4725   for (++i, ++GTI; i != e; ++i, ++GTI) {
4726     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4727     if (!CI) return 0;
4728    
4729     // Compute the aggregate offset of constant indices.
4730     if (CI->isZero()) continue;
4731     
4732     // Handle a struct index, which adds its field offset to the pointer.
4733     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4734       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4735     } else {
4736       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4737       Offset += Size*CI->getSExtValue();
4738     }
4739   }
4740   
4741   // Okay, we know we have a single variable index, which must be a
4742   // pointer/array/vector index.  If there is no offset, life is simple, return
4743   // the index.
4744   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4745   if (Offset == 0) {
4746     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4747     // we don't need to bother extending: the extension won't affect where the
4748     // computation crosses zero.
4749     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4750       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4751                                   VariableIdx->getNameStart(), &I);
4752     return VariableIdx;
4753   }
4754   
4755   // Otherwise, there is an index.  The computation we will do will be modulo
4756   // the pointer size, so get it.
4757   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4758   
4759   Offset &= PtrSizeMask;
4760   VariableScale &= PtrSizeMask;
4761
4762   // To do this transformation, any constant index must be a multiple of the
4763   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4764   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4765   // multiple of the variable scale.
4766   int64_t NewOffs = Offset / (int64_t)VariableScale;
4767   if (Offset != NewOffs*(int64_t)VariableScale)
4768     return 0;
4769
4770   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4771   const Type *IntPtrTy = TD.getIntPtrType();
4772   if (VariableIdx->getType() != IntPtrTy)
4773     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4774                                               true /*SExt*/, 
4775                                               VariableIdx->getNameStart(), &I);
4776   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4777   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4778 }
4779
4780
4781 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4782 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4783 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4784                                        ICmpInst::Predicate Cond,
4785                                        Instruction &I) {
4786   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4787
4788   // Look through bitcasts.
4789   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4790     RHS = BCI->getOperand(0);
4791
4792   Value *PtrBase = GEPLHS->getOperand(0);
4793   if (PtrBase == RHS) {
4794     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4795     // This transformation (ignoring the base and scales) is valid because we
4796     // know pointers can't overflow.  See if we can output an optimized form.
4797     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4798     
4799     // If not, synthesize the offset the hard way.
4800     if (Offset == 0)
4801       Offset = EmitGEPOffset(GEPLHS, I, *this);
4802     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4803                         Constant::getNullValue(Offset->getType()));
4804   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4805     // If the base pointers are different, but the indices are the same, just
4806     // compare the base pointer.
4807     if (PtrBase != GEPRHS->getOperand(0)) {
4808       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4809       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4810                         GEPRHS->getOperand(0)->getType();
4811       if (IndicesTheSame)
4812         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4813           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4814             IndicesTheSame = false;
4815             break;
4816           }
4817
4818       // If all indices are the same, just compare the base pointers.
4819       if (IndicesTheSame)
4820         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4821                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4822
4823       // Otherwise, the base pointers are different and the indices are
4824       // different, bail out.
4825       return 0;
4826     }
4827
4828     // If one of the GEPs has all zero indices, recurse.
4829     bool AllZeros = true;
4830     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4831       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4832           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4833         AllZeros = false;
4834         break;
4835       }
4836     if (AllZeros)
4837       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4838                           ICmpInst::getSwappedPredicate(Cond), I);
4839
4840     // If the other GEP has all zero indices, recurse.
4841     AllZeros = true;
4842     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4843       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4844           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4845         AllZeros = false;
4846         break;
4847       }
4848     if (AllZeros)
4849       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4850
4851     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4852       // If the GEPs only differ by one index, compare it.
4853       unsigned NumDifferences = 0;  // Keep track of # differences.
4854       unsigned DiffOperand = 0;     // The operand that differs.
4855       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4856         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4857           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4858                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4859             // Irreconcilable differences.
4860             NumDifferences = 2;
4861             break;
4862           } else {
4863             if (NumDifferences++) break;
4864             DiffOperand = i;
4865           }
4866         }
4867
4868       if (NumDifferences == 0)   // SAME GEP?
4869         return ReplaceInstUsesWith(I, // No comparison is needed here.
4870                                    ConstantInt::get(Type::Int1Ty,
4871                                              ICmpInst::isTrueWhenEqual(Cond)));
4872
4873       else if (NumDifferences == 1) {
4874         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4875         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4876         // Make sure we do a signed comparison here.
4877         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4878       }
4879     }
4880
4881     // Only lower this if the icmp is the only user of the GEP or if we expect
4882     // the result to fold to a constant!
4883     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4884         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4885       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4886       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4887       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4888       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4889     }
4890   }
4891   return 0;
4892 }
4893
4894 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4895 ///
4896 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4897                                                 Instruction *LHSI,
4898                                                 Constant *RHSC) {
4899   if (!isa<ConstantFP>(RHSC)) return 0;
4900   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4901   
4902   // Get the width of the mantissa.  We don't want to hack on conversions that
4903   // might lose information from the integer, e.g. "i64 -> float"
4904   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4905   if (MantissaWidth == -1) return 0;  // Unknown.
4906   
4907   // Check to see that the input is converted from an integer type that is small
4908   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4909   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4910   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4911   
4912   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4913   if (isa<UIToFPInst>(LHSI))
4914     ++InputSize;
4915   
4916   // If the conversion would lose info, don't hack on this.
4917   if ((int)InputSize > MantissaWidth)
4918     return 0;
4919   
4920   // Otherwise, we can potentially simplify the comparison.  We know that it
4921   // will always come through as an integer value and we know the constant is
4922   // not a NAN (it would have been previously simplified).
4923   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4924   
4925   ICmpInst::Predicate Pred;
4926   switch (I.getPredicate()) {
4927   default: assert(0 && "Unexpected predicate!");
4928   case FCmpInst::FCMP_UEQ:
4929   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4930   case FCmpInst::FCMP_UGT:
4931   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4932   case FCmpInst::FCMP_UGE:
4933   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4934   case FCmpInst::FCMP_ULT:
4935   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4936   case FCmpInst::FCMP_ULE:
4937   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4938   case FCmpInst::FCMP_UNE:
4939   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4940   case FCmpInst::FCMP_ORD:
4941     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4942   case FCmpInst::FCMP_UNO:
4943     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4944   }
4945   
4946   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4947   
4948   // Now we know that the APFloat is a normal number, zero or inf.
4949   
4950   // See if the FP constant is too large for the integer.  For example,
4951   // comparing an i8 to 300.0.
4952   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4953   
4954   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4955   // and large values. 
4956   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4957   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4958                         APFloat::rmNearestTiesToEven);
4959   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4960     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4961         Pred == ICmpInst::ICMP_SLE)
4962       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4963     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4964   }
4965   
4966   // See if the RHS value is < SignedMin.
4967   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4968   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4969                         APFloat::rmNearestTiesToEven);
4970   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4971     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4972         Pred == ICmpInst::ICMP_SGE)
4973       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4975   }
4976
4977   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4978   // it may still be fractional.  See if it is fractional by casting the FP
4979   // value to the integer value and back, checking for equality.  Don't do this
4980   // for zero, because -0.0 is not fractional.
4981   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4982   if (!RHS.isZero() &&
4983       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4984     // If we had a comparison against a fractional value, we have to adjust
4985     // the compare predicate and sometimes the value.  RHSC is rounded towards
4986     // zero at this point.
4987     switch (Pred) {
4988     default: assert(0 && "Unexpected integer comparison!");
4989     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
4990       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4991     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
4992       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4993     case ICmpInst::ICMP_SLE:
4994       // (float)int <= 4.4   --> int <= 4
4995       // (float)int <= -4.4  --> int < -4
4996       if (RHS.isNegative())
4997         Pred = ICmpInst::ICMP_SLT;
4998       break;
4999     case ICmpInst::ICMP_SLT:
5000       // (float)int < -4.4   --> int < -4
5001       // (float)int < 4.4    --> int <= 4
5002       if (!RHS.isNegative())
5003         Pred = ICmpInst::ICMP_SLE;
5004       break;
5005     case ICmpInst::ICMP_SGT:
5006       // (float)int > 4.4    --> int > 4
5007       // (float)int > -4.4   --> int >= -4
5008       if (RHS.isNegative())
5009         Pred = ICmpInst::ICMP_SGE;
5010       break;
5011     case ICmpInst::ICMP_SGE:
5012       // (float)int >= -4.4   --> int >= -4
5013       // (float)int >= 4.4    --> int > 4
5014       if (!RHS.isNegative())
5015         Pred = ICmpInst::ICMP_SGT;
5016       break;
5017     }
5018   }
5019
5020   // Lower this FP comparison into an appropriate integer version of the
5021   // comparison.
5022   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5023 }
5024
5025 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5026   bool Changed = SimplifyCompare(I);
5027   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5028
5029   // Fold trivial predicates.
5030   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5031     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5032   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5033     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5034   
5035   // Simplify 'fcmp pred X, X'
5036   if (Op0 == Op1) {
5037     switch (I.getPredicate()) {
5038     default: assert(0 && "Unknown predicate!");
5039     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5040     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5041     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5042       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5043     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5044     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5045     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5046       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5047       
5048     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5049     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5050     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5051     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5052       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5053       I.setPredicate(FCmpInst::FCMP_UNO);
5054       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5055       return &I;
5056       
5057     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5058     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5059     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5060     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5061       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5062       I.setPredicate(FCmpInst::FCMP_ORD);
5063       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5064       return &I;
5065     }
5066   }
5067     
5068   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5069     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5070
5071   // Handle fcmp with constant RHS
5072   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5073     // If the constant is a nan, see if we can fold the comparison based on it.
5074     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5075       if (CFP->getValueAPF().isNaN()) {
5076         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5077           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5078         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5079                "Comparison must be either ordered or unordered!");
5080         // True if unordered.
5081         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5082       }
5083     }
5084     
5085     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5086       switch (LHSI->getOpcode()) {
5087       case Instruction::PHI:
5088         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5089         // block.  If in the same block, we're encouraging jump threading.  If
5090         // not, we are just pessimizing the code by making an i1 phi.
5091         if (LHSI->getParent() == I.getParent())
5092           if (Instruction *NV = FoldOpIntoPhi(I))
5093             return NV;
5094         break;
5095       case Instruction::SIToFP:
5096       case Instruction::UIToFP:
5097         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5098           return NV;
5099         break;
5100       case Instruction::Select:
5101         // If either operand of the select is a constant, we can fold the
5102         // comparison into the select arms, which will cause one to be
5103         // constant folded and the select turned into a bitwise or.
5104         Value *Op1 = 0, *Op2 = 0;
5105         if (LHSI->hasOneUse()) {
5106           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5107             // Fold the known value into the constant operand.
5108             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5109             // Insert a new FCmp of the other select operand.
5110             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5111                                                       LHSI->getOperand(2), RHSC,
5112                                                       I.getName()), I);
5113           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5114             // Fold the known value into the constant operand.
5115             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5116             // Insert a new FCmp of the other select operand.
5117             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5118                                                       LHSI->getOperand(1), RHSC,
5119                                                       I.getName()), I);
5120           }
5121         }
5122
5123         if (Op1)
5124           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5125         break;
5126       }
5127   }
5128
5129   return Changed ? &I : 0;
5130 }
5131
5132 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5133   bool Changed = SimplifyCompare(I);
5134   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5135   const Type *Ty = Op0->getType();
5136
5137   // icmp X, X
5138   if (Op0 == Op1)
5139     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5140                                                    I.isTrueWhenEqual()));
5141
5142   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5143     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5144   
5145   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5146   // addresses never equal each other!  We already know that Op0 != Op1.
5147   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5148        isa<ConstantPointerNull>(Op0)) &&
5149       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5150        isa<ConstantPointerNull>(Op1)))
5151     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5152                                                    !I.isTrueWhenEqual()));
5153
5154   // icmp's with boolean values can always be turned into bitwise operations
5155   if (Ty == Type::Int1Ty) {
5156     switch (I.getPredicate()) {
5157     default: assert(0 && "Invalid icmp instruction!");
5158     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5159       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5160       InsertNewInstBefore(Xor, I);
5161       return BinaryOperator::CreateNot(Xor);
5162     }
5163     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5164       return BinaryOperator::CreateXor(Op0, Op1);
5165
5166     case ICmpInst::ICMP_UGT:
5167     case ICmpInst::ICMP_SGT:
5168       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5169       // FALL THROUGH
5170     case ICmpInst::ICMP_ULT:
5171     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5172       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5173       InsertNewInstBefore(Not, I);
5174       return BinaryOperator::CreateAnd(Not, Op1);
5175     }
5176     case ICmpInst::ICMP_UGE:
5177     case ICmpInst::ICMP_SGE:
5178       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5179       // FALL THROUGH
5180     case ICmpInst::ICMP_ULE:
5181     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5182       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5183       InsertNewInstBefore(Not, I);
5184       return BinaryOperator::CreateOr(Not, Op1);
5185     }
5186     }
5187   }
5188
5189   // See if we are doing a comparison between a constant and an instruction that
5190   // can be folded into the comparison.
5191   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5192       Value *A, *B;
5193     
5194     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5195     if (I.isEquality() && CI->isNullValue() &&
5196         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5197       // (icmp cond A B) if cond is equality
5198       return new ICmpInst(I.getPredicate(), A, B);
5199     }
5200     
5201     switch (I.getPredicate()) {
5202     default: break;
5203     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5204       if (CI->isMinValue(false))
5205         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5206       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5207         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5208       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5209         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5210       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5211       if (CI->isMinValue(true))
5212         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5213                             ConstantInt::getAllOnesValue(Op0->getType()));
5214           
5215       break;
5216
5217     case ICmpInst::ICMP_SLT:
5218       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5219         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5220       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5221         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5222       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5223         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5224       break;
5225
5226     case ICmpInst::ICMP_UGT:
5227       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5228         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5229       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5230         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5231       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5232         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5233         
5234       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5235       if (CI->isMaxValue(true))
5236         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5237                             ConstantInt::getNullValue(Op0->getType()));
5238       break;
5239
5240     case ICmpInst::ICMP_SGT:
5241       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5242         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5243       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5244         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5245       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5246         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5247       break;
5248
5249     case ICmpInst::ICMP_ULE:
5250       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5251         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5252       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5253         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5254       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5255         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5256       break;
5257
5258     case ICmpInst::ICMP_SLE:
5259       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5260         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5261       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5262         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5263       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5264         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5265       break;
5266
5267     case ICmpInst::ICMP_UGE:
5268       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5269         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5270       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5271         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5272       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5273         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5274       break;
5275
5276     case ICmpInst::ICMP_SGE:
5277       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5278         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5279       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5280         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5281       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5282         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5283       break;
5284     }
5285
5286     // If we still have a icmp le or icmp ge instruction, turn it into the
5287     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5288     // already been handled above, this requires little checking.
5289     //
5290     switch (I.getPredicate()) {
5291     default: break;
5292     case ICmpInst::ICMP_ULE: 
5293       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5294     case ICmpInst::ICMP_SLE:
5295       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5296     case ICmpInst::ICMP_UGE:
5297       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5298     case ICmpInst::ICMP_SGE:
5299       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5300     }
5301     
5302     // See if we can fold the comparison based on bits known to be zero or one
5303     // in the input.  If this comparison is a normal comparison, it demands all
5304     // bits, if it is a sign bit comparison, it only demands the sign bit.
5305     
5306     bool UnusedBit;
5307     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5308     
5309     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5310     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5311     if (SimplifyDemandedBits(Op0, 
5312                              isSignBit ? APInt::getSignBit(BitWidth)
5313                                        : APInt::getAllOnesValue(BitWidth),
5314                              KnownZero, KnownOne, 0))
5315       return &I;
5316         
5317     // Given the known and unknown bits, compute a range that the LHS could be
5318     // in.
5319     if ((KnownOne | KnownZero) != 0) {
5320       // Compute the Min, Max and RHS values based on the known bits. For the
5321       // EQ and NE we use unsigned values.
5322       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5323       const APInt& RHSVal = CI->getValue();
5324       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5325         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5326                                                Max);
5327       } else {
5328         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5329                                                  Max);
5330       }
5331       switch (I.getPredicate()) {  // LE/GE have been folded already.
5332       default: assert(0 && "Unknown icmp opcode!");
5333       case ICmpInst::ICMP_EQ:
5334         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5335           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5336         break;
5337       case ICmpInst::ICMP_NE:
5338         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5339           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5340         break;
5341       case ICmpInst::ICMP_ULT:
5342         if (Max.ult(RHSVal))
5343           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5344         if (Min.uge(RHSVal))
5345           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5346         break;
5347       case ICmpInst::ICMP_UGT:
5348         if (Min.ugt(RHSVal))
5349           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5350         if (Max.ule(RHSVal))
5351           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5352         break;
5353       case ICmpInst::ICMP_SLT:
5354         if (Max.slt(RHSVal))
5355           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5356         if (Min.sgt(RHSVal))
5357           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5358         break;
5359       case ICmpInst::ICMP_SGT: 
5360         if (Min.sgt(RHSVal))
5361           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5362         if (Max.sle(RHSVal))
5363           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5364         break;
5365       }
5366     }
5367           
5368     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5369     // instruction, see if that instruction also has constants so that the 
5370     // instruction can be folded into the icmp 
5371     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5372       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5373         return Res;
5374   }
5375
5376   // Handle icmp with constant (but not simple integer constant) RHS
5377   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5378     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5379       switch (LHSI->getOpcode()) {
5380       case Instruction::GetElementPtr:
5381         if (RHSC->isNullValue()) {
5382           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5383           bool isAllZeros = true;
5384           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5385             if (!isa<Constant>(LHSI->getOperand(i)) ||
5386                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5387               isAllZeros = false;
5388               break;
5389             }
5390           if (isAllZeros)
5391             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5392                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5393         }
5394         break;
5395
5396       case Instruction::PHI:
5397         // Only fold icmp into the PHI if the phi and fcmp are in the same
5398         // block.  If in the same block, we're encouraging jump threading.  If
5399         // not, we are just pessimizing the code by making an i1 phi.
5400         if (LHSI->getParent() == I.getParent())
5401           if (Instruction *NV = FoldOpIntoPhi(I))
5402             return NV;
5403         break;
5404       case Instruction::Select: {
5405         // If either operand of the select is a constant, we can fold the
5406         // comparison into the select arms, which will cause one to be
5407         // constant folded and the select turned into a bitwise or.
5408         Value *Op1 = 0, *Op2 = 0;
5409         if (LHSI->hasOneUse()) {
5410           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5411             // Fold the known value into the constant operand.
5412             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5413             // Insert a new ICmp of the other select operand.
5414             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5415                                                    LHSI->getOperand(2), RHSC,
5416                                                    I.getName()), I);
5417           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5418             // Fold the known value into the constant operand.
5419             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5420             // Insert a new ICmp of the other select operand.
5421             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5422                                                    LHSI->getOperand(1), RHSC,
5423                                                    I.getName()), I);
5424           }
5425         }
5426
5427         if (Op1)
5428           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5429         break;
5430       }
5431       case Instruction::Malloc:
5432         // If we have (malloc != null), and if the malloc has a single use, we
5433         // can assume it is successful and remove the malloc.
5434         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5435           AddToWorkList(LHSI);
5436           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5437                                                          !I.isTrueWhenEqual()));
5438         }
5439         break;
5440       }
5441   }
5442
5443   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5444   if (User *GEP = dyn_castGetElementPtr(Op0))
5445     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5446       return NI;
5447   if (User *GEP = dyn_castGetElementPtr(Op1))
5448     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5449                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5450       return NI;
5451
5452   // Test to see if the operands of the icmp are casted versions of other
5453   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5454   // now.
5455   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5456     if (isa<PointerType>(Op0->getType()) && 
5457         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5458       // We keep moving the cast from the left operand over to the right
5459       // operand, where it can often be eliminated completely.
5460       Op0 = CI->getOperand(0);
5461
5462       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5463       // so eliminate it as well.
5464       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5465         Op1 = CI2->getOperand(0);
5466
5467       // If Op1 is a constant, we can fold the cast into the constant.
5468       if (Op0->getType() != Op1->getType()) {
5469         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5470           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5471         } else {
5472           // Otherwise, cast the RHS right before the icmp
5473           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5474         }
5475       }
5476       return new ICmpInst(I.getPredicate(), Op0, Op1);
5477     }
5478   }
5479   
5480   if (isa<CastInst>(Op0)) {
5481     // Handle the special case of: icmp (cast bool to X), <cst>
5482     // This comes up when you have code like
5483     //   int X = A < B;
5484     //   if (X) ...
5485     // For generality, we handle any zero-extension of any operand comparison
5486     // with a constant or another cast from the same type.
5487     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5488       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5489         return R;
5490   }
5491   
5492   // ~x < ~y --> y < x
5493   { Value *A, *B;
5494     if (match(Op0, m_Not(m_Value(A))) &&
5495         match(Op1, m_Not(m_Value(B))))
5496       return new ICmpInst(I.getPredicate(), B, A);
5497   }
5498   
5499   if (I.isEquality()) {
5500     Value *A, *B, *C, *D;
5501     
5502     // -x == -y --> x == y
5503     if (match(Op0, m_Neg(m_Value(A))) &&
5504         match(Op1, m_Neg(m_Value(B))))
5505       return new ICmpInst(I.getPredicate(), A, B);
5506     
5507     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5508       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5509         Value *OtherVal = A == Op1 ? B : A;
5510         return new ICmpInst(I.getPredicate(), OtherVal,
5511                             Constant::getNullValue(A->getType()));
5512       }
5513
5514       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5515         // A^c1 == C^c2 --> A == C^(c1^c2)
5516         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5517           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5518             if (Op1->hasOneUse()) {
5519               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5520               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5521               return new ICmpInst(I.getPredicate(), A,
5522                                   InsertNewInstBefore(Xor, I));
5523             }
5524         
5525         // A^B == A^D -> B == D
5526         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5527         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5528         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5529         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5530       }
5531     }
5532     
5533     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5534         (A == Op0 || B == Op0)) {
5535       // A == (A^B)  ->  B == 0
5536       Value *OtherVal = A == Op0 ? B : A;
5537       return new ICmpInst(I.getPredicate(), OtherVal,
5538                           Constant::getNullValue(A->getType()));
5539     }
5540     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5541       // (A-B) == A  ->  B == 0
5542       return new ICmpInst(I.getPredicate(), B,
5543                           Constant::getNullValue(B->getType()));
5544     }
5545     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5546       // A == (A-B)  ->  B == 0
5547       return new ICmpInst(I.getPredicate(), B,
5548                           Constant::getNullValue(B->getType()));
5549     }
5550     
5551     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5552     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5553         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5554         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5555       Value *X = 0, *Y = 0, *Z = 0;
5556       
5557       if (A == C) {
5558         X = B; Y = D; Z = A;
5559       } else if (A == D) {
5560         X = B; Y = C; Z = A;
5561       } else if (B == C) {
5562         X = A; Y = D; Z = B;
5563       } else if (B == D) {
5564         X = A; Y = C; Z = B;
5565       }
5566       
5567       if (X) {   // Build (X^Y) & Z
5568         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5569         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5570         I.setOperand(0, Op1);
5571         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5572         return &I;
5573       }
5574     }
5575   }
5576   return Changed ? &I : 0;
5577 }
5578
5579
5580 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5581 /// and CmpRHS are both known to be integer constants.
5582 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5583                                           ConstantInt *DivRHS) {
5584   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5585   const APInt &CmpRHSV = CmpRHS->getValue();
5586   
5587   // FIXME: If the operand types don't match the type of the divide 
5588   // then don't attempt this transform. The code below doesn't have the
5589   // logic to deal with a signed divide and an unsigned compare (and
5590   // vice versa). This is because (x /s C1) <s C2  produces different 
5591   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5592   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5593   // work. :(  The if statement below tests that condition and bails 
5594   // if it finds it. 
5595   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5596   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5597     return 0;
5598   if (DivRHS->isZero())
5599     return 0; // The ProdOV computation fails on divide by zero.
5600
5601   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5602   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5603   // C2 (CI). By solving for X we can turn this into a range check 
5604   // instead of computing a divide. 
5605   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5606
5607   // Determine if the product overflows by seeing if the product is
5608   // not equal to the divide. Make sure we do the same kind of divide
5609   // as in the LHS instruction that we're folding. 
5610   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5611                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5612
5613   // Get the ICmp opcode
5614   ICmpInst::Predicate Pred = ICI.getPredicate();
5615
5616   // Figure out the interval that is being checked.  For example, a comparison
5617   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5618   // Compute this interval based on the constants involved and the signedness of
5619   // the compare/divide.  This computes a half-open interval, keeping track of
5620   // whether either value in the interval overflows.  After analysis each
5621   // overflow variable is set to 0 if it's corresponding bound variable is valid
5622   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5623   int LoOverflow = 0, HiOverflow = 0;
5624   ConstantInt *LoBound = 0, *HiBound = 0;
5625   
5626   
5627   if (!DivIsSigned) {  // udiv
5628     // e.g. X/5 op 3  --> [15, 20)
5629     LoBound = Prod;
5630     HiOverflow = LoOverflow = ProdOV;
5631     if (!HiOverflow)
5632       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5633   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5634     if (CmpRHSV == 0) {       // (X / pos) op 0
5635       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5636       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5637       HiBound = DivRHS;
5638     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5639       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5640       HiOverflow = LoOverflow = ProdOV;
5641       if (!HiOverflow)
5642         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5643     } else {                       // (X / pos) op neg
5644       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5645       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5646       LoOverflow = AddWithOverflow(LoBound, Prod,
5647                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5648       HiBound = AddOne(Prod);
5649       HiOverflow = ProdOV ? -1 : 0;
5650     }
5651   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5652     if (CmpRHSV == 0) {       // (X / neg) op 0
5653       // e.g. X/-5 op 0  --> [-4, 5)
5654       LoBound = AddOne(DivRHS);
5655       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5656       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5657         HiOverflow = 1;            // [INTMIN+1, overflow)
5658         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5659       }
5660     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5661       // e.g. X/-5 op 3  --> [-19, -14)
5662       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5663       if (!LoOverflow)
5664         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5665       HiBound = AddOne(Prod);
5666     } else {                       // (X / neg) op neg
5667       // e.g. X/-5 op -3  --> [15, 20)
5668       LoBound = Prod;
5669       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5670       HiBound = Subtract(Prod, DivRHS);
5671     }
5672     
5673     // Dividing by a negative swaps the condition.  LT <-> GT
5674     Pred = ICmpInst::getSwappedPredicate(Pred);
5675   }
5676
5677   Value *X = DivI->getOperand(0);
5678   switch (Pred) {
5679   default: assert(0 && "Unhandled icmp opcode!");
5680   case ICmpInst::ICMP_EQ:
5681     if (LoOverflow && HiOverflow)
5682       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5683     else if (HiOverflow)
5684       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5685                           ICmpInst::ICMP_UGE, X, LoBound);
5686     else if (LoOverflow)
5687       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5688                           ICmpInst::ICMP_ULT, X, HiBound);
5689     else
5690       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5691   case ICmpInst::ICMP_NE:
5692     if (LoOverflow && HiOverflow)
5693       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5694     else if (HiOverflow)
5695       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5696                           ICmpInst::ICMP_ULT, X, LoBound);
5697     else if (LoOverflow)
5698       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5699                           ICmpInst::ICMP_UGE, X, HiBound);
5700     else
5701       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5702   case ICmpInst::ICMP_ULT:
5703   case ICmpInst::ICMP_SLT:
5704     if (LoOverflow == +1)   // Low bound is greater than input range.
5705       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5706     if (LoOverflow == -1)   // Low bound is less than input range.
5707       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5708     return new ICmpInst(Pred, X, LoBound);
5709   case ICmpInst::ICMP_UGT:
5710   case ICmpInst::ICMP_SGT:
5711     if (HiOverflow == +1)       // High bound greater than input range.
5712       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5713     else if (HiOverflow == -1)  // High bound less than input range.
5714       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5715     if (Pred == ICmpInst::ICMP_UGT)
5716       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5717     else
5718       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5719   }
5720 }
5721
5722
5723 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5724 ///
5725 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5726                                                           Instruction *LHSI,
5727                                                           ConstantInt *RHS) {
5728   const APInt &RHSV = RHS->getValue();
5729   
5730   switch (LHSI->getOpcode()) {
5731   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5732     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5733       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5734       // fold the xor.
5735       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5736           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5737         Value *CompareVal = LHSI->getOperand(0);
5738         
5739         // If the sign bit of the XorCST is not set, there is no change to
5740         // the operation, just stop using the Xor.
5741         if (!XorCST->getValue().isNegative()) {
5742           ICI.setOperand(0, CompareVal);
5743           AddToWorkList(LHSI);
5744           return &ICI;
5745         }
5746         
5747         // Was the old condition true if the operand is positive?
5748         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5749         
5750         // If so, the new one isn't.
5751         isTrueIfPositive ^= true;
5752         
5753         if (isTrueIfPositive)
5754           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5755         else
5756           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5757       }
5758     }
5759     break;
5760   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5761     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5762         LHSI->getOperand(0)->hasOneUse()) {
5763       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5764       
5765       // If the LHS is an AND of a truncating cast, we can widen the
5766       // and/compare to be the input width without changing the value
5767       // produced, eliminating a cast.
5768       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5769         // We can do this transformation if either the AND constant does not
5770         // have its sign bit set or if it is an equality comparison. 
5771         // Extending a relational comparison when we're checking the sign
5772         // bit would not work.
5773         if (Cast->hasOneUse() &&
5774             (ICI.isEquality() ||
5775              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5776           uint32_t BitWidth = 
5777             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5778           APInt NewCST = AndCST->getValue();
5779           NewCST.zext(BitWidth);
5780           APInt NewCI = RHSV;
5781           NewCI.zext(BitWidth);
5782           Instruction *NewAnd = 
5783             BinaryOperator::CreateAnd(Cast->getOperand(0),
5784                                       ConstantInt::get(NewCST),LHSI->getName());
5785           InsertNewInstBefore(NewAnd, ICI);
5786           return new ICmpInst(ICI.getPredicate(), NewAnd,
5787                               ConstantInt::get(NewCI));
5788         }
5789       }
5790       
5791       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5792       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5793       // happens a LOT in code produced by the C front-end, for bitfield
5794       // access.
5795       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5796       if (Shift && !Shift->isShift())
5797         Shift = 0;
5798       
5799       ConstantInt *ShAmt;
5800       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5801       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5802       const Type *AndTy = AndCST->getType();          // Type of the and.
5803       
5804       // We can fold this as long as we can't shift unknown bits
5805       // into the mask.  This can only happen with signed shift
5806       // rights, as they sign-extend.
5807       if (ShAmt) {
5808         bool CanFold = Shift->isLogicalShift();
5809         if (!CanFold) {
5810           // To test for the bad case of the signed shr, see if any
5811           // of the bits shifted in could be tested after the mask.
5812           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5813           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5814           
5815           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5816           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5817                AndCST->getValue()) == 0)
5818             CanFold = true;
5819         }
5820         
5821         if (CanFold) {
5822           Constant *NewCst;
5823           if (Shift->getOpcode() == Instruction::Shl)
5824             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5825           else
5826             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5827           
5828           // Check to see if we are shifting out any of the bits being
5829           // compared.
5830           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5831             // If we shifted bits out, the fold is not going to work out.
5832             // As a special case, check to see if this means that the
5833             // result is always true or false now.
5834             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5835               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5836             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5837               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5838           } else {
5839             ICI.setOperand(1, NewCst);
5840             Constant *NewAndCST;
5841             if (Shift->getOpcode() == Instruction::Shl)
5842               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5843             else
5844               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5845             LHSI->setOperand(1, NewAndCST);
5846             LHSI->setOperand(0, Shift->getOperand(0));
5847             AddToWorkList(Shift); // Shift is dead.
5848             AddUsesToWorkList(ICI);
5849             return &ICI;
5850           }
5851         }
5852       }
5853       
5854       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5855       // preferable because it allows the C<<Y expression to be hoisted out
5856       // of a loop if Y is invariant and X is not.
5857       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5858           ICI.isEquality() && !Shift->isArithmeticShift() &&
5859           isa<Instruction>(Shift->getOperand(0))) {
5860         // Compute C << Y.
5861         Value *NS;
5862         if (Shift->getOpcode() == Instruction::LShr) {
5863           NS = BinaryOperator::CreateShl(AndCST, 
5864                                          Shift->getOperand(1), "tmp");
5865         } else {
5866           // Insert a logical shift.
5867           NS = BinaryOperator::CreateLShr(AndCST,
5868                                           Shift->getOperand(1), "tmp");
5869         }
5870         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5871         
5872         // Compute X & (C << Y).
5873         Instruction *NewAnd = 
5874           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5875         InsertNewInstBefore(NewAnd, ICI);
5876         
5877         ICI.setOperand(0, NewAnd);
5878         return &ICI;
5879       }
5880     }
5881     break;
5882     
5883   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5884     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5885     if (!ShAmt) break;
5886     
5887     uint32_t TypeBits = RHSV.getBitWidth();
5888     
5889     // Check that the shift amount is in range.  If not, don't perform
5890     // undefined shifts.  When the shift is visited it will be
5891     // simplified.
5892     if (ShAmt->uge(TypeBits))
5893       break;
5894     
5895     if (ICI.isEquality()) {
5896       // If we are comparing against bits always shifted out, the
5897       // comparison cannot succeed.
5898       Constant *Comp =
5899         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5900       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5901         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5902         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5903         return ReplaceInstUsesWith(ICI, Cst);
5904       }
5905       
5906       if (LHSI->hasOneUse()) {
5907         // Otherwise strength reduce the shift into an and.
5908         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5909         Constant *Mask =
5910           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5911         
5912         Instruction *AndI =
5913           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5914                                     Mask, LHSI->getName()+".mask");
5915         Value *And = InsertNewInstBefore(AndI, ICI);
5916         return new ICmpInst(ICI.getPredicate(), And,
5917                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5918       }
5919     }
5920     
5921     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5922     bool TrueIfSigned = false;
5923     if (LHSI->hasOneUse() &&
5924         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5925       // (X << 31) <s 0  --> (X&1) != 0
5926       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5927                                            (TypeBits-ShAmt->getZExtValue()-1));
5928       Instruction *AndI =
5929         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5930                                   Mask, LHSI->getName()+".mask");
5931       Value *And = InsertNewInstBefore(AndI, ICI);
5932       
5933       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5934                           And, Constant::getNullValue(And->getType()));
5935     }
5936     break;
5937   }
5938     
5939   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5940   case Instruction::AShr: {
5941     // Only handle equality comparisons of shift-by-constant.
5942     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5943     if (!ShAmt || !ICI.isEquality()) break;
5944
5945     // Check that the shift amount is in range.  If not, don't perform
5946     // undefined shifts.  When the shift is visited it will be
5947     // simplified.
5948     uint32_t TypeBits = RHSV.getBitWidth();
5949     if (ShAmt->uge(TypeBits))
5950       break;
5951     
5952     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5953       
5954     // If we are comparing against bits always shifted out, the
5955     // comparison cannot succeed.
5956     APInt Comp = RHSV << ShAmtVal;
5957     if (LHSI->getOpcode() == Instruction::LShr)
5958       Comp = Comp.lshr(ShAmtVal);
5959     else
5960       Comp = Comp.ashr(ShAmtVal);
5961     
5962     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5963       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5964       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5965       return ReplaceInstUsesWith(ICI, Cst);
5966     }
5967     
5968     // Otherwise, check to see if the bits shifted out are known to be zero.
5969     // If so, we can compare against the unshifted value:
5970     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5971     if (LHSI->hasOneUse() &&
5972         MaskedValueIsZero(LHSI->getOperand(0), 
5973                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5974       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5975                           ConstantExpr::getShl(RHS, ShAmt));
5976     }
5977       
5978     if (LHSI->hasOneUse()) {
5979       // Otherwise strength reduce the shift into an and.
5980       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5981       Constant *Mask = ConstantInt::get(Val);
5982       
5983       Instruction *AndI =
5984         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5985                                   Mask, LHSI->getName()+".mask");
5986       Value *And = InsertNewInstBefore(AndI, ICI);
5987       return new ICmpInst(ICI.getPredicate(), And,
5988                           ConstantExpr::getShl(RHS, ShAmt));
5989     }
5990     break;
5991   }
5992     
5993   case Instruction::SDiv:
5994   case Instruction::UDiv:
5995     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5996     // Fold this div into the comparison, producing a range check. 
5997     // Determine, based on the divide type, what the range is being 
5998     // checked.  If there is an overflow on the low or high side, remember 
5999     // it, otherwise compute the range [low, hi) bounding the new value.
6000     // See: InsertRangeTest above for the kinds of replacements possible.
6001     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6002       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6003                                           DivRHS))
6004         return R;
6005     break;
6006
6007   case Instruction::Add:
6008     // Fold: icmp pred (add, X, C1), C2
6009
6010     if (!ICI.isEquality()) {
6011       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6012       if (!LHSC) break;
6013       const APInt &LHSV = LHSC->getValue();
6014
6015       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6016                             .subtract(LHSV);
6017
6018       if (ICI.isSignedPredicate()) {
6019         if (CR.getLower().isSignBit()) {
6020           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6021                               ConstantInt::get(CR.getUpper()));
6022         } else if (CR.getUpper().isSignBit()) {
6023           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6024                               ConstantInt::get(CR.getLower()));
6025         }
6026       } else {
6027         if (CR.getLower().isMinValue()) {
6028           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6029                               ConstantInt::get(CR.getUpper()));
6030         } else if (CR.getUpper().isMinValue()) {
6031           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6032                               ConstantInt::get(CR.getLower()));
6033         }
6034       }
6035     }
6036     break;
6037   }
6038   
6039   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6040   if (ICI.isEquality()) {
6041     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6042     
6043     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6044     // the second operand is a constant, simplify a bit.
6045     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6046       switch (BO->getOpcode()) {
6047       case Instruction::SRem:
6048         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6049         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6050           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6051           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6052             Instruction *NewRem =
6053               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6054                                          BO->getName());
6055             InsertNewInstBefore(NewRem, ICI);
6056             return new ICmpInst(ICI.getPredicate(), NewRem, 
6057                                 Constant::getNullValue(BO->getType()));
6058           }
6059         }
6060         break;
6061       case Instruction::Add:
6062         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6063         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6064           if (BO->hasOneUse())
6065             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6066                                 Subtract(RHS, BOp1C));
6067         } else if (RHSV == 0) {
6068           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6069           // efficiently invertible, or if the add has just this one use.
6070           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6071           
6072           if (Value *NegVal = dyn_castNegVal(BOp1))
6073             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6074           else if (Value *NegVal = dyn_castNegVal(BOp0))
6075             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6076           else if (BO->hasOneUse()) {
6077             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6078             InsertNewInstBefore(Neg, ICI);
6079             Neg->takeName(BO);
6080             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6081           }
6082         }
6083         break;
6084       case Instruction::Xor:
6085         // For the xor case, we can xor two constants together, eliminating
6086         // the explicit xor.
6087         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6088           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6089                               ConstantExpr::getXor(RHS, BOC));
6090         
6091         // FALLTHROUGH
6092       case Instruction::Sub:
6093         // Replace (([sub|xor] A, B) != 0) with (A != B)
6094         if (RHSV == 0)
6095           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6096                               BO->getOperand(1));
6097         break;
6098         
6099       case Instruction::Or:
6100         // If bits are being or'd in that are not present in the constant we
6101         // are comparing against, then the comparison could never succeed!
6102         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6103           Constant *NotCI = ConstantExpr::getNot(RHS);
6104           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6105             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6106                                                              isICMP_NE));
6107         }
6108         break;
6109         
6110       case Instruction::And:
6111         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6112           // If bits are being compared against that are and'd out, then the
6113           // comparison can never succeed!
6114           if ((RHSV & ~BOC->getValue()) != 0)
6115             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6116                                                              isICMP_NE));
6117           
6118           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6119           if (RHS == BOC && RHSV.isPowerOf2())
6120             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6121                                 ICmpInst::ICMP_NE, LHSI,
6122                                 Constant::getNullValue(RHS->getType()));
6123           
6124           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6125           if (BOC->getValue().isSignBit()) {
6126             Value *X = BO->getOperand(0);
6127             Constant *Zero = Constant::getNullValue(X->getType());
6128             ICmpInst::Predicate pred = isICMP_NE ? 
6129               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6130             return new ICmpInst(pred, X, Zero);
6131           }
6132           
6133           // ((X & ~7) == 0) --> X < 8
6134           if (RHSV == 0 && isHighOnes(BOC)) {
6135             Value *X = BO->getOperand(0);
6136             Constant *NegX = ConstantExpr::getNeg(BOC);
6137             ICmpInst::Predicate pred = isICMP_NE ? 
6138               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6139             return new ICmpInst(pred, X, NegX);
6140           }
6141         }
6142       default: break;
6143       }
6144     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6145       // Handle icmp {eq|ne} <intrinsic>, intcst.
6146       if (II->getIntrinsicID() == Intrinsic::bswap) {
6147         AddToWorkList(II);
6148         ICI.setOperand(0, II->getOperand(1));
6149         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6150         return &ICI;
6151       }
6152     }
6153   } else {  // Not a ICMP_EQ/ICMP_NE
6154             // If the LHS is a cast from an integral value of the same size, 
6155             // then since we know the RHS is a constant, try to simlify.
6156     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6157       Value *CastOp = Cast->getOperand(0);
6158       const Type *SrcTy = CastOp->getType();
6159       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6160       if (SrcTy->isInteger() && 
6161           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6162         // If this is an unsigned comparison, try to make the comparison use
6163         // smaller constant values.
6164         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6165           // X u< 128 => X s> -1
6166           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6167                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6168         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6169                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6170           // X u> 127 => X s< 0
6171           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6172                               Constant::getNullValue(SrcTy));
6173         }
6174       }
6175     }
6176   }
6177   return 0;
6178 }
6179
6180 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6181 /// We only handle extending casts so far.
6182 ///
6183 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6184   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6185   Value *LHSCIOp        = LHSCI->getOperand(0);
6186   const Type *SrcTy     = LHSCIOp->getType();
6187   const Type *DestTy    = LHSCI->getType();
6188   Value *RHSCIOp;
6189
6190   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6191   // integer type is the same size as the pointer type.
6192   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6193       getTargetData().getPointerSizeInBits() == 
6194          cast<IntegerType>(DestTy)->getBitWidth()) {
6195     Value *RHSOp = 0;
6196     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6197       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6198     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6199       RHSOp = RHSC->getOperand(0);
6200       // If the pointer types don't match, insert a bitcast.
6201       if (LHSCIOp->getType() != RHSOp->getType())
6202         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6203     }
6204
6205     if (RHSOp)
6206       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6207   }
6208   
6209   // The code below only handles extension cast instructions, so far.
6210   // Enforce this.
6211   if (LHSCI->getOpcode() != Instruction::ZExt &&
6212       LHSCI->getOpcode() != Instruction::SExt)
6213     return 0;
6214
6215   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6216   bool isSignedCmp = ICI.isSignedPredicate();
6217
6218   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6219     // Not an extension from the same type?
6220     RHSCIOp = CI->getOperand(0);
6221     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6222       return 0;
6223     
6224     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6225     // and the other is a zext), then we can't handle this.
6226     if (CI->getOpcode() != LHSCI->getOpcode())
6227       return 0;
6228
6229     // Deal with equality cases early.
6230     if (ICI.isEquality())
6231       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6232
6233     // A signed comparison of sign extended values simplifies into a
6234     // signed comparison.
6235     if (isSignedCmp && isSignedExt)
6236       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6237
6238     // The other three cases all fold into an unsigned comparison.
6239     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6240   }
6241
6242   // If we aren't dealing with a constant on the RHS, exit early
6243   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6244   if (!CI)
6245     return 0;
6246
6247   // Compute the constant that would happen if we truncated to SrcTy then
6248   // reextended to DestTy.
6249   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6250   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6251
6252   // If the re-extended constant didn't change...
6253   if (Res2 == CI) {
6254     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6255     // For example, we might have:
6256     //    %A = sext short %X to uint
6257     //    %B = icmp ugt uint %A, 1330
6258     // It is incorrect to transform this into 
6259     //    %B = icmp ugt short %X, 1330 
6260     // because %A may have negative value. 
6261     //
6262     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6263     // OR operation is EQ/NE.
6264     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6265       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6266     else
6267       return 0;
6268   }
6269
6270   // The re-extended constant changed so the constant cannot be represented 
6271   // in the shorter type. Consequently, we cannot emit a simple comparison.
6272
6273   // First, handle some easy cases. We know the result cannot be equal at this
6274   // point so handle the ICI.isEquality() cases
6275   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6276     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6277   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6278     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6279
6280   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6281   // should have been folded away previously and not enter in here.
6282   Value *Result;
6283   if (isSignedCmp) {
6284     // We're performing a signed comparison.
6285     if (cast<ConstantInt>(CI)->getValue().isNegative())
6286       Result = ConstantInt::getFalse();          // X < (small) --> false
6287     else
6288       Result = ConstantInt::getTrue();           // X < (large) --> true
6289   } else {
6290     // We're performing an unsigned comparison.
6291     if (isSignedExt) {
6292       // We're performing an unsigned comp with a sign extended value.
6293       // This is true if the input is >= 0. [aka >s -1]
6294       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6295       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6296                                    NegOne, ICI.getName()), ICI);
6297     } else {
6298       // Unsigned extend & unsigned compare -> always true.
6299       Result = ConstantInt::getTrue();
6300     }
6301   }
6302
6303   // Finally, return the value computed.
6304   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6305       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6306     return ReplaceInstUsesWith(ICI, Result);
6307   } else {
6308     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6309             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6310            "ICmp should be folded!");
6311     if (Constant *CI = dyn_cast<Constant>(Result))
6312       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6313     else
6314       return BinaryOperator::CreateNot(Result);
6315   }
6316 }
6317
6318 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6319   return commonShiftTransforms(I);
6320 }
6321
6322 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6323   return commonShiftTransforms(I);
6324 }
6325
6326 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6327   if (Instruction *R = commonShiftTransforms(I))
6328     return R;
6329   
6330   Value *Op0 = I.getOperand(0);
6331   
6332   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6333   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6334     if (CSI->isAllOnesValue())
6335       return ReplaceInstUsesWith(I, CSI);
6336   
6337   // See if we can turn a signed shr into an unsigned shr.
6338   if (MaskedValueIsZero(Op0, 
6339                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6340     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6341   
6342   return 0;
6343 }
6344
6345 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6346   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6347   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6348
6349   // shl X, 0 == X and shr X, 0 == X
6350   // shl 0, X == 0 and shr 0, X == 0
6351   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6352       Op0 == Constant::getNullValue(Op0->getType()))
6353     return ReplaceInstUsesWith(I, Op0);
6354   
6355   if (isa<UndefValue>(Op0)) {            
6356     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6357       return ReplaceInstUsesWith(I, Op0);
6358     else                                    // undef << X -> 0, undef >>u X -> 0
6359       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6360   }
6361   if (isa<UndefValue>(Op1)) {
6362     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6363       return ReplaceInstUsesWith(I, Op0);          
6364     else                                     // X << undef, X >>u undef -> 0
6365       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6366   }
6367
6368   // Try to fold constant and into select arguments.
6369   if (isa<Constant>(Op0))
6370     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6371       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6372         return R;
6373
6374   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6375     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6376       return Res;
6377   return 0;
6378 }
6379
6380 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6381                                                BinaryOperator &I) {
6382   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6383
6384   // See if we can simplify any instructions used by the instruction whose sole 
6385   // purpose is to compute bits we don't care about.
6386   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6387   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6388   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6389                            KnownZero, KnownOne))
6390     return &I;
6391   
6392   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6393   // of a signed value.
6394   //
6395   if (Op1->uge(TypeBits)) {
6396     if (I.getOpcode() != Instruction::AShr)
6397       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6398     else {
6399       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6400       return &I;
6401     }
6402   }
6403   
6404   // ((X*C1) << C2) == (X * (C1 << C2))
6405   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6406     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6407       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6408         return BinaryOperator::CreateMul(BO->getOperand(0),
6409                                          ConstantExpr::getShl(BOOp, Op1));
6410   
6411   // Try to fold constant and into select arguments.
6412   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6413     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6414       return R;
6415   if (isa<PHINode>(Op0))
6416     if (Instruction *NV = FoldOpIntoPhi(I))
6417       return NV;
6418   
6419   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6420   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6421     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6422     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6423     // place.  Don't try to do this transformation in this case.  Also, we
6424     // require that the input operand is a shift-by-constant so that we have
6425     // confidence that the shifts will get folded together.  We could do this
6426     // xform in more cases, but it is unlikely to be profitable.
6427     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6428         isa<ConstantInt>(TrOp->getOperand(1))) {
6429       // Okay, we'll do this xform.  Make the shift of shift.
6430       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6431       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6432                                                 I.getName());
6433       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6434
6435       // For logical shifts, the truncation has the effect of making the high
6436       // part of the register be zeros.  Emulate this by inserting an AND to
6437       // clear the top bits as needed.  This 'and' will usually be zapped by
6438       // other xforms later if dead.
6439       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6440       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6441       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6442       
6443       // The mask we constructed says what the trunc would do if occurring
6444       // between the shifts.  We want to know the effect *after* the second
6445       // shift.  We know that it is a logical shift by a constant, so adjust the
6446       // mask as appropriate.
6447       if (I.getOpcode() == Instruction::Shl)
6448         MaskV <<= Op1->getZExtValue();
6449       else {
6450         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6451         MaskV = MaskV.lshr(Op1->getZExtValue());
6452       }
6453
6454       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6455                                                    TI->getName());
6456       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6457
6458       // Return the value truncated to the interesting size.
6459       return new TruncInst(And, I.getType());
6460     }
6461   }
6462   
6463   if (Op0->hasOneUse()) {
6464     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6465       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6466       Value *V1, *V2;
6467       ConstantInt *CC;
6468       switch (Op0BO->getOpcode()) {
6469         default: break;
6470         case Instruction::Add:
6471         case Instruction::And:
6472         case Instruction::Or:
6473         case Instruction::Xor: {
6474           // These operators commute.
6475           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6476           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6477               match(Op0BO->getOperand(1),
6478                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6479             Instruction *YS = BinaryOperator::CreateShl(
6480                                             Op0BO->getOperand(0), Op1,
6481                                             Op0BO->getName());
6482             InsertNewInstBefore(YS, I); // (Y << C)
6483             Instruction *X = 
6484               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6485                                      Op0BO->getOperand(1)->getName());
6486             InsertNewInstBefore(X, I);  // (X + (Y << C))
6487             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6488             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6489                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6490           }
6491           
6492           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6493           Value *Op0BOOp1 = Op0BO->getOperand(1);
6494           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6495               match(Op0BOOp1, 
6496                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6497               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6498               V2 == Op1) {
6499             Instruction *YS = BinaryOperator::CreateShl(
6500                                                      Op0BO->getOperand(0), Op1,
6501                                                      Op0BO->getName());
6502             InsertNewInstBefore(YS, I); // (Y << C)
6503             Instruction *XM =
6504               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6505                                         V1->getName()+".mask");
6506             InsertNewInstBefore(XM, I); // X & (CC << C)
6507             
6508             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6509           }
6510         }
6511           
6512         // FALL THROUGH.
6513         case Instruction::Sub: {
6514           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6515           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6516               match(Op0BO->getOperand(0),
6517                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6518             Instruction *YS = BinaryOperator::CreateShl(
6519                                                      Op0BO->getOperand(1), Op1,
6520                                                      Op0BO->getName());
6521             InsertNewInstBefore(YS, I); // (Y << C)
6522             Instruction *X =
6523               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6524                                      Op0BO->getOperand(0)->getName());
6525             InsertNewInstBefore(X, I);  // (X + (Y << C))
6526             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6527             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6528                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6529           }
6530           
6531           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6532           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6533               match(Op0BO->getOperand(0),
6534                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6535                           m_ConstantInt(CC))) && V2 == Op1 &&
6536               cast<BinaryOperator>(Op0BO->getOperand(0))
6537                   ->getOperand(0)->hasOneUse()) {
6538             Instruction *YS = BinaryOperator::CreateShl(
6539                                                      Op0BO->getOperand(1), Op1,
6540                                                      Op0BO->getName());
6541             InsertNewInstBefore(YS, I); // (Y << C)
6542             Instruction *XM =
6543               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6544                                         V1->getName()+".mask");
6545             InsertNewInstBefore(XM, I); // X & (CC << C)
6546             
6547             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6548           }
6549           
6550           break;
6551         }
6552       }
6553       
6554       
6555       // If the operand is an bitwise operator with a constant RHS, and the
6556       // shift is the only use, we can pull it out of the shift.
6557       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6558         bool isValid = true;     // Valid only for And, Or, Xor
6559         bool highBitSet = false; // Transform if high bit of constant set?
6560         
6561         switch (Op0BO->getOpcode()) {
6562           default: isValid = false; break;   // Do not perform transform!
6563           case Instruction::Add:
6564             isValid = isLeftShift;
6565             break;
6566           case Instruction::Or:
6567           case Instruction::Xor:
6568             highBitSet = false;
6569             break;
6570           case Instruction::And:
6571             highBitSet = true;
6572             break;
6573         }
6574         
6575         // If this is a signed shift right, and the high bit is modified
6576         // by the logical operation, do not perform the transformation.
6577         // The highBitSet boolean indicates the value of the high bit of
6578         // the constant which would cause it to be modified for this
6579         // operation.
6580         //
6581         if (isValid && I.getOpcode() == Instruction::AShr)
6582           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6583         
6584         if (isValid) {
6585           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6586           
6587           Instruction *NewShift =
6588             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6589           InsertNewInstBefore(NewShift, I);
6590           NewShift->takeName(Op0BO);
6591           
6592           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6593                                         NewRHS);
6594         }
6595       }
6596     }
6597   }
6598   
6599   // Find out if this is a shift of a shift by a constant.
6600   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6601   if (ShiftOp && !ShiftOp->isShift())
6602     ShiftOp = 0;
6603   
6604   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6605     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6606     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6607     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6608     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6609     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6610     Value *X = ShiftOp->getOperand(0);
6611     
6612     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6613     if (AmtSum > TypeBits)
6614       AmtSum = TypeBits;
6615     
6616     const IntegerType *Ty = cast<IntegerType>(I.getType());
6617     
6618     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6619     if (I.getOpcode() == ShiftOp->getOpcode()) {
6620       return BinaryOperator::Create(I.getOpcode(), X,
6621                                     ConstantInt::get(Ty, AmtSum));
6622     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6623                I.getOpcode() == Instruction::AShr) {
6624       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6625       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6626     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6627                I.getOpcode() == Instruction::LShr) {
6628       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6629       Instruction *Shift =
6630         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6631       InsertNewInstBefore(Shift, I);
6632
6633       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6634       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6635     }
6636     
6637     // Okay, if we get here, one shift must be left, and the other shift must be
6638     // right.  See if the amounts are equal.
6639     if (ShiftAmt1 == ShiftAmt2) {
6640       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6641       if (I.getOpcode() == Instruction::Shl) {
6642         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6643         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6644       }
6645       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6646       if (I.getOpcode() == Instruction::LShr) {
6647         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6648         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6649       }
6650       // We can simplify ((X << C) >>s C) into a trunc + sext.
6651       // NOTE: we could do this for any C, but that would make 'unusual' integer
6652       // types.  For now, just stick to ones well-supported by the code
6653       // generators.
6654       const Type *SExtType = 0;
6655       switch (Ty->getBitWidth() - ShiftAmt1) {
6656       case 1  :
6657       case 8  :
6658       case 16 :
6659       case 32 :
6660       case 64 :
6661       case 128:
6662         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6663         break;
6664       default: break;
6665       }
6666       if (SExtType) {
6667         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6668         InsertNewInstBefore(NewTrunc, I);
6669         return new SExtInst(NewTrunc, Ty);
6670       }
6671       // Otherwise, we can't handle it yet.
6672     } else if (ShiftAmt1 < ShiftAmt2) {
6673       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6674       
6675       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6676       if (I.getOpcode() == Instruction::Shl) {
6677         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6678                ShiftOp->getOpcode() == Instruction::AShr);
6679         Instruction *Shift =
6680           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6681         InsertNewInstBefore(Shift, I);
6682         
6683         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6684         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6685       }
6686       
6687       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6688       if (I.getOpcode() == Instruction::LShr) {
6689         assert(ShiftOp->getOpcode() == Instruction::Shl);
6690         Instruction *Shift =
6691           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6692         InsertNewInstBefore(Shift, I);
6693         
6694         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6695         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6696       }
6697       
6698       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6699     } else {
6700       assert(ShiftAmt2 < ShiftAmt1);
6701       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6702
6703       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6704       if (I.getOpcode() == Instruction::Shl) {
6705         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6706                ShiftOp->getOpcode() == Instruction::AShr);
6707         Instruction *Shift =
6708           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6709                                  ConstantInt::get(Ty, ShiftDiff));
6710         InsertNewInstBefore(Shift, I);
6711         
6712         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6713         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6714       }
6715       
6716       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6717       if (I.getOpcode() == Instruction::LShr) {
6718         assert(ShiftOp->getOpcode() == Instruction::Shl);
6719         Instruction *Shift =
6720           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6721         InsertNewInstBefore(Shift, I);
6722         
6723         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6724         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6725       }
6726       
6727       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6728     }
6729   }
6730   return 0;
6731 }
6732
6733
6734 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6735 /// expression.  If so, decompose it, returning some value X, such that Val is
6736 /// X*Scale+Offset.
6737 ///
6738 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6739                                         int &Offset) {
6740   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6741   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6742     Offset = CI->getZExtValue();
6743     Scale  = 0;
6744     return ConstantInt::get(Type::Int32Ty, 0);
6745   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6746     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6747       if (I->getOpcode() == Instruction::Shl) {
6748         // This is a value scaled by '1 << the shift amt'.
6749         Scale = 1U << RHS->getZExtValue();
6750         Offset = 0;
6751         return I->getOperand(0);
6752       } else if (I->getOpcode() == Instruction::Mul) {
6753         // This value is scaled by 'RHS'.
6754         Scale = RHS->getZExtValue();
6755         Offset = 0;
6756         return I->getOperand(0);
6757       } else if (I->getOpcode() == Instruction::Add) {
6758         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6759         // where C1 is divisible by C2.
6760         unsigned SubScale;
6761         Value *SubVal = 
6762           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6763         Offset += RHS->getZExtValue();
6764         Scale = SubScale;
6765         return SubVal;
6766       }
6767     }
6768   }
6769
6770   // Otherwise, we can't look past this.
6771   Scale = 1;
6772   Offset = 0;
6773   return Val;
6774 }
6775
6776
6777 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6778 /// try to eliminate the cast by moving the type information into the alloc.
6779 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6780                                                    AllocationInst &AI) {
6781   const PointerType *PTy = cast<PointerType>(CI.getType());
6782   
6783   // Remove any uses of AI that are dead.
6784   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6785   
6786   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6787     Instruction *User = cast<Instruction>(*UI++);
6788     if (isInstructionTriviallyDead(User)) {
6789       while (UI != E && *UI == User)
6790         ++UI; // If this instruction uses AI more than once, don't break UI.
6791       
6792       ++NumDeadInst;
6793       DOUT << "IC: DCE: " << *User;
6794       EraseInstFromFunction(*User);
6795     }
6796   }
6797   
6798   // Get the type really allocated and the type casted to.
6799   const Type *AllocElTy = AI.getAllocatedType();
6800   const Type *CastElTy = PTy->getElementType();
6801   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6802
6803   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6804   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6805   if (CastElTyAlign < AllocElTyAlign) return 0;
6806
6807   // If the allocation has multiple uses, only promote it if we are strictly
6808   // increasing the alignment of the resultant allocation.  If we keep it the
6809   // same, we open the door to infinite loops of various kinds.
6810   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6811
6812   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6813   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6814   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6815
6816   // See if we can satisfy the modulus by pulling a scale out of the array
6817   // size argument.
6818   unsigned ArraySizeScale;
6819   int ArrayOffset;
6820   Value *NumElements = // See if the array size is a decomposable linear expr.
6821     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6822  
6823   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6824   // do the xform.
6825   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6826       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6827
6828   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6829   Value *Amt = 0;
6830   if (Scale == 1) {
6831     Amt = NumElements;
6832   } else {
6833     // If the allocation size is constant, form a constant mul expression
6834     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6835     if (isa<ConstantInt>(NumElements))
6836       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6837     // otherwise multiply the amount and the number of elements
6838     else if (Scale != 1) {
6839       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6840       Amt = InsertNewInstBefore(Tmp, AI);
6841     }
6842   }
6843   
6844   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6845     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6846     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6847     Amt = InsertNewInstBefore(Tmp, AI);
6848   }
6849   
6850   AllocationInst *New;
6851   if (isa<MallocInst>(AI))
6852     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6853   else
6854     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6855   InsertNewInstBefore(New, AI);
6856   New->takeName(&AI);
6857   
6858   // If the allocation has multiple uses, insert a cast and change all things
6859   // that used it to use the new cast.  This will also hack on CI, but it will
6860   // die soon.
6861   if (!AI.hasOneUse()) {
6862     AddUsesToWorkList(AI);
6863     // New is the allocation instruction, pointer typed. AI is the original
6864     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6865     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6866     InsertNewInstBefore(NewCast, AI);
6867     AI.replaceAllUsesWith(NewCast);
6868   }
6869   return ReplaceInstUsesWith(CI, New);
6870 }
6871
6872 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6873 /// and return it as type Ty without inserting any new casts and without
6874 /// changing the computed value.  This is used by code that tries to decide
6875 /// whether promoting or shrinking integer operations to wider or smaller types
6876 /// will allow us to eliminate a truncate or extend.
6877 ///
6878 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6879 /// extension operation if Ty is larger.
6880 ///
6881 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6882 /// should return true if trunc(V) can be computed by computing V in the smaller
6883 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6884 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6885 /// efficiently truncated.
6886 ///
6887 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6888 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6889 /// the final result.
6890 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6891                                               unsigned CastOpc,
6892                                               int &NumCastsRemoved) {
6893   // We can always evaluate constants in another type.
6894   if (isa<ConstantInt>(V))
6895     return true;
6896   
6897   Instruction *I = dyn_cast<Instruction>(V);
6898   if (!I) return false;
6899   
6900   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6901   
6902   // If this is an extension or truncate, we can often eliminate it.
6903   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6904     // If this is a cast from the destination type, we can trivially eliminate
6905     // it, and this will remove a cast overall.
6906     if (I->getOperand(0)->getType() == Ty) {
6907       // If the first operand is itself a cast, and is eliminable, do not count
6908       // this as an eliminable cast.  We would prefer to eliminate those two
6909       // casts first.
6910       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6911         ++NumCastsRemoved;
6912       return true;
6913     }
6914   }
6915
6916   // We can't extend or shrink something that has multiple uses: doing so would
6917   // require duplicating the instruction in general, which isn't profitable.
6918   if (!I->hasOneUse()) return false;
6919
6920   switch (I->getOpcode()) {
6921   case Instruction::Add:
6922   case Instruction::Sub:
6923   case Instruction::And:
6924   case Instruction::Or:
6925   case Instruction::Xor:
6926     // These operators can all arbitrarily be extended or truncated.
6927     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6928                                       NumCastsRemoved) &&
6929            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6930                                       NumCastsRemoved);
6931
6932   case Instruction::Mul:
6933     // A multiply can be truncated by truncating its operands.
6934     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6935            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6936                                       NumCastsRemoved) &&
6937            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6938                                       NumCastsRemoved);
6939
6940   case Instruction::Shl:
6941     // If we are truncating the result of this SHL, and if it's a shift of a
6942     // constant amount, we can always perform a SHL in a smaller type.
6943     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6944       uint32_t BitWidth = Ty->getBitWidth();
6945       if (BitWidth < OrigTy->getBitWidth() && 
6946           CI->getLimitedValue(BitWidth) < BitWidth)
6947         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6948                                           NumCastsRemoved);
6949     }
6950     break;
6951   case Instruction::LShr:
6952     // If this is a truncate of a logical shr, we can truncate it to a smaller
6953     // lshr iff we know that the bits we would otherwise be shifting in are
6954     // already zeros.
6955     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6956       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6957       uint32_t BitWidth = Ty->getBitWidth();
6958       if (BitWidth < OrigBitWidth &&
6959           MaskedValueIsZero(I->getOperand(0),
6960             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6961           CI->getLimitedValue(BitWidth) < BitWidth) {
6962         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6963                                           NumCastsRemoved);
6964       }
6965     }
6966     break;
6967   case Instruction::ZExt:
6968   case Instruction::SExt:
6969   case Instruction::Trunc:
6970     // If this is the same kind of case as our original (e.g. zext+zext), we
6971     // can safely replace it.  Note that replacing it does not reduce the number
6972     // of casts in the input.
6973     if (I->getOpcode() == CastOpc)
6974       return true;
6975     break;
6976       
6977   case Instruction::PHI: {
6978     // We can change a phi if we can change all operands.
6979     PHINode *PN = cast<PHINode>(I);
6980     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6981       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6982                                       NumCastsRemoved))
6983         return false;
6984     return true;
6985   }
6986   default:
6987     // TODO: Can handle more cases here.
6988     break;
6989   }
6990   
6991   return false;
6992 }
6993
6994 /// EvaluateInDifferentType - Given an expression that 
6995 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6996 /// evaluate the expression.
6997 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6998                                              bool isSigned) {
6999   if (Constant *C = dyn_cast<Constant>(V))
7000     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7001
7002   // Otherwise, it must be an instruction.
7003   Instruction *I = cast<Instruction>(V);
7004   Instruction *Res = 0;
7005   switch (I->getOpcode()) {
7006   case Instruction::Add:
7007   case Instruction::Sub:
7008   case Instruction::Mul:
7009   case Instruction::And:
7010   case Instruction::Or:
7011   case Instruction::Xor:
7012   case Instruction::AShr:
7013   case Instruction::LShr:
7014   case Instruction::Shl: {
7015     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7016     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7017     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7018                                  LHS, RHS);
7019     break;
7020   }    
7021   case Instruction::Trunc:
7022   case Instruction::ZExt:
7023   case Instruction::SExt:
7024     // If the source type of the cast is the type we're trying for then we can
7025     // just return the source.  There's no need to insert it because it is not
7026     // new.
7027     if (I->getOperand(0)->getType() == Ty)
7028       return I->getOperand(0);
7029     
7030     // Otherwise, must be the same type of cast, so just reinsert a new one.
7031     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7032                            Ty);
7033     break;
7034   case Instruction::PHI: {
7035     PHINode *OPN = cast<PHINode>(I);
7036     PHINode *NPN = PHINode::Create(Ty);
7037     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7038       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7039       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7040     }
7041     Res = NPN;
7042     break;
7043   }
7044   default: 
7045     // TODO: Can handle more cases here.
7046     assert(0 && "Unreachable!");
7047     break;
7048   }
7049   
7050   Res->takeName(I);
7051   return InsertNewInstBefore(Res, *I);
7052 }
7053
7054 /// @brief Implement the transforms common to all CastInst visitors.
7055 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7056   Value *Src = CI.getOperand(0);
7057
7058   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7059   // eliminate it now.
7060   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7061     if (Instruction::CastOps opc = 
7062         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7063       // The first cast (CSrc) is eliminable so we need to fix up or replace
7064       // the second cast (CI). CSrc will then have a good chance of being dead.
7065       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7066     }
7067   }
7068
7069   // If we are casting a select then fold the cast into the select
7070   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7071     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7072       return NV;
7073
7074   // If we are casting a PHI then fold the cast into the PHI
7075   if (isa<PHINode>(Src))
7076     if (Instruction *NV = FoldOpIntoPhi(CI))
7077       return NV;
7078   
7079   return 0;
7080 }
7081
7082 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7083 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7084   Value *Src = CI.getOperand(0);
7085   
7086   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7087     // If casting the result of a getelementptr instruction with no offset, turn
7088     // this into a cast of the original pointer!
7089     if (GEP->hasAllZeroIndices()) {
7090       // Changing the cast operand is usually not a good idea but it is safe
7091       // here because the pointer operand is being replaced with another 
7092       // pointer operand so the opcode doesn't need to change.
7093       AddToWorkList(GEP);
7094       CI.setOperand(0, GEP->getOperand(0));
7095       return &CI;
7096     }
7097     
7098     // If the GEP has a single use, and the base pointer is a bitcast, and the
7099     // GEP computes a constant offset, see if we can convert these three
7100     // instructions into fewer.  This typically happens with unions and other
7101     // non-type-safe code.
7102     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7103       if (GEP->hasAllConstantIndices()) {
7104         // We are guaranteed to get a constant from EmitGEPOffset.
7105         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7106         int64_t Offset = OffsetV->getSExtValue();
7107         
7108         // Get the base pointer input of the bitcast, and the type it points to.
7109         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7110         const Type *GEPIdxTy =
7111           cast<PointerType>(OrigBase->getType())->getElementType();
7112         if (GEPIdxTy->isSized()) {
7113           SmallVector<Value*, 8> NewIndices;
7114           
7115           // Start with the index over the outer type.  Note that the type size
7116           // might be zero (even if the offset isn't zero) if the indexed type
7117           // is something like [0 x {int, int}]
7118           const Type *IntPtrTy = TD->getIntPtrType();
7119           int64_t FirstIdx = 0;
7120           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7121             FirstIdx = Offset/TySize;
7122             Offset %= TySize;
7123           
7124             // Handle silly modulus not returning values values [0..TySize).
7125             if (Offset < 0) {
7126               --FirstIdx;
7127               Offset += TySize;
7128               assert(Offset >= 0);
7129             }
7130             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7131           }
7132           
7133           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7134
7135           // Index into the types.  If we fail, set OrigBase to null.
7136           while (Offset) {
7137             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7138               const StructLayout *SL = TD->getStructLayout(STy);
7139               if (Offset < (int64_t)SL->getSizeInBytes()) {
7140                 unsigned Elt = SL->getElementContainingOffset(Offset);
7141                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7142               
7143                 Offset -= SL->getElementOffset(Elt);
7144                 GEPIdxTy = STy->getElementType(Elt);
7145               } else {
7146                 // Otherwise, we can't index into this, bail out.
7147                 Offset = 0;
7148                 OrigBase = 0;
7149               }
7150             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7151               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7152               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7153                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7154                 Offset %= EltSize;
7155               } else {
7156                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7157               }
7158               GEPIdxTy = STy->getElementType();
7159             } else {
7160               // Otherwise, we can't index into this, bail out.
7161               Offset = 0;
7162               OrigBase = 0;
7163             }
7164           }
7165           if (OrigBase) {
7166             // If we were able to index down into an element, create the GEP
7167             // and bitcast the result.  This eliminates one bitcast, potentially
7168             // two.
7169             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7170                                                           NewIndices.begin(),
7171                                                           NewIndices.end(), "");
7172             InsertNewInstBefore(NGEP, CI);
7173             NGEP->takeName(GEP);
7174             
7175             if (isa<BitCastInst>(CI))
7176               return new BitCastInst(NGEP, CI.getType());
7177             assert(isa<PtrToIntInst>(CI));
7178             return new PtrToIntInst(NGEP, CI.getType());
7179           }
7180         }
7181       }      
7182     }
7183   }
7184     
7185   return commonCastTransforms(CI);
7186 }
7187
7188
7189
7190 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7191 /// integer types. This function implements the common transforms for all those
7192 /// cases.
7193 /// @brief Implement the transforms common to CastInst with integer operands
7194 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7195   if (Instruction *Result = commonCastTransforms(CI))
7196     return Result;
7197
7198   Value *Src = CI.getOperand(0);
7199   const Type *SrcTy = Src->getType();
7200   const Type *DestTy = CI.getType();
7201   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7202   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7203
7204   // See if we can simplify any instructions used by the LHS whose sole 
7205   // purpose is to compute bits we don't care about.
7206   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7207   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7208                            KnownZero, KnownOne))
7209     return &CI;
7210
7211   // If the source isn't an instruction or has more than one use then we
7212   // can't do anything more. 
7213   Instruction *SrcI = dyn_cast<Instruction>(Src);
7214   if (!SrcI || !Src->hasOneUse())
7215     return 0;
7216
7217   // Attempt to propagate the cast into the instruction for int->int casts.
7218   int NumCastsRemoved = 0;
7219   if (!isa<BitCastInst>(CI) &&
7220       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7221                                  CI.getOpcode(), NumCastsRemoved)) {
7222     // If this cast is a truncate, evaluting in a different type always
7223     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7224     // we need to do an AND to maintain the clear top-part of the computation,
7225     // so we require that the input have eliminated at least one cast.  If this
7226     // is a sign extension, we insert two new casts (to do the extension) so we
7227     // require that two casts have been eliminated.
7228     bool DoXForm;
7229     switch (CI.getOpcode()) {
7230     default:
7231       // All the others use floating point so we shouldn't actually 
7232       // get here because of the check above.
7233       assert(0 && "Unknown cast type");
7234     case Instruction::Trunc:
7235       DoXForm = true;
7236       break;
7237     case Instruction::ZExt:
7238       DoXForm = NumCastsRemoved >= 1;
7239       break;
7240     case Instruction::SExt:
7241       DoXForm = NumCastsRemoved >= 2;
7242       break;
7243     }
7244     
7245     if (DoXForm) {
7246       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7247                                            CI.getOpcode() == Instruction::SExt);
7248       assert(Res->getType() == DestTy);
7249       switch (CI.getOpcode()) {
7250       default: assert(0 && "Unknown cast type!");
7251       case Instruction::Trunc:
7252       case Instruction::BitCast:
7253         // Just replace this cast with the result.
7254         return ReplaceInstUsesWith(CI, Res);
7255       case Instruction::ZExt: {
7256         // We need to emit an AND to clear the high bits.
7257         assert(SrcBitSize < DestBitSize && "Not a zext?");
7258         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7259                                                             SrcBitSize));
7260         return BinaryOperator::CreateAnd(Res, C);
7261       }
7262       case Instruction::SExt:
7263         // We need to emit a cast to truncate, then a cast to sext.
7264         return CastInst::Create(Instruction::SExt,
7265             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7266                              CI), DestTy);
7267       }
7268     }
7269   }
7270   
7271   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7272   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7273
7274   switch (SrcI->getOpcode()) {
7275   case Instruction::Add:
7276   case Instruction::Mul:
7277   case Instruction::And:
7278   case Instruction::Or:
7279   case Instruction::Xor:
7280     // If we are discarding information, rewrite.
7281     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7282       // Don't insert two casts if they cannot be eliminated.  We allow 
7283       // two casts to be inserted if the sizes are the same.  This could 
7284       // only be converting signedness, which is a noop.
7285       if (DestBitSize == SrcBitSize || 
7286           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7287           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7288         Instruction::CastOps opcode = CI.getOpcode();
7289         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7290         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7291         return BinaryOperator::Create(
7292             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7293       }
7294     }
7295
7296     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7297     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7298         SrcI->getOpcode() == Instruction::Xor &&
7299         Op1 == ConstantInt::getTrue() &&
7300         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7301       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7302       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7303     }
7304     break;
7305   case Instruction::SDiv:
7306   case Instruction::UDiv:
7307   case Instruction::SRem:
7308   case Instruction::URem:
7309     // If we are just changing the sign, rewrite.
7310     if (DestBitSize == SrcBitSize) {
7311       // Don't insert two casts if they cannot be eliminated.  We allow 
7312       // two casts to be inserted if the sizes are the same.  This could 
7313       // only be converting signedness, which is a noop.
7314       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7315           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7316         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7317                                               Op0, DestTy, SrcI);
7318         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7319                                               Op1, DestTy, SrcI);
7320         return BinaryOperator::Create(
7321           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7322       }
7323     }
7324     break;
7325
7326   case Instruction::Shl:
7327     // Allow changing the sign of the source operand.  Do not allow 
7328     // changing the size of the shift, UNLESS the shift amount is a 
7329     // constant.  We must not change variable sized shifts to a smaller 
7330     // size, because it is undefined to shift more bits out than exist 
7331     // in the value.
7332     if (DestBitSize == SrcBitSize ||
7333         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7334       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7335           Instruction::BitCast : Instruction::Trunc);
7336       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7337       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7338       return BinaryOperator::CreateShl(Op0c, Op1c);
7339     }
7340     break;
7341   case Instruction::AShr:
7342     // If this is a signed shr, and if all bits shifted in are about to be
7343     // truncated off, turn it into an unsigned shr to allow greater
7344     // simplifications.
7345     if (DestBitSize < SrcBitSize &&
7346         isa<ConstantInt>(Op1)) {
7347       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7348       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7349         // Insert the new logical shift right.
7350         return BinaryOperator::CreateLShr(Op0, Op1);
7351       }
7352     }
7353     break;
7354   }
7355   return 0;
7356 }
7357
7358 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7359   if (Instruction *Result = commonIntCastTransforms(CI))
7360     return Result;
7361   
7362   Value *Src = CI.getOperand(0);
7363   const Type *Ty = CI.getType();
7364   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7365   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7366   
7367   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7368     switch (SrcI->getOpcode()) {
7369     default: break;
7370     case Instruction::LShr:
7371       // We can shrink lshr to something smaller if we know the bits shifted in
7372       // are already zeros.
7373       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7374         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7375         
7376         // Get a mask for the bits shifting in.
7377         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7378         Value* SrcIOp0 = SrcI->getOperand(0);
7379         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7380           if (ShAmt >= DestBitWidth)        // All zeros.
7381             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7382
7383           // Okay, we can shrink this.  Truncate the input, then return a new
7384           // shift.
7385           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7386           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7387                                        Ty, CI);
7388           return BinaryOperator::CreateLShr(V1, V2);
7389         }
7390       } else {     // This is a variable shr.
7391         
7392         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7393         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7394         // loop-invariant and CSE'd.
7395         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7396           Value *One = ConstantInt::get(SrcI->getType(), 1);
7397
7398           Value *V = InsertNewInstBefore(
7399               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7400                                      "tmp"), CI);
7401           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7402                                                             SrcI->getOperand(0),
7403                                                             "tmp"), CI);
7404           Value *Zero = Constant::getNullValue(V->getType());
7405           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7406         }
7407       }
7408       break;
7409     }
7410   }
7411   
7412   return 0;
7413 }
7414
7415 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7416 /// in order to eliminate the icmp.
7417 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7418                                              bool DoXform) {
7419   // If we are just checking for a icmp eq of a single bit and zext'ing it
7420   // to an integer, then shift the bit to the appropriate place and then
7421   // cast to integer to avoid the comparison.
7422   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7423     const APInt &Op1CV = Op1C->getValue();
7424       
7425     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7426     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7427     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7428         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7429       if (!DoXform) return ICI;
7430
7431       Value *In = ICI->getOperand(0);
7432       Value *Sh = ConstantInt::get(In->getType(),
7433                                    In->getType()->getPrimitiveSizeInBits()-1);
7434       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7435                                                         In->getName()+".lobit"),
7436                                CI);
7437       if (In->getType() != CI.getType())
7438         In = CastInst::CreateIntegerCast(In, CI.getType(),
7439                                          false/*ZExt*/, "tmp", &CI);
7440
7441       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7442         Constant *One = ConstantInt::get(In->getType(), 1);
7443         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7444                                                          In->getName()+".not"),
7445                                  CI);
7446       }
7447
7448       return ReplaceInstUsesWith(CI, In);
7449     }
7450       
7451       
7452       
7453     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7454     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7455     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7456     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7457     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7458     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7459     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7460     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7461     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7462         // This only works for EQ and NE
7463         ICI->isEquality()) {
7464       // If Op1C some other power of two, convert:
7465       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7466       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7467       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7468       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7469         
7470       APInt KnownZeroMask(~KnownZero);
7471       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7472         if (!DoXform) return ICI;
7473
7474         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7475         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7476           // (X&4) == 2 --> false
7477           // (X&4) != 2 --> true
7478           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7479           Res = ConstantExpr::getZExt(Res, CI.getType());
7480           return ReplaceInstUsesWith(CI, Res);
7481         }
7482           
7483         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7484         Value *In = ICI->getOperand(0);
7485         if (ShiftAmt) {
7486           // Perform a logical shr by shiftamt.
7487           // Insert the shift to put the result in the low bit.
7488           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7489                                   ConstantInt::get(In->getType(), ShiftAmt),
7490                                                    In->getName()+".lobit"), CI);
7491         }
7492           
7493         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7494           Constant *One = ConstantInt::get(In->getType(), 1);
7495           In = BinaryOperator::CreateXor(In, One, "tmp");
7496           InsertNewInstBefore(cast<Instruction>(In), CI);
7497         }
7498           
7499         if (CI.getType() == In->getType())
7500           return ReplaceInstUsesWith(CI, In);
7501         else
7502           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7503       }
7504     }
7505   }
7506
7507   return 0;
7508 }
7509
7510 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7511   // If one of the common conversion will work ..
7512   if (Instruction *Result = commonIntCastTransforms(CI))
7513     return Result;
7514
7515   Value *Src = CI.getOperand(0);
7516
7517   // If this is a cast of a cast
7518   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7519     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7520     // types and if the sizes are just right we can convert this into a logical
7521     // 'and' which will be much cheaper than the pair of casts.
7522     if (isa<TruncInst>(CSrc)) {
7523       // Get the sizes of the types involved
7524       Value *A = CSrc->getOperand(0);
7525       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7526       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7527       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7528       // If we're actually extending zero bits and the trunc is a no-op
7529       if (MidSize < DstSize && SrcSize == DstSize) {
7530         // Replace both of the casts with an And of the type mask.
7531         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7532         Constant *AndConst = ConstantInt::get(AndValue);
7533         Instruction *And = 
7534           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7535         // Unfortunately, if the type changed, we need to cast it back.
7536         if (And->getType() != CI.getType()) {
7537           And->setName(CSrc->getName()+".mask");
7538           InsertNewInstBefore(And, CI);
7539           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7540         }
7541         return And;
7542       }
7543     }
7544   }
7545
7546   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7547     return transformZExtICmp(ICI, CI);
7548
7549   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7550   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7551     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7552     // of the (zext icmp) will be transformed.
7553     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7554     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7555     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7556         (transformZExtICmp(LHS, CI, false) ||
7557          transformZExtICmp(RHS, CI, false))) {
7558       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7559       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7560       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7561     }
7562   }
7563
7564   return 0;
7565 }
7566
7567 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7568   if (Instruction *I = commonIntCastTransforms(CI))
7569     return I;
7570   
7571   Value *Src = CI.getOperand(0);
7572   
7573   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7574   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7575   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7576     // If we are just checking for a icmp eq of a single bit and zext'ing it
7577     // to an integer, then shift the bit to the appropriate place and then
7578     // cast to integer to avoid the comparison.
7579     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7580       const APInt &Op1CV = Op1C->getValue();
7581       
7582       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7583       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7584       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7585           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7586         Value *In = ICI->getOperand(0);
7587         Value *Sh = ConstantInt::get(In->getType(),
7588                                      In->getType()->getPrimitiveSizeInBits()-1);
7589         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7590                                                         In->getName()+".lobit"),
7591                                  CI);
7592         if (In->getType() != CI.getType())
7593           In = CastInst::CreateIntegerCast(In, CI.getType(),
7594                                            true/*SExt*/, "tmp", &CI);
7595         
7596         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7597           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7598                                      In->getName()+".not"), CI);
7599         
7600         return ReplaceInstUsesWith(CI, In);
7601       }
7602     }
7603   }
7604
7605   // See if the value being truncated is already sign extended.  If so, just
7606   // eliminate the trunc/sext pair.
7607   if (getOpcode(Src) == Instruction::Trunc) {
7608     Value *Op = cast<User>(Src)->getOperand(0);
7609     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7610     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7611     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7612     unsigned NumSignBits = ComputeNumSignBits(Op);
7613
7614     if (OpBits == DestBits) {
7615       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7616       // bits, it is already ready.
7617       if (NumSignBits > DestBits-MidBits)
7618         return ReplaceInstUsesWith(CI, Op);
7619     } else if (OpBits < DestBits) {
7620       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7621       // bits, just sext from i32.
7622       if (NumSignBits > OpBits-MidBits)
7623         return new SExtInst(Op, CI.getType(), "tmp");
7624     } else {
7625       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7626       // bits, just truncate to i32.
7627       if (NumSignBits > OpBits-MidBits)
7628         return new TruncInst(Op, CI.getType(), "tmp");
7629     }
7630   }
7631       
7632   return 0;
7633 }
7634
7635 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7636 /// in the specified FP type without changing its value.
7637 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7638   APFloat F = CFP->getValueAPF();
7639   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7640     return ConstantFP::get(F);
7641   return 0;
7642 }
7643
7644 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7645 /// through it until we get the source value.
7646 static Value *LookThroughFPExtensions(Value *V) {
7647   if (Instruction *I = dyn_cast<Instruction>(V))
7648     if (I->getOpcode() == Instruction::FPExt)
7649       return LookThroughFPExtensions(I->getOperand(0));
7650   
7651   // If this value is a constant, return the constant in the smallest FP type
7652   // that can accurately represent it.  This allows us to turn
7653   // (float)((double)X+2.0) into x+2.0f.
7654   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7655     if (CFP->getType() == Type::PPC_FP128Ty)
7656       return V;  // No constant folding of this.
7657     // See if the value can be truncated to float and then reextended.
7658     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7659       return V;
7660     if (CFP->getType() == Type::DoubleTy)
7661       return V;  // Won't shrink.
7662     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7663       return V;
7664     // Don't try to shrink to various long double types.
7665   }
7666   
7667   return V;
7668 }
7669
7670 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7671   if (Instruction *I = commonCastTransforms(CI))
7672     return I;
7673   
7674   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7675   // smaller than the destination type, we can eliminate the truncate by doing
7676   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7677   // many builtins (sqrt, etc).
7678   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7679   if (OpI && OpI->hasOneUse()) {
7680     switch (OpI->getOpcode()) {
7681     default: break;
7682     case Instruction::Add:
7683     case Instruction::Sub:
7684     case Instruction::Mul:
7685     case Instruction::FDiv:
7686     case Instruction::FRem:
7687       const Type *SrcTy = OpI->getType();
7688       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7689       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7690       if (LHSTrunc->getType() != SrcTy && 
7691           RHSTrunc->getType() != SrcTy) {
7692         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7693         // If the source types were both smaller than the destination type of
7694         // the cast, do this xform.
7695         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7696             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7697           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7698                                       CI.getType(), CI);
7699           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7700                                       CI.getType(), CI);
7701           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7702         }
7703       }
7704       break;  
7705     }
7706   }
7707   return 0;
7708 }
7709
7710 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7711   return commonCastTransforms(CI);
7712 }
7713
7714 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7715   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7716   // mantissa to accurately represent all values of X.  For example, do not
7717   // do this with i64->float->i64.
7718   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7719     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7720         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7721                     SrcI->getType()->getFPMantissaWidth())
7722       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7723
7724   return commonCastTransforms(FI);
7725 }
7726
7727 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7728   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7729   // mantissa to accurately represent all values of X.  For example, do not
7730   // do this with i64->float->i64.
7731   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7732     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7733         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7734                     SrcI->getType()->getFPMantissaWidth())
7735       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7736   
7737   return commonCastTransforms(FI);
7738 }
7739
7740 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7741   return commonCastTransforms(CI);
7742 }
7743
7744 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7745   return commonCastTransforms(CI);
7746 }
7747
7748 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7749   return commonPointerCastTransforms(CI);
7750 }
7751
7752 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7753   if (Instruction *I = commonCastTransforms(CI))
7754     return I;
7755   
7756   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7757   if (!DestPointee->isSized()) return 0;
7758
7759   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7760   ConstantInt *Cst;
7761   Value *X;
7762   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7763                                     m_ConstantInt(Cst)))) {
7764     // If the source and destination operands have the same type, see if this
7765     // is a single-index GEP.
7766     if (X->getType() == CI.getType()) {
7767       // Get the size of the pointee type.
7768       uint64_t Size = TD->getABITypeSize(DestPointee);
7769
7770       // Convert the constant to intptr type.
7771       APInt Offset = Cst->getValue();
7772       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7773
7774       // If Offset is evenly divisible by Size, we can do this xform.
7775       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7776         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7777         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7778       }
7779     }
7780     // TODO: Could handle other cases, e.g. where add is indexing into field of
7781     // struct etc.
7782   } else if (CI.getOperand(0)->hasOneUse() &&
7783              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7784     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7785     // "inttoptr+GEP" instead of "add+intptr".
7786     
7787     // Get the size of the pointee type.
7788     uint64_t Size = TD->getABITypeSize(DestPointee);
7789     
7790     // Convert the constant to intptr type.
7791     APInt Offset = Cst->getValue();
7792     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7793     
7794     // If Offset is evenly divisible by Size, we can do this xform.
7795     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7796       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7797       
7798       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7799                                                             "tmp"), CI);
7800       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7801     }
7802   }
7803   return 0;
7804 }
7805
7806 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7807   // If the operands are integer typed then apply the integer transforms,
7808   // otherwise just apply the common ones.
7809   Value *Src = CI.getOperand(0);
7810   const Type *SrcTy = Src->getType();
7811   const Type *DestTy = CI.getType();
7812
7813   if (SrcTy->isInteger() && DestTy->isInteger()) {
7814     if (Instruction *Result = commonIntCastTransforms(CI))
7815       return Result;
7816   } else if (isa<PointerType>(SrcTy)) {
7817     if (Instruction *I = commonPointerCastTransforms(CI))
7818       return I;
7819   } else {
7820     if (Instruction *Result = commonCastTransforms(CI))
7821       return Result;
7822   }
7823
7824
7825   // Get rid of casts from one type to the same type. These are useless and can
7826   // be replaced by the operand.
7827   if (DestTy == Src->getType())
7828     return ReplaceInstUsesWith(CI, Src);
7829
7830   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7831     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7832     const Type *DstElTy = DstPTy->getElementType();
7833     const Type *SrcElTy = SrcPTy->getElementType();
7834     
7835     // If the address spaces don't match, don't eliminate the bitcast, which is
7836     // required for changing types.
7837     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7838       return 0;
7839     
7840     // If we are casting a malloc or alloca to a pointer to a type of the same
7841     // size, rewrite the allocation instruction to allocate the "right" type.
7842     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7843       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7844         return V;
7845     
7846     // If the source and destination are pointers, and this cast is equivalent
7847     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7848     // This can enhance SROA and other transforms that want type-safe pointers.
7849     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7850     unsigned NumZeros = 0;
7851     while (SrcElTy != DstElTy && 
7852            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7853            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7854       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7855       ++NumZeros;
7856     }
7857
7858     // If we found a path from the src to dest, create the getelementptr now.
7859     if (SrcElTy == DstElTy) {
7860       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7861       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7862                                        ((Instruction*) NULL));
7863     }
7864   }
7865
7866   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7867     if (SVI->hasOneUse()) {
7868       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7869       // a bitconvert to a vector with the same # elts.
7870       if (isa<VectorType>(DestTy) && 
7871           cast<VectorType>(DestTy)->getNumElements() == 
7872                 SVI->getType()->getNumElements()) {
7873         CastInst *Tmp;
7874         // If either of the operands is a cast from CI.getType(), then
7875         // evaluating the shuffle in the casted destination's type will allow
7876         // us to eliminate at least one cast.
7877         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7878              Tmp->getOperand(0)->getType() == DestTy) ||
7879             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7880              Tmp->getOperand(0)->getType() == DestTy)) {
7881           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7882                                                SVI->getOperand(0), DestTy, &CI);
7883           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7884                                                SVI->getOperand(1), DestTy, &CI);
7885           // Return a new shuffle vector.  Use the same element ID's, as we
7886           // know the vector types match #elts.
7887           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7888         }
7889       }
7890     }
7891   }
7892   return 0;
7893 }
7894
7895 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7896 ///   %C = or %A, %B
7897 ///   %D = select %cond, %C, %A
7898 /// into:
7899 ///   %C = select %cond, %B, 0
7900 ///   %D = or %A, %C
7901 ///
7902 /// Assuming that the specified instruction is an operand to the select, return
7903 /// a bitmask indicating which operands of this instruction are foldable if they
7904 /// equal the other incoming value of the select.
7905 ///
7906 static unsigned GetSelectFoldableOperands(Instruction *I) {
7907   switch (I->getOpcode()) {
7908   case Instruction::Add:
7909   case Instruction::Mul:
7910   case Instruction::And:
7911   case Instruction::Or:
7912   case Instruction::Xor:
7913     return 3;              // Can fold through either operand.
7914   case Instruction::Sub:   // Can only fold on the amount subtracted.
7915   case Instruction::Shl:   // Can only fold on the shift amount.
7916   case Instruction::LShr:
7917   case Instruction::AShr:
7918     return 1;
7919   default:
7920     return 0;              // Cannot fold
7921   }
7922 }
7923
7924 /// GetSelectFoldableConstant - For the same transformation as the previous
7925 /// function, return the identity constant that goes into the select.
7926 static Constant *GetSelectFoldableConstant(Instruction *I) {
7927   switch (I->getOpcode()) {
7928   default: assert(0 && "This cannot happen!"); abort();
7929   case Instruction::Add:
7930   case Instruction::Sub:
7931   case Instruction::Or:
7932   case Instruction::Xor:
7933   case Instruction::Shl:
7934   case Instruction::LShr:
7935   case Instruction::AShr:
7936     return Constant::getNullValue(I->getType());
7937   case Instruction::And:
7938     return Constant::getAllOnesValue(I->getType());
7939   case Instruction::Mul:
7940     return ConstantInt::get(I->getType(), 1);
7941   }
7942 }
7943
7944 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7945 /// have the same opcode and only one use each.  Try to simplify this.
7946 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7947                                           Instruction *FI) {
7948   if (TI->getNumOperands() == 1) {
7949     // If this is a non-volatile load or a cast from the same type,
7950     // merge.
7951     if (TI->isCast()) {
7952       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7953         return 0;
7954     } else {
7955       return 0;  // unknown unary op.
7956     }
7957
7958     // Fold this by inserting a select from the input values.
7959     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7960                                            FI->getOperand(0), SI.getName()+".v");
7961     InsertNewInstBefore(NewSI, SI);
7962     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7963                             TI->getType());
7964   }
7965
7966   // Only handle binary operators here.
7967   if (!isa<BinaryOperator>(TI))
7968     return 0;
7969
7970   // Figure out if the operations have any operands in common.
7971   Value *MatchOp, *OtherOpT, *OtherOpF;
7972   bool MatchIsOpZero;
7973   if (TI->getOperand(0) == FI->getOperand(0)) {
7974     MatchOp  = TI->getOperand(0);
7975     OtherOpT = TI->getOperand(1);
7976     OtherOpF = FI->getOperand(1);
7977     MatchIsOpZero = true;
7978   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7979     MatchOp  = TI->getOperand(1);
7980     OtherOpT = TI->getOperand(0);
7981     OtherOpF = FI->getOperand(0);
7982     MatchIsOpZero = false;
7983   } else if (!TI->isCommutative()) {
7984     return 0;
7985   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7986     MatchOp  = TI->getOperand(0);
7987     OtherOpT = TI->getOperand(1);
7988     OtherOpF = FI->getOperand(0);
7989     MatchIsOpZero = true;
7990   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7991     MatchOp  = TI->getOperand(1);
7992     OtherOpT = TI->getOperand(0);
7993     OtherOpF = FI->getOperand(1);
7994     MatchIsOpZero = true;
7995   } else {
7996     return 0;
7997   }
7998
7999   // If we reach here, they do have operations in common.
8000   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8001                                          OtherOpF, SI.getName()+".v");
8002   InsertNewInstBefore(NewSI, SI);
8003
8004   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8005     if (MatchIsOpZero)
8006       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8007     else
8008       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8009   }
8010   assert(0 && "Shouldn't get here");
8011   return 0;
8012 }
8013
8014 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8015   Value *CondVal = SI.getCondition();
8016   Value *TrueVal = SI.getTrueValue();
8017   Value *FalseVal = SI.getFalseValue();
8018
8019   // select true, X, Y  -> X
8020   // select false, X, Y -> Y
8021   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8022     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8023
8024   // select C, X, X -> X
8025   if (TrueVal == FalseVal)
8026     return ReplaceInstUsesWith(SI, TrueVal);
8027
8028   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8029     return ReplaceInstUsesWith(SI, FalseVal);
8030   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8031     return ReplaceInstUsesWith(SI, TrueVal);
8032   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8033     if (isa<Constant>(TrueVal))
8034       return ReplaceInstUsesWith(SI, TrueVal);
8035     else
8036       return ReplaceInstUsesWith(SI, FalseVal);
8037   }
8038
8039   if (SI.getType() == Type::Int1Ty) {
8040     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8041       if (C->getZExtValue()) {
8042         // Change: A = select B, true, C --> A = or B, C
8043         return BinaryOperator::CreateOr(CondVal, FalseVal);
8044       } else {
8045         // Change: A = select B, false, C --> A = and !B, C
8046         Value *NotCond =
8047           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8048                                              "not."+CondVal->getName()), SI);
8049         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8050       }
8051     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8052       if (C->getZExtValue() == false) {
8053         // Change: A = select B, C, false --> A = and B, C
8054         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8055       } else {
8056         // Change: A = select B, C, true --> A = or !B, C
8057         Value *NotCond =
8058           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8059                                              "not."+CondVal->getName()), SI);
8060         return BinaryOperator::CreateOr(NotCond, TrueVal);
8061       }
8062     }
8063     
8064     // select a, b, a  -> a&b
8065     // select a, a, b  -> a|b
8066     if (CondVal == TrueVal)
8067       return BinaryOperator::CreateOr(CondVal, FalseVal);
8068     else if (CondVal == FalseVal)
8069       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8070   }
8071
8072   // Selecting between two integer constants?
8073   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8074     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8075       // select C, 1, 0 -> zext C to int
8076       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8077         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8078       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8079         // select C, 0, 1 -> zext !C to int
8080         Value *NotCond =
8081           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8082                                                "not."+CondVal->getName()), SI);
8083         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8084       }
8085       
8086       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8087
8088       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8089
8090         // (x <s 0) ? -1 : 0 -> ashr x, 31
8091         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8092           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8093             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8094               // The comparison constant and the result are not neccessarily the
8095               // same width. Make an all-ones value by inserting a AShr.
8096               Value *X = IC->getOperand(0);
8097               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8098               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8099               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8100                                                         ShAmt, "ones");
8101               InsertNewInstBefore(SRA, SI);
8102               
8103               // Finally, convert to the type of the select RHS.  We figure out
8104               // if this requires a SExt, Trunc or BitCast based on the sizes.
8105               Instruction::CastOps opc = Instruction::BitCast;
8106               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8107               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8108               if (SRASize < SISize)
8109                 opc = Instruction::SExt;
8110               else if (SRASize > SISize)
8111                 opc = Instruction::Trunc;
8112               return CastInst::Create(opc, SRA, SI.getType());
8113             }
8114           }
8115
8116
8117         // If one of the constants is zero (we know they can't both be) and we
8118         // have an icmp instruction with zero, and we have an 'and' with the
8119         // non-constant value, eliminate this whole mess.  This corresponds to
8120         // cases like this: ((X & 27) ? 27 : 0)
8121         if (TrueValC->isZero() || FalseValC->isZero())
8122           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8123               cast<Constant>(IC->getOperand(1))->isNullValue())
8124             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8125               if (ICA->getOpcode() == Instruction::And &&
8126                   isa<ConstantInt>(ICA->getOperand(1)) &&
8127                   (ICA->getOperand(1) == TrueValC ||
8128                    ICA->getOperand(1) == FalseValC) &&
8129                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8130                 // Okay, now we know that everything is set up, we just don't
8131                 // know whether we have a icmp_ne or icmp_eq and whether the 
8132                 // true or false val is the zero.
8133                 bool ShouldNotVal = !TrueValC->isZero();
8134                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8135                 Value *V = ICA;
8136                 if (ShouldNotVal)
8137                   V = InsertNewInstBefore(BinaryOperator::Create(
8138                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8139                 return ReplaceInstUsesWith(SI, V);
8140               }
8141       }
8142     }
8143
8144   // See if we are selecting two values based on a comparison of the two values.
8145   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8146     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8147       // Transform (X == Y) ? X : Y  -> Y
8148       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8149         // This is not safe in general for floating point:  
8150         // consider X== -0, Y== +0.
8151         // It becomes safe if either operand is a nonzero constant.
8152         ConstantFP *CFPt, *CFPf;
8153         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8154               !CFPt->getValueAPF().isZero()) ||
8155             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8156              !CFPf->getValueAPF().isZero()))
8157         return ReplaceInstUsesWith(SI, FalseVal);
8158       }
8159       // Transform (X != Y) ? X : Y  -> X
8160       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8161         return ReplaceInstUsesWith(SI, TrueVal);
8162       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8163
8164     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8165       // Transform (X == Y) ? Y : X  -> X
8166       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8167         // This is not safe in general for floating point:  
8168         // consider X== -0, Y== +0.
8169         // It becomes safe if either operand is a nonzero constant.
8170         ConstantFP *CFPt, *CFPf;
8171         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8172               !CFPt->getValueAPF().isZero()) ||
8173             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8174              !CFPf->getValueAPF().isZero()))
8175           return ReplaceInstUsesWith(SI, FalseVal);
8176       }
8177       // Transform (X != Y) ? Y : X  -> Y
8178       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8179         return ReplaceInstUsesWith(SI, TrueVal);
8180       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8181     }
8182   }
8183
8184   // See if we are selecting two values based on a comparison of the two values.
8185   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8186     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8187       // Transform (X == Y) ? X : Y  -> Y
8188       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8189         return ReplaceInstUsesWith(SI, FalseVal);
8190       // Transform (X != Y) ? X : Y  -> X
8191       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8192         return ReplaceInstUsesWith(SI, TrueVal);
8193       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8194
8195     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8196       // Transform (X == Y) ? Y : X  -> X
8197       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8198         return ReplaceInstUsesWith(SI, FalseVal);
8199       // Transform (X != Y) ? Y : X  -> Y
8200       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8201         return ReplaceInstUsesWith(SI, TrueVal);
8202       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8203     }
8204   }
8205
8206   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8207     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8208       if (TI->hasOneUse() && FI->hasOneUse()) {
8209         Instruction *AddOp = 0, *SubOp = 0;
8210
8211         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8212         if (TI->getOpcode() == FI->getOpcode())
8213           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8214             return IV;
8215
8216         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8217         // even legal for FP.
8218         if (TI->getOpcode() == Instruction::Sub &&
8219             FI->getOpcode() == Instruction::Add) {
8220           AddOp = FI; SubOp = TI;
8221         } else if (FI->getOpcode() == Instruction::Sub &&
8222                    TI->getOpcode() == Instruction::Add) {
8223           AddOp = TI; SubOp = FI;
8224         }
8225
8226         if (AddOp) {
8227           Value *OtherAddOp = 0;
8228           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8229             OtherAddOp = AddOp->getOperand(1);
8230           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8231             OtherAddOp = AddOp->getOperand(0);
8232           }
8233
8234           if (OtherAddOp) {
8235             // So at this point we know we have (Y -> OtherAddOp):
8236             //        select C, (add X, Y), (sub X, Z)
8237             Value *NegVal;  // Compute -Z
8238             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8239               NegVal = ConstantExpr::getNeg(C);
8240             } else {
8241               NegVal = InsertNewInstBefore(
8242                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8243             }
8244
8245             Value *NewTrueOp = OtherAddOp;
8246             Value *NewFalseOp = NegVal;
8247             if (AddOp != TI)
8248               std::swap(NewTrueOp, NewFalseOp);
8249             Instruction *NewSel =
8250               SelectInst::Create(CondVal, NewTrueOp,
8251                                  NewFalseOp, SI.getName() + ".p");
8252
8253             NewSel = InsertNewInstBefore(NewSel, SI);
8254             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8255           }
8256         }
8257       }
8258
8259   // See if we can fold the select into one of our operands.
8260   if (SI.getType()->isInteger()) {
8261     // See the comment above GetSelectFoldableOperands for a description of the
8262     // transformation we are doing here.
8263     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8264       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8265           !isa<Constant>(FalseVal))
8266         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8267           unsigned OpToFold = 0;
8268           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8269             OpToFold = 1;
8270           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8271             OpToFold = 2;
8272           }
8273
8274           if (OpToFold) {
8275             Constant *C = GetSelectFoldableConstant(TVI);
8276             Instruction *NewSel =
8277               SelectInst::Create(SI.getCondition(),
8278                                  TVI->getOperand(2-OpToFold), C);
8279             InsertNewInstBefore(NewSel, SI);
8280             NewSel->takeName(TVI);
8281             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8282               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8283             else {
8284               assert(0 && "Unknown instruction!!");
8285             }
8286           }
8287         }
8288
8289     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8290       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8291           !isa<Constant>(TrueVal))
8292         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8293           unsigned OpToFold = 0;
8294           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8295             OpToFold = 1;
8296           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8297             OpToFold = 2;
8298           }
8299
8300           if (OpToFold) {
8301             Constant *C = GetSelectFoldableConstant(FVI);
8302             Instruction *NewSel =
8303               SelectInst::Create(SI.getCondition(), C,
8304                                  FVI->getOperand(2-OpToFold));
8305             InsertNewInstBefore(NewSel, SI);
8306             NewSel->takeName(FVI);
8307             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8308               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8309             else
8310               assert(0 && "Unknown instruction!!");
8311           }
8312         }
8313   }
8314
8315   if (BinaryOperator::isNot(CondVal)) {
8316     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8317     SI.setOperand(1, FalseVal);
8318     SI.setOperand(2, TrueVal);
8319     return &SI;
8320   }
8321
8322   return 0;
8323 }
8324
8325 /// EnforceKnownAlignment - If the specified pointer points to an object that
8326 /// we control, modify the object's alignment to PrefAlign. This isn't
8327 /// often possible though. If alignment is important, a more reliable approach
8328 /// is to simply align all global variables and allocation instructions to
8329 /// their preferred alignment from the beginning.
8330 ///
8331 static unsigned EnforceKnownAlignment(Value *V,
8332                                       unsigned Align, unsigned PrefAlign) {
8333
8334   User *U = dyn_cast<User>(V);
8335   if (!U) return Align;
8336
8337   switch (getOpcode(U)) {
8338   default: break;
8339   case Instruction::BitCast:
8340     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8341   case Instruction::GetElementPtr: {
8342     // If all indexes are zero, it is just the alignment of the base pointer.
8343     bool AllZeroOperands = true;
8344     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8345       if (!isa<Constant>(*i) ||
8346           !cast<Constant>(*i)->isNullValue()) {
8347         AllZeroOperands = false;
8348         break;
8349       }
8350
8351     if (AllZeroOperands) {
8352       // Treat this like a bitcast.
8353       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8354     }
8355     break;
8356   }
8357   }
8358
8359   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8360     // If there is a large requested alignment and we can, bump up the alignment
8361     // of the global.
8362     if (!GV->isDeclaration()) {
8363       GV->setAlignment(PrefAlign);
8364       Align = PrefAlign;
8365     }
8366   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8367     // If there is a requested alignment and if this is an alloca, round up.  We
8368     // don't do this for malloc, because some systems can't respect the request.
8369     if (isa<AllocaInst>(AI)) {
8370       AI->setAlignment(PrefAlign);
8371       Align = PrefAlign;
8372     }
8373   }
8374
8375   return Align;
8376 }
8377
8378 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8379 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8380 /// and it is more than the alignment of the ultimate object, see if we can
8381 /// increase the alignment of the ultimate object, making this check succeed.
8382 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8383                                                   unsigned PrefAlign) {
8384   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8385                       sizeof(PrefAlign) * CHAR_BIT;
8386   APInt Mask = APInt::getAllOnesValue(BitWidth);
8387   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8388   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8389   unsigned TrailZ = KnownZero.countTrailingOnes();
8390   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8391
8392   if (PrefAlign > Align)
8393     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8394   
8395     // We don't need to make any adjustment.
8396   return Align;
8397 }
8398
8399 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8400   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8401   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8402   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8403   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8404
8405   if (CopyAlign < MinAlign) {
8406     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8407     return MI;
8408   }
8409   
8410   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8411   // load/store.
8412   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8413   if (MemOpLength == 0) return 0;
8414   
8415   // Source and destination pointer types are always "i8*" for intrinsic.  See
8416   // if the size is something we can handle with a single primitive load/store.
8417   // A single load+store correctly handles overlapping memory in the memmove
8418   // case.
8419   unsigned Size = MemOpLength->getZExtValue();
8420   if (Size == 0) return MI;  // Delete this mem transfer.
8421   
8422   if (Size > 8 || (Size&(Size-1)))
8423     return 0;  // If not 1/2/4/8 bytes, exit.
8424   
8425   // Use an integer load+store unless we can find something better.
8426   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8427   
8428   // Memcpy forces the use of i8* for the source and destination.  That means
8429   // that if you're using memcpy to move one double around, you'll get a cast
8430   // from double* to i8*.  We'd much rather use a double load+store rather than
8431   // an i64 load+store, here because this improves the odds that the source or
8432   // dest address will be promotable.  See if we can find a better type than the
8433   // integer datatype.
8434   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8435     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8436     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8437       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8438       // down through these levels if so.
8439       while (!SrcETy->isSingleValueType()) {
8440         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8441           if (STy->getNumElements() == 1)
8442             SrcETy = STy->getElementType(0);
8443           else
8444             break;
8445         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8446           if (ATy->getNumElements() == 1)
8447             SrcETy = ATy->getElementType();
8448           else
8449             break;
8450         } else
8451           break;
8452       }
8453       
8454       if (SrcETy->isSingleValueType())
8455         NewPtrTy = PointerType::getUnqual(SrcETy);
8456     }
8457   }
8458   
8459   
8460   // If the memcpy/memmove provides better alignment info than we can
8461   // infer, use it.
8462   SrcAlign = std::max(SrcAlign, CopyAlign);
8463   DstAlign = std::max(DstAlign, CopyAlign);
8464   
8465   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8466   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8467   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8468   InsertNewInstBefore(L, *MI);
8469   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8470
8471   // Set the size of the copy to 0, it will be deleted on the next iteration.
8472   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8473   return MI;
8474 }
8475
8476 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8477   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8478   if (MI->getAlignment()->getZExtValue() < Alignment) {
8479     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8480     return MI;
8481   }
8482   
8483   // Extract the length and alignment and fill if they are constant.
8484   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8485   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8486   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8487     return 0;
8488   uint64_t Len = LenC->getZExtValue();
8489   Alignment = MI->getAlignment()->getZExtValue();
8490   
8491   // If the length is zero, this is a no-op
8492   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8493   
8494   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8495   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8496     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8497     
8498     Value *Dest = MI->getDest();
8499     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8500
8501     // Alignment 0 is identity for alignment 1 for memset, but not store.
8502     if (Alignment == 0) Alignment = 1;
8503     
8504     // Extract the fill value and store.
8505     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8506     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8507                                       Alignment), *MI);
8508     
8509     // Set the size of the copy to 0, it will be deleted on the next iteration.
8510     MI->setLength(Constant::getNullValue(LenC->getType()));
8511     return MI;
8512   }
8513
8514   return 0;
8515 }
8516
8517
8518 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8519 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8520 /// the heavy lifting.
8521 ///
8522 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8523   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8524   if (!II) return visitCallSite(&CI);
8525   
8526   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8527   // visitCallSite.
8528   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8529     bool Changed = false;
8530
8531     // memmove/cpy/set of zero bytes is a noop.
8532     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8533       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8534
8535       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8536         if (CI->getZExtValue() == 1) {
8537           // Replace the instruction with just byte operations.  We would
8538           // transform other cases to loads/stores, but we don't know if
8539           // alignment is sufficient.
8540         }
8541     }
8542
8543     // If we have a memmove and the source operation is a constant global,
8544     // then the source and dest pointers can't alias, so we can change this
8545     // into a call to memcpy.
8546     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8547       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8548         if (GVSrc->isConstant()) {
8549           Module *M = CI.getParent()->getParent()->getParent();
8550           Intrinsic::ID MemCpyID;
8551           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8552             MemCpyID = Intrinsic::memcpy_i32;
8553           else
8554             MemCpyID = Intrinsic::memcpy_i64;
8555           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8556           Changed = true;
8557         }
8558
8559       // memmove(x,x,size) -> noop.
8560       if (MMI->getSource() == MMI->getDest())
8561         return EraseInstFromFunction(CI);
8562     }
8563
8564     // If we can determine a pointer alignment that is bigger than currently
8565     // set, update the alignment.
8566     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8567       if (Instruction *I = SimplifyMemTransfer(MI))
8568         return I;
8569     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8570       if (Instruction *I = SimplifyMemSet(MSI))
8571         return I;
8572     }
8573           
8574     if (Changed) return II;
8575   }
8576   
8577   switch (II->getIntrinsicID()) {
8578   default: break;
8579   case Intrinsic::bswap:
8580     // bswap(bswap(x)) -> x
8581     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8582       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8583         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8584     break;
8585   case Intrinsic::ppc_altivec_lvx:
8586   case Intrinsic::ppc_altivec_lvxl:
8587   case Intrinsic::x86_sse_loadu_ps:
8588   case Intrinsic::x86_sse2_loadu_pd:
8589   case Intrinsic::x86_sse2_loadu_dq:
8590     // Turn PPC lvx     -> load if the pointer is known aligned.
8591     // Turn X86 loadups -> load if the pointer is known aligned.
8592     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8593       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8594                                        PointerType::getUnqual(II->getType()),
8595                                        CI);
8596       return new LoadInst(Ptr);
8597     }
8598     break;
8599   case Intrinsic::ppc_altivec_stvx:
8600   case Intrinsic::ppc_altivec_stvxl:
8601     // Turn stvx -> store if the pointer is known aligned.
8602     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8603       const Type *OpPtrTy = 
8604         PointerType::getUnqual(II->getOperand(1)->getType());
8605       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8606       return new StoreInst(II->getOperand(1), Ptr);
8607     }
8608     break;
8609   case Intrinsic::x86_sse_storeu_ps:
8610   case Intrinsic::x86_sse2_storeu_pd:
8611   case Intrinsic::x86_sse2_storeu_dq:
8612   case Intrinsic::x86_sse2_storel_dq:
8613     // Turn X86 storeu -> store if the pointer is known aligned.
8614     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8615       const Type *OpPtrTy = 
8616         PointerType::getUnqual(II->getOperand(2)->getType());
8617       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8618       return new StoreInst(II->getOperand(2), Ptr);
8619     }
8620     break;
8621     
8622   case Intrinsic::x86_sse_cvttss2si: {
8623     // These intrinsics only demands the 0th element of its input vector.  If
8624     // we can simplify the input based on that, do so now.
8625     uint64_t UndefElts;
8626     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8627                                               UndefElts)) {
8628       II->setOperand(1, V);
8629       return II;
8630     }
8631     break;
8632   }
8633     
8634   case Intrinsic::ppc_altivec_vperm:
8635     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8636     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8637       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8638       
8639       // Check that all of the elements are integer constants or undefs.
8640       bool AllEltsOk = true;
8641       for (unsigned i = 0; i != 16; ++i) {
8642         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8643             !isa<UndefValue>(Mask->getOperand(i))) {
8644           AllEltsOk = false;
8645           break;
8646         }
8647       }
8648       
8649       if (AllEltsOk) {
8650         // Cast the input vectors to byte vectors.
8651         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8652         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8653         Value *Result = UndefValue::get(Op0->getType());
8654         
8655         // Only extract each element once.
8656         Value *ExtractedElts[32];
8657         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8658         
8659         for (unsigned i = 0; i != 16; ++i) {
8660           if (isa<UndefValue>(Mask->getOperand(i)))
8661             continue;
8662           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8663           Idx &= 31;  // Match the hardware behavior.
8664           
8665           if (ExtractedElts[Idx] == 0) {
8666             Instruction *Elt = 
8667               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8668             InsertNewInstBefore(Elt, CI);
8669             ExtractedElts[Idx] = Elt;
8670           }
8671         
8672           // Insert this value into the result vector.
8673           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8674                                              i, "tmp");
8675           InsertNewInstBefore(cast<Instruction>(Result), CI);
8676         }
8677         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8678       }
8679     }
8680     break;
8681
8682   case Intrinsic::stackrestore: {
8683     // If the save is right next to the restore, remove the restore.  This can
8684     // happen when variable allocas are DCE'd.
8685     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8686       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8687         BasicBlock::iterator BI = SS;
8688         if (&*++BI == II)
8689           return EraseInstFromFunction(CI);
8690       }
8691     }
8692     
8693     // Scan down this block to see if there is another stack restore in the
8694     // same block without an intervening call/alloca.
8695     BasicBlock::iterator BI = II;
8696     TerminatorInst *TI = II->getParent()->getTerminator();
8697     bool CannotRemove = false;
8698     for (++BI; &*BI != TI; ++BI) {
8699       if (isa<AllocaInst>(BI)) {
8700         CannotRemove = true;
8701         break;
8702       }
8703       if (isa<CallInst>(BI)) {
8704         if (!isa<IntrinsicInst>(BI)) {
8705           CannotRemove = true;
8706           break;
8707         }
8708         // If there is a stackrestore below this one, remove this one.
8709         return EraseInstFromFunction(CI);
8710       }
8711     }
8712     
8713     // If the stack restore is in a return/unwind block and if there are no
8714     // allocas or calls between the restore and the return, nuke the restore.
8715     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8716       return EraseInstFromFunction(CI);
8717     break;
8718   }
8719   }
8720
8721   return visitCallSite(II);
8722 }
8723
8724 // InvokeInst simplification
8725 //
8726 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8727   return visitCallSite(&II);
8728 }
8729
8730 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8731 /// passed through the varargs area, we can eliminate the use of the cast.
8732 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8733                                          const CastInst * const CI,
8734                                          const TargetData * const TD,
8735                                          const int ix) {
8736   if (!CI->isLosslessCast())
8737     return false;
8738
8739   // The size of ByVal arguments is derived from the type, so we
8740   // can't change to a type with a different size.  If the size were
8741   // passed explicitly we could avoid this check.
8742   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8743     return true;
8744
8745   const Type* SrcTy = 
8746             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8747   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8748   if (!SrcTy->isSized() || !DstTy->isSized())
8749     return false;
8750   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8751     return false;
8752   return true;
8753 }
8754
8755 // visitCallSite - Improvements for call and invoke instructions.
8756 //
8757 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8758   bool Changed = false;
8759
8760   // If the callee is a constexpr cast of a function, attempt to move the cast
8761   // to the arguments of the call/invoke.
8762   if (transformConstExprCastCall(CS)) return 0;
8763
8764   Value *Callee = CS.getCalledValue();
8765
8766   if (Function *CalleeF = dyn_cast<Function>(Callee))
8767     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8768       Instruction *OldCall = CS.getInstruction();
8769       // If the call and callee calling conventions don't match, this call must
8770       // be unreachable, as the call is undefined.
8771       new StoreInst(ConstantInt::getTrue(),
8772                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8773                                     OldCall);
8774       if (!OldCall->use_empty())
8775         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8776       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8777         return EraseInstFromFunction(*OldCall);
8778       return 0;
8779     }
8780
8781   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8782     // This instruction is not reachable, just remove it.  We insert a store to
8783     // undef so that we know that this code is not reachable, despite the fact
8784     // that we can't modify the CFG here.
8785     new StoreInst(ConstantInt::getTrue(),
8786                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8787                   CS.getInstruction());
8788
8789     if (!CS.getInstruction()->use_empty())
8790       CS.getInstruction()->
8791         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8792
8793     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8794       // Don't break the CFG, insert a dummy cond branch.
8795       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8796                          ConstantInt::getTrue(), II);
8797     }
8798     return EraseInstFromFunction(*CS.getInstruction());
8799   }
8800
8801   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8802     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8803       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8804         return transformCallThroughTrampoline(CS);
8805
8806   const PointerType *PTy = cast<PointerType>(Callee->getType());
8807   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8808   if (FTy->isVarArg()) {
8809     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8810     // See if we can optimize any arguments passed through the varargs area of
8811     // the call.
8812     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8813            E = CS.arg_end(); I != E; ++I, ++ix) {
8814       CastInst *CI = dyn_cast<CastInst>(*I);
8815       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8816         *I = CI->getOperand(0);
8817         Changed = true;
8818       }
8819     }
8820   }
8821
8822   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8823     // Inline asm calls cannot throw - mark them 'nounwind'.
8824     CS.setDoesNotThrow();
8825     Changed = true;
8826   }
8827
8828   return Changed ? CS.getInstruction() : 0;
8829 }
8830
8831 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8832 // attempt to move the cast to the arguments of the call/invoke.
8833 //
8834 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8835   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8836   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8837   if (CE->getOpcode() != Instruction::BitCast || 
8838       !isa<Function>(CE->getOperand(0)))
8839     return false;
8840   Function *Callee = cast<Function>(CE->getOperand(0));
8841   Instruction *Caller = CS.getInstruction();
8842   const PAListPtr &CallerPAL = CS.getParamAttrs();
8843
8844   // Okay, this is a cast from a function to a different type.  Unless doing so
8845   // would cause a type conversion of one of our arguments, change this call to
8846   // be a direct call with arguments casted to the appropriate types.
8847   //
8848   const FunctionType *FT = Callee->getFunctionType();
8849   const Type *OldRetTy = Caller->getType();
8850   const Type *NewRetTy = FT->getReturnType();
8851
8852   if (isa<StructType>(NewRetTy))
8853     return false; // TODO: Handle multiple return values.
8854
8855   // Check to see if we are changing the return type...
8856   if (OldRetTy != NewRetTy) {
8857     if (Callee->isDeclaration() &&
8858         // Conversion is ok if changing from one pointer type to another or from
8859         // a pointer to an integer of the same size.
8860         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8861           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8862       return false;   // Cannot transform this return value.
8863
8864     if (!Caller->use_empty() &&
8865         // void -> non-void is handled specially
8866         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8867       return false;   // Cannot transform this return value.
8868
8869     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8870       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8871       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8872         return false;   // Attribute not compatible with transformed value.
8873     }
8874
8875     // If the callsite is an invoke instruction, and the return value is used by
8876     // a PHI node in a successor, we cannot change the return type of the call
8877     // because there is no place to put the cast instruction (without breaking
8878     // the critical edge).  Bail out in this case.
8879     if (!Caller->use_empty())
8880       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8881         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8882              UI != E; ++UI)
8883           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8884             if (PN->getParent() == II->getNormalDest() ||
8885                 PN->getParent() == II->getUnwindDest())
8886               return false;
8887   }
8888
8889   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8890   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8891
8892   CallSite::arg_iterator AI = CS.arg_begin();
8893   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8894     const Type *ParamTy = FT->getParamType(i);
8895     const Type *ActTy = (*AI)->getType();
8896
8897     if (!CastInst::isCastable(ActTy, ParamTy))
8898       return false;   // Cannot transform this parameter value.
8899
8900     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8901       return false;   // Attribute not compatible with transformed value.
8902
8903     // Converting from one pointer type to another or between a pointer and an
8904     // integer of the same size is safe even if we do not have a body.
8905     bool isConvertible = ActTy == ParamTy ||
8906       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8907        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8908     if (Callee->isDeclaration() && !isConvertible) return false;
8909   }
8910
8911   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8912       Callee->isDeclaration())
8913     return false;   // Do not delete arguments unless we have a function body.
8914
8915   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8916       !CallerPAL.isEmpty())
8917     // In this case we have more arguments than the new function type, but we
8918     // won't be dropping them.  Check that these extra arguments have attributes
8919     // that are compatible with being a vararg call argument.
8920     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8921       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8922         break;
8923       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8924       if (PAttrs & ParamAttr::VarArgsIncompatible)
8925         return false;
8926     }
8927
8928   // Okay, we decided that this is a safe thing to do: go ahead and start
8929   // inserting cast instructions as necessary...
8930   std::vector<Value*> Args;
8931   Args.reserve(NumActualArgs);
8932   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8933   attrVec.reserve(NumCommonArgs);
8934
8935   // Get any return attributes.
8936   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8937
8938   // If the return value is not being used, the type may not be compatible
8939   // with the existing attributes.  Wipe out any problematic attributes.
8940   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8941
8942   // Add the new return attributes.
8943   if (RAttrs)
8944     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8945
8946   AI = CS.arg_begin();
8947   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8948     const Type *ParamTy = FT->getParamType(i);
8949     if ((*AI)->getType() == ParamTy) {
8950       Args.push_back(*AI);
8951     } else {
8952       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8953           false, ParamTy, false);
8954       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8955       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8956     }
8957
8958     // Add any parameter attributes.
8959     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8960       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8961   }
8962
8963   // If the function takes more arguments than the call was taking, add them
8964   // now...
8965   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8966     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8967
8968   // If we are removing arguments to the function, emit an obnoxious warning...
8969   if (FT->getNumParams() < NumActualArgs) {
8970     if (!FT->isVarArg()) {
8971       cerr << "WARNING: While resolving call to function '"
8972            << Callee->getName() << "' arguments were dropped!\n";
8973     } else {
8974       // Add all of the arguments in their promoted form to the arg list...
8975       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8976         const Type *PTy = getPromotedType((*AI)->getType());
8977         if (PTy != (*AI)->getType()) {
8978           // Must promote to pass through va_arg area!
8979           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8980                                                                 PTy, false);
8981           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
8982           InsertNewInstBefore(Cast, *Caller);
8983           Args.push_back(Cast);
8984         } else {
8985           Args.push_back(*AI);
8986         }
8987
8988         // Add any parameter attributes.
8989         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8990           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8991       }
8992     }
8993   }
8994
8995   if (NewRetTy == Type::VoidTy)
8996     Caller->setName("");   // Void type should not have a name.
8997
8998   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
8999
9000   Instruction *NC;
9001   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9002     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9003                             Args.begin(), Args.end(),
9004                             Caller->getName(), Caller);
9005     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9006     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9007   } else {
9008     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9009                           Caller->getName(), Caller);
9010     CallInst *CI = cast<CallInst>(Caller);
9011     if (CI->isTailCall())
9012       cast<CallInst>(NC)->setTailCall();
9013     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9014     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9015   }
9016
9017   // Insert a cast of the return type as necessary.
9018   Value *NV = NC;
9019   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9020     if (NV->getType() != Type::VoidTy) {
9021       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9022                                                             OldRetTy, false);
9023       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9024
9025       // If this is an invoke instruction, we should insert it after the first
9026       // non-phi, instruction in the normal successor block.
9027       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9028         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9029         InsertNewInstBefore(NC, *I);
9030       } else {
9031         // Otherwise, it's a call, just insert cast right after the call instr
9032         InsertNewInstBefore(NC, *Caller);
9033       }
9034       AddUsersToWorkList(*Caller);
9035     } else {
9036       NV = UndefValue::get(Caller->getType());
9037     }
9038   }
9039
9040   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9041     Caller->replaceAllUsesWith(NV);
9042   Caller->eraseFromParent();
9043   RemoveFromWorkList(Caller);
9044   return true;
9045 }
9046
9047 // transformCallThroughTrampoline - Turn a call to a function created by the
9048 // init_trampoline intrinsic into a direct call to the underlying function.
9049 //
9050 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9051   Value *Callee = CS.getCalledValue();
9052   const PointerType *PTy = cast<PointerType>(Callee->getType());
9053   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9054   const PAListPtr &Attrs = CS.getParamAttrs();
9055
9056   // If the call already has the 'nest' attribute somewhere then give up -
9057   // otherwise 'nest' would occur twice after splicing in the chain.
9058   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9059     return 0;
9060
9061   IntrinsicInst *Tramp =
9062     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9063
9064   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9065   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9066   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9067
9068   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9069   if (!NestAttrs.isEmpty()) {
9070     unsigned NestIdx = 1;
9071     const Type *NestTy = 0;
9072     ParameterAttributes NestAttr = ParamAttr::None;
9073
9074     // Look for a parameter marked with the 'nest' attribute.
9075     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9076          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9077       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9078         // Record the parameter type and any other attributes.
9079         NestTy = *I;
9080         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9081         break;
9082       }
9083
9084     if (NestTy) {
9085       Instruction *Caller = CS.getInstruction();
9086       std::vector<Value*> NewArgs;
9087       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9088
9089       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9090       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9091
9092       // Insert the nest argument into the call argument list, which may
9093       // mean appending it.  Likewise for attributes.
9094
9095       // Add any function result attributes.
9096       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9097         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9098
9099       {
9100         unsigned Idx = 1;
9101         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9102         do {
9103           if (Idx == NestIdx) {
9104             // Add the chain argument and attributes.
9105             Value *NestVal = Tramp->getOperand(3);
9106             if (NestVal->getType() != NestTy)
9107               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9108             NewArgs.push_back(NestVal);
9109             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9110           }
9111
9112           if (I == E)
9113             break;
9114
9115           // Add the original argument and attributes.
9116           NewArgs.push_back(*I);
9117           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9118             NewAttrs.push_back
9119               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9120
9121           ++Idx, ++I;
9122         } while (1);
9123       }
9124
9125       // The trampoline may have been bitcast to a bogus type (FTy).
9126       // Handle this by synthesizing a new function type, equal to FTy
9127       // with the chain parameter inserted.
9128
9129       std::vector<const Type*> NewTypes;
9130       NewTypes.reserve(FTy->getNumParams()+1);
9131
9132       // Insert the chain's type into the list of parameter types, which may
9133       // mean appending it.
9134       {
9135         unsigned Idx = 1;
9136         FunctionType::param_iterator I = FTy->param_begin(),
9137           E = FTy->param_end();
9138
9139         do {
9140           if (Idx == NestIdx)
9141             // Add the chain's type.
9142             NewTypes.push_back(NestTy);
9143
9144           if (I == E)
9145             break;
9146
9147           // Add the original type.
9148           NewTypes.push_back(*I);
9149
9150           ++Idx, ++I;
9151         } while (1);
9152       }
9153
9154       // Replace the trampoline call with a direct call.  Let the generic
9155       // code sort out any function type mismatches.
9156       FunctionType *NewFTy =
9157         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9158       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9159         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9160       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9161
9162       Instruction *NewCaller;
9163       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9164         NewCaller = InvokeInst::Create(NewCallee,
9165                                        II->getNormalDest(), II->getUnwindDest(),
9166                                        NewArgs.begin(), NewArgs.end(),
9167                                        Caller->getName(), Caller);
9168         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9169         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9170       } else {
9171         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9172                                      Caller->getName(), Caller);
9173         if (cast<CallInst>(Caller)->isTailCall())
9174           cast<CallInst>(NewCaller)->setTailCall();
9175         cast<CallInst>(NewCaller)->
9176           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9177         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9178       }
9179       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9180         Caller->replaceAllUsesWith(NewCaller);
9181       Caller->eraseFromParent();
9182       RemoveFromWorkList(Caller);
9183       return 0;
9184     }
9185   }
9186
9187   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9188   // parameter, there is no need to adjust the argument list.  Let the generic
9189   // code sort out any function type mismatches.
9190   Constant *NewCallee =
9191     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9192   CS.setCalledFunction(NewCallee);
9193   return CS.getInstruction();
9194 }
9195
9196 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9197 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9198 /// and a single binop.
9199 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9200   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9201   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9202          isa<CmpInst>(FirstInst));
9203   unsigned Opc = FirstInst->getOpcode();
9204   Value *LHSVal = FirstInst->getOperand(0);
9205   Value *RHSVal = FirstInst->getOperand(1);
9206     
9207   const Type *LHSType = LHSVal->getType();
9208   const Type *RHSType = RHSVal->getType();
9209   
9210   // Scan to see if all operands are the same opcode, all have one use, and all
9211   // kill their operands (i.e. the operands have one use).
9212   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9213     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9214     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9215         // Verify type of the LHS matches so we don't fold cmp's of different
9216         // types or GEP's with different index types.
9217         I->getOperand(0)->getType() != LHSType ||
9218         I->getOperand(1)->getType() != RHSType)
9219       return 0;
9220
9221     // If they are CmpInst instructions, check their predicates
9222     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9223       if (cast<CmpInst>(I)->getPredicate() !=
9224           cast<CmpInst>(FirstInst)->getPredicate())
9225         return 0;
9226     
9227     // Keep track of which operand needs a phi node.
9228     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9229     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9230   }
9231   
9232   // Otherwise, this is safe to transform, determine if it is profitable.
9233
9234   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9235   // Indexes are often folded into load/store instructions, so we don't want to
9236   // hide them behind a phi.
9237   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9238     return 0;
9239   
9240   Value *InLHS = FirstInst->getOperand(0);
9241   Value *InRHS = FirstInst->getOperand(1);
9242   PHINode *NewLHS = 0, *NewRHS = 0;
9243   if (LHSVal == 0) {
9244     NewLHS = PHINode::Create(LHSType,
9245                              FirstInst->getOperand(0)->getName() + ".pn");
9246     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9247     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9248     InsertNewInstBefore(NewLHS, PN);
9249     LHSVal = NewLHS;
9250   }
9251   
9252   if (RHSVal == 0) {
9253     NewRHS = PHINode::Create(RHSType,
9254                              FirstInst->getOperand(1)->getName() + ".pn");
9255     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9256     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9257     InsertNewInstBefore(NewRHS, PN);
9258     RHSVal = NewRHS;
9259   }
9260   
9261   // Add all operands to the new PHIs.
9262   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9263     if (NewLHS) {
9264       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9265       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9266     }
9267     if (NewRHS) {
9268       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9269       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9270     }
9271   }
9272     
9273   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9274     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9275   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9276     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9277                            RHSVal);
9278   else {
9279     assert(isa<GetElementPtrInst>(FirstInst));
9280     return GetElementPtrInst::Create(LHSVal, RHSVal);
9281   }
9282 }
9283
9284 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9285 /// of the block that defines it.  This means that it must be obvious the value
9286 /// of the load is not changed from the point of the load to the end of the
9287 /// block it is in.
9288 ///
9289 /// Finally, it is safe, but not profitable, to sink a load targetting a
9290 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9291 /// to a register.
9292 static bool isSafeToSinkLoad(LoadInst *L) {
9293   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9294   
9295   for (++BBI; BBI != E; ++BBI)
9296     if (BBI->mayWriteToMemory())
9297       return false;
9298   
9299   // Check for non-address taken alloca.  If not address-taken already, it isn't
9300   // profitable to do this xform.
9301   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9302     bool isAddressTaken = false;
9303     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9304          UI != E; ++UI) {
9305       if (isa<LoadInst>(UI)) continue;
9306       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9307         // If storing TO the alloca, then the address isn't taken.
9308         if (SI->getOperand(1) == AI) continue;
9309       }
9310       isAddressTaken = true;
9311       break;
9312     }
9313     
9314     if (!isAddressTaken)
9315       return false;
9316   }
9317   
9318   return true;
9319 }
9320
9321
9322 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9323 // operator and they all are only used by the PHI, PHI together their
9324 // inputs, and do the operation once, to the result of the PHI.
9325 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9326   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9327
9328   // Scan the instruction, looking for input operations that can be folded away.
9329   // If all input operands to the phi are the same instruction (e.g. a cast from
9330   // the same type or "+42") we can pull the operation through the PHI, reducing
9331   // code size and simplifying code.
9332   Constant *ConstantOp = 0;
9333   const Type *CastSrcTy = 0;
9334   bool isVolatile = false;
9335   if (isa<CastInst>(FirstInst)) {
9336     CastSrcTy = FirstInst->getOperand(0)->getType();
9337   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9338     // Can fold binop, compare or shift here if the RHS is a constant, 
9339     // otherwise call FoldPHIArgBinOpIntoPHI.
9340     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9341     if (ConstantOp == 0)
9342       return FoldPHIArgBinOpIntoPHI(PN);
9343   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9344     isVolatile = LI->isVolatile();
9345     // We can't sink the load if the loaded value could be modified between the
9346     // load and the PHI.
9347     if (LI->getParent() != PN.getIncomingBlock(0) ||
9348         !isSafeToSinkLoad(LI))
9349       return 0;
9350   } else if (isa<GetElementPtrInst>(FirstInst)) {
9351     if (FirstInst->getNumOperands() == 2)
9352       return FoldPHIArgBinOpIntoPHI(PN);
9353     // Can't handle general GEPs yet.
9354     return 0;
9355   } else {
9356     return 0;  // Cannot fold this operation.
9357   }
9358
9359   // Check to see if all arguments are the same operation.
9360   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9361     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9362     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9363     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9364       return 0;
9365     if (CastSrcTy) {
9366       if (I->getOperand(0)->getType() != CastSrcTy)
9367         return 0;  // Cast operation must match.
9368     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9369       // We can't sink the load if the loaded value could be modified between 
9370       // the load and the PHI.
9371       if (LI->isVolatile() != isVolatile ||
9372           LI->getParent() != PN.getIncomingBlock(i) ||
9373           !isSafeToSinkLoad(LI))
9374         return 0;
9375       
9376       // If the PHI is volatile and its block has multiple successors, sinking
9377       // it would remove a load of the volatile value from the path through the
9378       // other successor.
9379       if (isVolatile &&
9380           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9381         return 0;
9382
9383       
9384     } else if (I->getOperand(1) != ConstantOp) {
9385       return 0;
9386     }
9387   }
9388
9389   // Okay, they are all the same operation.  Create a new PHI node of the
9390   // correct type, and PHI together all of the LHS's of the instructions.
9391   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9392                                    PN.getName()+".in");
9393   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9394
9395   Value *InVal = FirstInst->getOperand(0);
9396   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9397
9398   // Add all operands to the new PHI.
9399   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9400     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9401     if (NewInVal != InVal)
9402       InVal = 0;
9403     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9404   }
9405
9406   Value *PhiVal;
9407   if (InVal) {
9408     // The new PHI unions all of the same values together.  This is really
9409     // common, so we handle it intelligently here for compile-time speed.
9410     PhiVal = InVal;
9411     delete NewPN;
9412   } else {
9413     InsertNewInstBefore(NewPN, PN);
9414     PhiVal = NewPN;
9415   }
9416
9417   // Insert and return the new operation.
9418   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9419     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9420   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9421     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9422   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9423     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9424                            PhiVal, ConstantOp);
9425   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9426   
9427   // If this was a volatile load that we are merging, make sure to loop through
9428   // and mark all the input loads as non-volatile.  If we don't do this, we will
9429   // insert a new volatile load and the old ones will not be deletable.
9430   if (isVolatile)
9431     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9432       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9433   
9434   return new LoadInst(PhiVal, "", isVolatile);
9435 }
9436
9437 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9438 /// that is dead.
9439 static bool DeadPHICycle(PHINode *PN,
9440                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9441   if (PN->use_empty()) return true;
9442   if (!PN->hasOneUse()) return false;
9443
9444   // Remember this node, and if we find the cycle, return.
9445   if (!PotentiallyDeadPHIs.insert(PN))
9446     return true;
9447   
9448   // Don't scan crazily complex things.
9449   if (PotentiallyDeadPHIs.size() == 16)
9450     return false;
9451
9452   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9453     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9454
9455   return false;
9456 }
9457
9458 /// PHIsEqualValue - Return true if this phi node is always equal to
9459 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9460 ///   z = some value; x = phi (y, z); y = phi (x, z)
9461 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9462                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9463   // See if we already saw this PHI node.
9464   if (!ValueEqualPHIs.insert(PN))
9465     return true;
9466   
9467   // Don't scan crazily complex things.
9468   if (ValueEqualPHIs.size() == 16)
9469     return false;
9470  
9471   // Scan the operands to see if they are either phi nodes or are equal to
9472   // the value.
9473   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9474     Value *Op = PN->getIncomingValue(i);
9475     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9476       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9477         return false;
9478     } else if (Op != NonPhiInVal)
9479       return false;
9480   }
9481   
9482   return true;
9483 }
9484
9485
9486 // PHINode simplification
9487 //
9488 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9489   // If LCSSA is around, don't mess with Phi nodes
9490   if (MustPreserveLCSSA) return 0;
9491   
9492   if (Value *V = PN.hasConstantValue())
9493     return ReplaceInstUsesWith(PN, V);
9494
9495   // If all PHI operands are the same operation, pull them through the PHI,
9496   // reducing code size.
9497   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9498       PN.getIncomingValue(0)->hasOneUse())
9499     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9500       return Result;
9501
9502   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9503   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9504   // PHI)... break the cycle.
9505   if (PN.hasOneUse()) {
9506     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9507     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9508       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9509       PotentiallyDeadPHIs.insert(&PN);
9510       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9511         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9512     }
9513    
9514     // If this phi has a single use, and if that use just computes a value for
9515     // the next iteration of a loop, delete the phi.  This occurs with unused
9516     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9517     // common case here is good because the only other things that catch this
9518     // are induction variable analysis (sometimes) and ADCE, which is only run
9519     // late.
9520     if (PHIUser->hasOneUse() &&
9521         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9522         PHIUser->use_back() == &PN) {
9523       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9524     }
9525   }
9526
9527   // We sometimes end up with phi cycles that non-obviously end up being the
9528   // same value, for example:
9529   //   z = some value; x = phi (y, z); y = phi (x, z)
9530   // where the phi nodes don't necessarily need to be in the same block.  Do a
9531   // quick check to see if the PHI node only contains a single non-phi value, if
9532   // so, scan to see if the phi cycle is actually equal to that value.
9533   {
9534     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9535     // Scan for the first non-phi operand.
9536     while (InValNo != NumOperandVals && 
9537            isa<PHINode>(PN.getIncomingValue(InValNo)))
9538       ++InValNo;
9539
9540     if (InValNo != NumOperandVals) {
9541       Value *NonPhiInVal = PN.getOperand(InValNo);
9542       
9543       // Scan the rest of the operands to see if there are any conflicts, if so
9544       // there is no need to recursively scan other phis.
9545       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9546         Value *OpVal = PN.getIncomingValue(InValNo);
9547         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9548           break;
9549       }
9550       
9551       // If we scanned over all operands, then we have one unique value plus
9552       // phi values.  Scan PHI nodes to see if they all merge in each other or
9553       // the value.
9554       if (InValNo == NumOperandVals) {
9555         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9556         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9557           return ReplaceInstUsesWith(PN, NonPhiInVal);
9558       }
9559     }
9560   }
9561   return 0;
9562 }
9563
9564 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9565                                    Instruction *InsertPoint,
9566                                    InstCombiner *IC) {
9567   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9568   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9569   // We must cast correctly to the pointer type. Ensure that we
9570   // sign extend the integer value if it is smaller as this is
9571   // used for address computation.
9572   Instruction::CastOps opcode = 
9573      (VTySize < PtrSize ? Instruction::SExt :
9574       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9575   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9576 }
9577
9578
9579 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9580   Value *PtrOp = GEP.getOperand(0);
9581   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9582   // If so, eliminate the noop.
9583   if (GEP.getNumOperands() == 1)
9584     return ReplaceInstUsesWith(GEP, PtrOp);
9585
9586   if (isa<UndefValue>(GEP.getOperand(0)))
9587     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9588
9589   bool HasZeroPointerIndex = false;
9590   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9591     HasZeroPointerIndex = C->isNullValue();
9592
9593   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9594     return ReplaceInstUsesWith(GEP, PtrOp);
9595
9596   // Eliminate unneeded casts for indices.
9597   bool MadeChange = false;
9598   
9599   gep_type_iterator GTI = gep_type_begin(GEP);
9600   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9601        i != e; ++i, ++GTI) {
9602     if (isa<SequentialType>(*GTI)) {
9603       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9604         if (CI->getOpcode() == Instruction::ZExt ||
9605             CI->getOpcode() == Instruction::SExt) {
9606           const Type *SrcTy = CI->getOperand(0)->getType();
9607           // We can eliminate a cast from i32 to i64 iff the target 
9608           // is a 32-bit pointer target.
9609           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9610             MadeChange = true;
9611             *i = CI->getOperand(0);
9612           }
9613         }
9614       }
9615       // If we are using a wider index than needed for this platform, shrink it
9616       // to what we need.  If the incoming value needs a cast instruction,
9617       // insert it.  This explicit cast can make subsequent optimizations more
9618       // obvious.
9619       Value *Op = *i;
9620       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9621         if (Constant *C = dyn_cast<Constant>(Op)) {
9622           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9623           MadeChange = true;
9624         } else {
9625           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9626                                 GEP);
9627           *i = Op;
9628           MadeChange = true;
9629         }
9630       }
9631     }
9632   }
9633   if (MadeChange) return &GEP;
9634
9635   // If this GEP instruction doesn't move the pointer, and if the input operand
9636   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9637   // real input to the dest type.
9638   if (GEP.hasAllZeroIndices()) {
9639     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9640       // If the bitcast is of an allocation, and the allocation will be
9641       // converted to match the type of the cast, don't touch this.
9642       if (isa<AllocationInst>(BCI->getOperand(0))) {
9643         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9644         if (Instruction *I = visitBitCast(*BCI)) {
9645           if (I != BCI) {
9646             I->takeName(BCI);
9647             BCI->getParent()->getInstList().insert(BCI, I);
9648             ReplaceInstUsesWith(*BCI, I);
9649           }
9650           return &GEP;
9651         }
9652       }
9653       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9654     }
9655   }
9656   
9657   // Combine Indices - If the source pointer to this getelementptr instruction
9658   // is a getelementptr instruction, combine the indices of the two
9659   // getelementptr instructions into a single instruction.
9660   //
9661   SmallVector<Value*, 8> SrcGEPOperands;
9662   if (User *Src = dyn_castGetElementPtr(PtrOp))
9663     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9664
9665   if (!SrcGEPOperands.empty()) {
9666     // Note that if our source is a gep chain itself that we wait for that
9667     // chain to be resolved before we perform this transformation.  This
9668     // avoids us creating a TON of code in some cases.
9669     //
9670     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9671         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9672       return 0;   // Wait until our source is folded to completion.
9673
9674     SmallVector<Value*, 8> Indices;
9675
9676     // Find out whether the last index in the source GEP is a sequential idx.
9677     bool EndsWithSequential = false;
9678     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9679            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9680       EndsWithSequential = !isa<StructType>(*I);
9681
9682     // Can we combine the two pointer arithmetics offsets?
9683     if (EndsWithSequential) {
9684       // Replace: gep (gep %P, long B), long A, ...
9685       // With:    T = long A+B; gep %P, T, ...
9686       //
9687       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9688       if (SO1 == Constant::getNullValue(SO1->getType())) {
9689         Sum = GO1;
9690       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9691         Sum = SO1;
9692       } else {
9693         // If they aren't the same type, convert both to an integer of the
9694         // target's pointer size.
9695         if (SO1->getType() != GO1->getType()) {
9696           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9697             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9698           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9699             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9700           } else {
9701             unsigned PS = TD->getPointerSizeInBits();
9702             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9703               // Convert GO1 to SO1's type.
9704               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9705
9706             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9707               // Convert SO1 to GO1's type.
9708               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9709             } else {
9710               const Type *PT = TD->getIntPtrType();
9711               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9712               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9713             }
9714           }
9715         }
9716         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9717           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9718         else {
9719           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9720           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9721         }
9722       }
9723
9724       // Recycle the GEP we already have if possible.
9725       if (SrcGEPOperands.size() == 2) {
9726         GEP.setOperand(0, SrcGEPOperands[0]);
9727         GEP.setOperand(1, Sum);
9728         return &GEP;
9729       } else {
9730         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9731                        SrcGEPOperands.end()-1);
9732         Indices.push_back(Sum);
9733         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9734       }
9735     } else if (isa<Constant>(*GEP.idx_begin()) &&
9736                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9737                SrcGEPOperands.size() != 1) {
9738       // Otherwise we can do the fold if the first index of the GEP is a zero
9739       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9740                      SrcGEPOperands.end());
9741       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9742     }
9743
9744     if (!Indices.empty())
9745       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9746                                        Indices.end(), GEP.getName());
9747
9748   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9749     // GEP of global variable.  If all of the indices for this GEP are
9750     // constants, we can promote this to a constexpr instead of an instruction.
9751
9752     // Scan for nonconstants...
9753     SmallVector<Constant*, 8> Indices;
9754     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9755     for (; I != E && isa<Constant>(*I); ++I)
9756       Indices.push_back(cast<Constant>(*I));
9757
9758     if (I == E) {  // If they are all constants...
9759       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9760                                                     &Indices[0],Indices.size());
9761
9762       // Replace all uses of the GEP with the new constexpr...
9763       return ReplaceInstUsesWith(GEP, CE);
9764     }
9765   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9766     if (!isa<PointerType>(X->getType())) {
9767       // Not interesting.  Source pointer must be a cast from pointer.
9768     } else if (HasZeroPointerIndex) {
9769       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9770       // into     : GEP [10 x i8]* X, i32 0, ...
9771       //
9772       // This occurs when the program declares an array extern like "int X[];"
9773       //
9774       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9775       const PointerType *XTy = cast<PointerType>(X->getType());
9776       if (const ArrayType *XATy =
9777           dyn_cast<ArrayType>(XTy->getElementType()))
9778         if (const ArrayType *CATy =
9779             dyn_cast<ArrayType>(CPTy->getElementType()))
9780           if (CATy->getElementType() == XATy->getElementType()) {
9781             // At this point, we know that the cast source type is a pointer
9782             // to an array of the same type as the destination pointer
9783             // array.  Because the array type is never stepped over (there
9784             // is a leading zero) we can fold the cast into this GEP.
9785             GEP.setOperand(0, X);
9786             return &GEP;
9787           }
9788     } else if (GEP.getNumOperands() == 2) {
9789       // Transform things like:
9790       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9791       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9792       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9793       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9794       if (isa<ArrayType>(SrcElTy) &&
9795           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9796           TD->getABITypeSize(ResElTy)) {
9797         Value *Idx[2];
9798         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9799         Idx[1] = GEP.getOperand(1);
9800         Value *V = InsertNewInstBefore(
9801                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9802         // V and GEP are both pointer types --> BitCast
9803         return new BitCastInst(V, GEP.getType());
9804       }
9805       
9806       // Transform things like:
9807       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9808       //   (where tmp = 8*tmp2) into:
9809       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9810       
9811       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9812         uint64_t ArrayEltSize =
9813             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9814         
9815         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9816         // allow either a mul, shift, or constant here.
9817         Value *NewIdx = 0;
9818         ConstantInt *Scale = 0;
9819         if (ArrayEltSize == 1) {
9820           NewIdx = GEP.getOperand(1);
9821           Scale = ConstantInt::get(NewIdx->getType(), 1);
9822         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9823           NewIdx = ConstantInt::get(CI->getType(), 1);
9824           Scale = CI;
9825         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9826           if (Inst->getOpcode() == Instruction::Shl &&
9827               isa<ConstantInt>(Inst->getOperand(1))) {
9828             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9829             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9830             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9831             NewIdx = Inst->getOperand(0);
9832           } else if (Inst->getOpcode() == Instruction::Mul &&
9833                      isa<ConstantInt>(Inst->getOperand(1))) {
9834             Scale = cast<ConstantInt>(Inst->getOperand(1));
9835             NewIdx = Inst->getOperand(0);
9836           }
9837         }
9838         
9839         // If the index will be to exactly the right offset with the scale taken
9840         // out, perform the transformation. Note, we don't know whether Scale is
9841         // signed or not. We'll use unsigned version of division/modulo
9842         // operation after making sure Scale doesn't have the sign bit set.
9843         if (Scale && Scale->getSExtValue() >= 0LL &&
9844             Scale->getZExtValue() % ArrayEltSize == 0) {
9845           Scale = ConstantInt::get(Scale->getType(),
9846                                    Scale->getZExtValue() / ArrayEltSize);
9847           if (Scale->getZExtValue() != 1) {
9848             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9849                                                        false /*ZExt*/);
9850             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9851             NewIdx = InsertNewInstBefore(Sc, GEP);
9852           }
9853
9854           // Insert the new GEP instruction.
9855           Value *Idx[2];
9856           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9857           Idx[1] = NewIdx;
9858           Instruction *NewGEP =
9859             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9860           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9861           // The NewGEP must be pointer typed, so must the old one -> BitCast
9862           return new BitCastInst(NewGEP, GEP.getType());
9863         }
9864       }
9865     }
9866   }
9867
9868   return 0;
9869 }
9870
9871 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9872   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9873   if (AI.isArrayAllocation()) {  // Check C != 1
9874     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9875       const Type *NewTy = 
9876         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9877       AllocationInst *New = 0;
9878
9879       // Create and insert the replacement instruction...
9880       if (isa<MallocInst>(AI))
9881         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9882       else {
9883         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9884         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9885       }
9886
9887       InsertNewInstBefore(New, AI);
9888
9889       // Scan to the end of the allocation instructions, to skip over a block of
9890       // allocas if possible...
9891       //
9892       BasicBlock::iterator It = New;
9893       while (isa<AllocationInst>(*It)) ++It;
9894
9895       // Now that I is pointing to the first non-allocation-inst in the block,
9896       // insert our getelementptr instruction...
9897       //
9898       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9899       Value *Idx[2];
9900       Idx[0] = NullIdx;
9901       Idx[1] = NullIdx;
9902       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9903                                            New->getName()+".sub", It);
9904
9905       // Now make everything use the getelementptr instead of the original
9906       // allocation.
9907       return ReplaceInstUsesWith(AI, V);
9908     } else if (isa<UndefValue>(AI.getArraySize())) {
9909       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9910     }
9911   }
9912
9913   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9914   // Note that we only do this for alloca's, because malloc should allocate and
9915   // return a unique pointer, even for a zero byte allocation.
9916   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9917       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9918     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9919
9920   return 0;
9921 }
9922
9923 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9924   Value *Op = FI.getOperand(0);
9925
9926   // free undef -> unreachable.
9927   if (isa<UndefValue>(Op)) {
9928     // Insert a new store to null because we cannot modify the CFG here.
9929     new StoreInst(ConstantInt::getTrue(),
9930                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9931     return EraseInstFromFunction(FI);
9932   }
9933   
9934   // If we have 'free null' delete the instruction.  This can happen in stl code
9935   // when lots of inlining happens.
9936   if (isa<ConstantPointerNull>(Op))
9937     return EraseInstFromFunction(FI);
9938   
9939   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9940   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9941     FI.setOperand(0, CI->getOperand(0));
9942     return &FI;
9943   }
9944   
9945   // Change free (gep X, 0,0,0,0) into free(X)
9946   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9947     if (GEPI->hasAllZeroIndices()) {
9948       AddToWorkList(GEPI);
9949       FI.setOperand(0, GEPI->getOperand(0));
9950       return &FI;
9951     }
9952   }
9953   
9954   // Change free(malloc) into nothing, if the malloc has a single use.
9955   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9956     if (MI->hasOneUse()) {
9957       EraseInstFromFunction(FI);
9958       return EraseInstFromFunction(*MI);
9959     }
9960
9961   return 0;
9962 }
9963
9964
9965 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9966 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9967                                         const TargetData *TD) {
9968   User *CI = cast<User>(LI.getOperand(0));
9969   Value *CastOp = CI->getOperand(0);
9970
9971   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9972     // Instead of loading constant c string, use corresponding integer value
9973     // directly if string length is small enough.
9974     const std::string &Str = CE->getOperand(0)->getStringValue();
9975     if (!Str.empty()) {
9976       unsigned len = Str.length();
9977       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9978       unsigned numBits = Ty->getPrimitiveSizeInBits();
9979       // Replace LI with immediate integer store.
9980       if ((numBits >> 3) == len + 1) {
9981         APInt StrVal(numBits, 0);
9982         APInt SingleChar(numBits, 0);
9983         if (TD->isLittleEndian()) {
9984           for (signed i = len-1; i >= 0; i--) {
9985             SingleChar = (uint64_t) Str[i];
9986             StrVal = (StrVal << 8) | SingleChar;
9987           }
9988         } else {
9989           for (unsigned i = 0; i < len; i++) {
9990             SingleChar = (uint64_t) Str[i];
9991             StrVal = (StrVal << 8) | SingleChar;
9992           }
9993           // Append NULL at the end.
9994           SingleChar = 0;
9995           StrVal = (StrVal << 8) | SingleChar;
9996         }
9997         Value *NL = ConstantInt::get(StrVal);
9998         return IC.ReplaceInstUsesWith(LI, NL);
9999       }
10000     }
10001   }
10002
10003   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10004   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10005     const Type *SrcPTy = SrcTy->getElementType();
10006
10007     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10008          isa<VectorType>(DestPTy)) {
10009       // If the source is an array, the code below will not succeed.  Check to
10010       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10011       // constants.
10012       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10013         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10014           if (ASrcTy->getNumElements() != 0) {
10015             Value *Idxs[2];
10016             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10017             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10018             SrcTy = cast<PointerType>(CastOp->getType());
10019             SrcPTy = SrcTy->getElementType();
10020           }
10021
10022       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10023             isa<VectorType>(SrcPTy)) &&
10024           // Do not allow turning this into a load of an integer, which is then
10025           // casted to a pointer, this pessimizes pointer analysis a lot.
10026           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10027           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10028                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10029
10030         // Okay, we are casting from one integer or pointer type to another of
10031         // the same size.  Instead of casting the pointer before the load, cast
10032         // the result of the loaded value.
10033         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10034                                                              CI->getName(),
10035                                                          LI.isVolatile()),LI);
10036         // Now cast the result of the load.
10037         return new BitCastInst(NewLoad, LI.getType());
10038       }
10039     }
10040   }
10041   return 0;
10042 }
10043
10044 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10045 /// from this value cannot trap.  If it is not obviously safe to load from the
10046 /// specified pointer, we do a quick local scan of the basic block containing
10047 /// ScanFrom, to determine if the address is already accessed.
10048 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10049   // If it is an alloca it is always safe to load from.
10050   if (isa<AllocaInst>(V)) return true;
10051
10052   // If it is a global variable it is mostly safe to load from.
10053   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10054     // Don't try to evaluate aliases.  External weak GV can be null.
10055     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10056
10057   // Otherwise, be a little bit agressive by scanning the local block where we
10058   // want to check to see if the pointer is already being loaded or stored
10059   // from/to.  If so, the previous load or store would have already trapped,
10060   // so there is no harm doing an extra load (also, CSE will later eliminate
10061   // the load entirely).
10062   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10063
10064   while (BBI != E) {
10065     --BBI;
10066
10067     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10068       if (LI->getOperand(0) == V) return true;
10069     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10070       if (SI->getOperand(1) == V) return true;
10071
10072   }
10073   return false;
10074 }
10075
10076 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10077 /// until we find the underlying object a pointer is referring to or something
10078 /// we don't understand.  Note that the returned pointer may be offset from the
10079 /// input, because we ignore GEP indices.
10080 static Value *GetUnderlyingObject(Value *Ptr) {
10081   while (1) {
10082     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10083       if (CE->getOpcode() == Instruction::BitCast ||
10084           CE->getOpcode() == Instruction::GetElementPtr)
10085         Ptr = CE->getOperand(0);
10086       else
10087         return Ptr;
10088     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10089       Ptr = BCI->getOperand(0);
10090     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10091       Ptr = GEP->getOperand(0);
10092     } else {
10093       return Ptr;
10094     }
10095   }
10096 }
10097
10098 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10099   Value *Op = LI.getOperand(0);
10100
10101   // Attempt to improve the alignment.
10102   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10103   if (KnownAlign >
10104       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10105                                 LI.getAlignment()))
10106     LI.setAlignment(KnownAlign);
10107
10108   // load (cast X) --> cast (load X) iff safe
10109   if (isa<CastInst>(Op))
10110     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10111       return Res;
10112
10113   // None of the following transforms are legal for volatile loads.
10114   if (LI.isVolatile()) return 0;
10115   
10116   if (&LI.getParent()->front() != &LI) {
10117     BasicBlock::iterator BBI = &LI; --BBI;
10118     // If the instruction immediately before this is a store to the same
10119     // address, do a simple form of store->load forwarding.
10120     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10121       if (SI->getOperand(1) == LI.getOperand(0))
10122         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10123     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10124       if (LIB->getOperand(0) == LI.getOperand(0))
10125         return ReplaceInstUsesWith(LI, LIB);
10126   }
10127
10128   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10129     const Value *GEPI0 = GEPI->getOperand(0);
10130     // TODO: Consider a target hook for valid address spaces for this xform.
10131     if (isa<ConstantPointerNull>(GEPI0) &&
10132         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10133       // Insert a new store to null instruction before the load to indicate
10134       // that this code is not reachable.  We do this instead of inserting
10135       // an unreachable instruction directly because we cannot modify the
10136       // CFG.
10137       new StoreInst(UndefValue::get(LI.getType()),
10138                     Constant::getNullValue(Op->getType()), &LI);
10139       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10140     }
10141   } 
10142
10143   if (Constant *C = dyn_cast<Constant>(Op)) {
10144     // load null/undef -> undef
10145     // TODO: Consider a target hook for valid address spaces for this xform.
10146     if (isa<UndefValue>(C) || (C->isNullValue() && 
10147         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10148       // Insert a new store to null instruction before the load to indicate that
10149       // this code is not reachable.  We do this instead of inserting an
10150       // unreachable instruction directly because we cannot modify the CFG.
10151       new StoreInst(UndefValue::get(LI.getType()),
10152                     Constant::getNullValue(Op->getType()), &LI);
10153       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10154     }
10155
10156     // Instcombine load (constant global) into the value loaded.
10157     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10158       if (GV->isConstant() && !GV->isDeclaration())
10159         return ReplaceInstUsesWith(LI, GV->getInitializer());
10160
10161     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10162     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10163       if (CE->getOpcode() == Instruction::GetElementPtr) {
10164         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10165           if (GV->isConstant() && !GV->isDeclaration())
10166             if (Constant *V = 
10167                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10168               return ReplaceInstUsesWith(LI, V);
10169         if (CE->getOperand(0)->isNullValue()) {
10170           // Insert a new store to null instruction before the load to indicate
10171           // that this code is not reachable.  We do this instead of inserting
10172           // an unreachable instruction directly because we cannot modify the
10173           // CFG.
10174           new StoreInst(UndefValue::get(LI.getType()),
10175                         Constant::getNullValue(Op->getType()), &LI);
10176           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10177         }
10178
10179       } else if (CE->isCast()) {
10180         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10181           return Res;
10182       }
10183     }
10184   }
10185     
10186   // If this load comes from anywhere in a constant global, and if the global
10187   // is all undef or zero, we know what it loads.
10188   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10189     if (GV->isConstant() && GV->hasInitializer()) {
10190       if (GV->getInitializer()->isNullValue())
10191         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10192       else if (isa<UndefValue>(GV->getInitializer()))
10193         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10194     }
10195   }
10196
10197   if (Op->hasOneUse()) {
10198     // Change select and PHI nodes to select values instead of addresses: this
10199     // helps alias analysis out a lot, allows many others simplifications, and
10200     // exposes redundancy in the code.
10201     //
10202     // Note that we cannot do the transformation unless we know that the
10203     // introduced loads cannot trap!  Something like this is valid as long as
10204     // the condition is always false: load (select bool %C, int* null, int* %G),
10205     // but it would not be valid if we transformed it to load from null
10206     // unconditionally.
10207     //
10208     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10209       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10210       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10211           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10212         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10213                                      SI->getOperand(1)->getName()+".val"), LI);
10214         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10215                                      SI->getOperand(2)->getName()+".val"), LI);
10216         return SelectInst::Create(SI->getCondition(), V1, V2);
10217       }
10218
10219       // load (select (cond, null, P)) -> load P
10220       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10221         if (C->isNullValue()) {
10222           LI.setOperand(0, SI->getOperand(2));
10223           return &LI;
10224         }
10225
10226       // load (select (cond, P, null)) -> load P
10227       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10228         if (C->isNullValue()) {
10229           LI.setOperand(0, SI->getOperand(1));
10230           return &LI;
10231         }
10232     }
10233   }
10234   return 0;
10235 }
10236
10237 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10238 /// when possible.
10239 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10240   User *CI = cast<User>(SI.getOperand(1));
10241   Value *CastOp = CI->getOperand(0);
10242
10243   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10244   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10245     const Type *SrcPTy = SrcTy->getElementType();
10246
10247     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10248       // If the source is an array, the code below will not succeed.  Check to
10249       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10250       // constants.
10251       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10252         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10253           if (ASrcTy->getNumElements() != 0) {
10254             Value* Idxs[2];
10255             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10256             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10257             SrcTy = cast<PointerType>(CastOp->getType());
10258             SrcPTy = SrcTy->getElementType();
10259           }
10260
10261       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10262           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10263                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10264
10265         // Okay, we are casting from one integer or pointer type to another of
10266         // the same size.  Instead of casting the pointer before 
10267         // the store, cast the value to be stored.
10268         Value *NewCast;
10269         Value *SIOp0 = SI.getOperand(0);
10270         Instruction::CastOps opcode = Instruction::BitCast;
10271         const Type* CastSrcTy = SIOp0->getType();
10272         const Type* CastDstTy = SrcPTy;
10273         if (isa<PointerType>(CastDstTy)) {
10274           if (CastSrcTy->isInteger())
10275             opcode = Instruction::IntToPtr;
10276         } else if (isa<IntegerType>(CastDstTy)) {
10277           if (isa<PointerType>(SIOp0->getType()))
10278             opcode = Instruction::PtrToInt;
10279         }
10280         if (Constant *C = dyn_cast<Constant>(SIOp0))
10281           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10282         else
10283           NewCast = IC.InsertNewInstBefore(
10284             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10285             SI);
10286         return new StoreInst(NewCast, CastOp);
10287       }
10288     }
10289   }
10290   return 0;
10291 }
10292
10293 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10294   Value *Val = SI.getOperand(0);
10295   Value *Ptr = SI.getOperand(1);
10296
10297   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10298     EraseInstFromFunction(SI);
10299     ++NumCombined;
10300     return 0;
10301   }
10302   
10303   // If the RHS is an alloca with a single use, zapify the store, making the
10304   // alloca dead.
10305   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10306     if (isa<AllocaInst>(Ptr)) {
10307       EraseInstFromFunction(SI);
10308       ++NumCombined;
10309       return 0;
10310     }
10311     
10312     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10313       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10314           GEP->getOperand(0)->hasOneUse()) {
10315         EraseInstFromFunction(SI);
10316         ++NumCombined;
10317         return 0;
10318       }
10319   }
10320
10321   // Attempt to improve the alignment.
10322   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10323   if (KnownAlign >
10324       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10325                                 SI.getAlignment()))
10326     SI.setAlignment(KnownAlign);
10327
10328   // Do really simple DSE, to catch cases where there are several consequtive
10329   // stores to the same location, separated by a few arithmetic operations. This
10330   // situation often occurs with bitfield accesses.
10331   BasicBlock::iterator BBI = &SI;
10332   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10333        --ScanInsts) {
10334     --BBI;
10335     
10336     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10337       // Prev store isn't volatile, and stores to the same location?
10338       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10339         ++NumDeadStore;
10340         ++BBI;
10341         EraseInstFromFunction(*PrevSI);
10342         continue;
10343       }
10344       break;
10345     }
10346     
10347     // If this is a load, we have to stop.  However, if the loaded value is from
10348     // the pointer we're loading and is producing the pointer we're storing,
10349     // then *this* store is dead (X = load P; store X -> P).
10350     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10351       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10352         EraseInstFromFunction(SI);
10353         ++NumCombined;
10354         return 0;
10355       }
10356       // Otherwise, this is a load from some other location.  Stores before it
10357       // may not be dead.
10358       break;
10359     }
10360     
10361     // Don't skip over loads or things that can modify memory.
10362     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10363       break;
10364   }
10365   
10366   
10367   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10368
10369   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10370   if (isa<ConstantPointerNull>(Ptr)) {
10371     if (!isa<UndefValue>(Val)) {
10372       SI.setOperand(0, UndefValue::get(Val->getType()));
10373       if (Instruction *U = dyn_cast<Instruction>(Val))
10374         AddToWorkList(U);  // Dropped a use.
10375       ++NumCombined;
10376     }
10377     return 0;  // Do not modify these!
10378   }
10379
10380   // store undef, Ptr -> noop
10381   if (isa<UndefValue>(Val)) {
10382     EraseInstFromFunction(SI);
10383     ++NumCombined;
10384     return 0;
10385   }
10386
10387   // If the pointer destination is a cast, see if we can fold the cast into the
10388   // source instead.
10389   if (isa<CastInst>(Ptr))
10390     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10391       return Res;
10392   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10393     if (CE->isCast())
10394       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10395         return Res;
10396
10397   
10398   // If this store is the last instruction in the basic block, and if the block
10399   // ends with an unconditional branch, try to move it to the successor block.
10400   BBI = &SI; ++BBI;
10401   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10402     if (BI->isUnconditional())
10403       if (SimplifyStoreAtEndOfBlock(SI))
10404         return 0;  // xform done!
10405   
10406   return 0;
10407 }
10408
10409 /// SimplifyStoreAtEndOfBlock - Turn things like:
10410 ///   if () { *P = v1; } else { *P = v2 }
10411 /// into a phi node with a store in the successor.
10412 ///
10413 /// Simplify things like:
10414 ///   *P = v1; if () { *P = v2; }
10415 /// into a phi node with a store in the successor.
10416 ///
10417 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10418   BasicBlock *StoreBB = SI.getParent();
10419   
10420   // Check to see if the successor block has exactly two incoming edges.  If
10421   // so, see if the other predecessor contains a store to the same location.
10422   // if so, insert a PHI node (if needed) and move the stores down.
10423   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10424   
10425   // Determine whether Dest has exactly two predecessors and, if so, compute
10426   // the other predecessor.
10427   pred_iterator PI = pred_begin(DestBB);
10428   BasicBlock *OtherBB = 0;
10429   if (*PI != StoreBB)
10430     OtherBB = *PI;
10431   ++PI;
10432   if (PI == pred_end(DestBB))
10433     return false;
10434   
10435   if (*PI != StoreBB) {
10436     if (OtherBB)
10437       return false;
10438     OtherBB = *PI;
10439   }
10440   if (++PI != pred_end(DestBB))
10441     return false;
10442
10443   // Bail out if all the relevant blocks aren't distinct (this can happen,
10444   // for example, if SI is in an infinite loop)
10445   if (StoreBB == DestBB || OtherBB == DestBB)
10446     return false;
10447
10448   // Verify that the other block ends in a branch and is not otherwise empty.
10449   BasicBlock::iterator BBI = OtherBB->getTerminator();
10450   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10451   if (!OtherBr || BBI == OtherBB->begin())
10452     return false;
10453   
10454   // If the other block ends in an unconditional branch, check for the 'if then
10455   // else' case.  there is an instruction before the branch.
10456   StoreInst *OtherStore = 0;
10457   if (OtherBr->isUnconditional()) {
10458     // If this isn't a store, or isn't a store to the same location, bail out.
10459     --BBI;
10460     OtherStore = dyn_cast<StoreInst>(BBI);
10461     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10462       return false;
10463   } else {
10464     // Otherwise, the other block ended with a conditional branch. If one of the
10465     // destinations is StoreBB, then we have the if/then case.
10466     if (OtherBr->getSuccessor(0) != StoreBB && 
10467         OtherBr->getSuccessor(1) != StoreBB)
10468       return false;
10469     
10470     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10471     // if/then triangle.  See if there is a store to the same ptr as SI that
10472     // lives in OtherBB.
10473     for (;; --BBI) {
10474       // Check to see if we find the matching store.
10475       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10476         if (OtherStore->getOperand(1) != SI.getOperand(1))
10477           return false;
10478         break;
10479       }
10480       // If we find something that may be using or overwriting the stored
10481       // value, or if we run out of instructions, we can't do the xform.
10482       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10483           BBI == OtherBB->begin())
10484         return false;
10485     }
10486     
10487     // In order to eliminate the store in OtherBr, we have to
10488     // make sure nothing reads or overwrites the stored value in
10489     // StoreBB.
10490     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10491       // FIXME: This should really be AA driven.
10492       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10493         return false;
10494     }
10495   }
10496   
10497   // Insert a PHI node now if we need it.
10498   Value *MergedVal = OtherStore->getOperand(0);
10499   if (MergedVal != SI.getOperand(0)) {
10500     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10501     PN->reserveOperandSpace(2);
10502     PN->addIncoming(SI.getOperand(0), SI.getParent());
10503     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10504     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10505   }
10506   
10507   // Advance to a place where it is safe to insert the new store and
10508   // insert it.
10509   BBI = DestBB->getFirstNonPHI();
10510   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10511                                     OtherStore->isVolatile()), *BBI);
10512   
10513   // Nuke the old stores.
10514   EraseInstFromFunction(SI);
10515   EraseInstFromFunction(*OtherStore);
10516   ++NumCombined;
10517   return true;
10518 }
10519
10520
10521 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10522   // Change br (not X), label True, label False to: br X, label False, True
10523   Value *X = 0;
10524   BasicBlock *TrueDest;
10525   BasicBlock *FalseDest;
10526   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10527       !isa<Constant>(X)) {
10528     // Swap Destinations and condition...
10529     BI.setCondition(X);
10530     BI.setSuccessor(0, FalseDest);
10531     BI.setSuccessor(1, TrueDest);
10532     return &BI;
10533   }
10534
10535   // Cannonicalize fcmp_one -> fcmp_oeq
10536   FCmpInst::Predicate FPred; Value *Y;
10537   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10538                              TrueDest, FalseDest)))
10539     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10540          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10541       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10542       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10543       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10544       NewSCC->takeName(I);
10545       // Swap Destinations and condition...
10546       BI.setCondition(NewSCC);
10547       BI.setSuccessor(0, FalseDest);
10548       BI.setSuccessor(1, TrueDest);
10549       RemoveFromWorkList(I);
10550       I->eraseFromParent();
10551       AddToWorkList(NewSCC);
10552       return &BI;
10553     }
10554
10555   // Cannonicalize icmp_ne -> icmp_eq
10556   ICmpInst::Predicate IPred;
10557   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10558                       TrueDest, FalseDest)))
10559     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10560          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10561          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10562       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10563       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10564       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10565       NewSCC->takeName(I);
10566       // Swap Destinations and condition...
10567       BI.setCondition(NewSCC);
10568       BI.setSuccessor(0, FalseDest);
10569       BI.setSuccessor(1, TrueDest);
10570       RemoveFromWorkList(I);
10571       I->eraseFromParent();;
10572       AddToWorkList(NewSCC);
10573       return &BI;
10574     }
10575
10576   return 0;
10577 }
10578
10579 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10580   Value *Cond = SI.getCondition();
10581   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10582     if (I->getOpcode() == Instruction::Add)
10583       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10584         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10585         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10586           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10587                                                 AddRHS));
10588         SI.setOperand(0, I->getOperand(0));
10589         AddToWorkList(I);
10590         return &SI;
10591       }
10592   }
10593   return 0;
10594 }
10595
10596 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10597   // See if we are trying to extract a known value. If so, use that instead.
10598   if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10599                                      EV.idx_end(), &EV))
10600     return ReplaceInstUsesWith(EV, Elt);
10601
10602   // No changes
10603   return 0;
10604 }
10605
10606 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10607 /// is to leave as a vector operation.
10608 static bool CheapToScalarize(Value *V, bool isConstant) {
10609   if (isa<ConstantAggregateZero>(V)) 
10610     return true;
10611   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10612     if (isConstant) return true;
10613     // If all elts are the same, we can extract.
10614     Constant *Op0 = C->getOperand(0);
10615     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10616       if (C->getOperand(i) != Op0)
10617         return false;
10618     return true;
10619   }
10620   Instruction *I = dyn_cast<Instruction>(V);
10621   if (!I) return false;
10622   
10623   // Insert element gets simplified to the inserted element or is deleted if
10624   // this is constant idx extract element and its a constant idx insertelt.
10625   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10626       isa<ConstantInt>(I->getOperand(2)))
10627     return true;
10628   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10629     return true;
10630   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10631     if (BO->hasOneUse() &&
10632         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10633          CheapToScalarize(BO->getOperand(1), isConstant)))
10634       return true;
10635   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10636     if (CI->hasOneUse() &&
10637         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10638          CheapToScalarize(CI->getOperand(1), isConstant)))
10639       return true;
10640   
10641   return false;
10642 }
10643
10644 /// Read and decode a shufflevector mask.
10645 ///
10646 /// It turns undef elements into values that are larger than the number of
10647 /// elements in the input.
10648 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10649   unsigned NElts = SVI->getType()->getNumElements();
10650   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10651     return std::vector<unsigned>(NElts, 0);
10652   if (isa<UndefValue>(SVI->getOperand(2)))
10653     return std::vector<unsigned>(NElts, 2*NElts);
10654
10655   std::vector<unsigned> Result;
10656   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10657   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10658     if (isa<UndefValue>(*i))
10659       Result.push_back(NElts*2);  // undef -> 8
10660     else
10661       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10662   return Result;
10663 }
10664
10665 /// FindScalarElement - Given a vector and an element number, see if the scalar
10666 /// value is already around as a register, for example if it were inserted then
10667 /// extracted from the vector.
10668 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10669   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10670   const VectorType *PTy = cast<VectorType>(V->getType());
10671   unsigned Width = PTy->getNumElements();
10672   if (EltNo >= Width)  // Out of range access.
10673     return UndefValue::get(PTy->getElementType());
10674   
10675   if (isa<UndefValue>(V))
10676     return UndefValue::get(PTy->getElementType());
10677   else if (isa<ConstantAggregateZero>(V))
10678     return Constant::getNullValue(PTy->getElementType());
10679   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10680     return CP->getOperand(EltNo);
10681   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10682     // If this is an insert to a variable element, we don't know what it is.
10683     if (!isa<ConstantInt>(III->getOperand(2))) 
10684       return 0;
10685     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10686     
10687     // If this is an insert to the element we are looking for, return the
10688     // inserted value.
10689     if (EltNo == IIElt) 
10690       return III->getOperand(1);
10691     
10692     // Otherwise, the insertelement doesn't modify the value, recurse on its
10693     // vector input.
10694     return FindScalarElement(III->getOperand(0), EltNo);
10695   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10696     unsigned InEl = getShuffleMask(SVI)[EltNo];
10697     if (InEl < Width)
10698       return FindScalarElement(SVI->getOperand(0), InEl);
10699     else if (InEl < Width*2)
10700       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10701     else
10702       return UndefValue::get(PTy->getElementType());
10703   }
10704   
10705   // Otherwise, we don't know.
10706   return 0;
10707 }
10708
10709 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10710   // If vector val is undef, replace extract with scalar undef.
10711   if (isa<UndefValue>(EI.getOperand(0)))
10712     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10713
10714   // If vector val is constant 0, replace extract with scalar 0.
10715   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10716     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10717   
10718   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10719     // If vector val is constant with all elements the same, replace EI with
10720     // that element. When the elements are not identical, we cannot replace yet
10721     // (we do that below, but only when the index is constant).
10722     Constant *op0 = C->getOperand(0);
10723     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10724       if (C->getOperand(i) != op0) {
10725         op0 = 0; 
10726         break;
10727       }
10728     if (op0)
10729       return ReplaceInstUsesWith(EI, op0);
10730   }
10731   
10732   // If extracting a specified index from the vector, see if we can recursively
10733   // find a previously computed scalar that was inserted into the vector.
10734   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10735     unsigned IndexVal = IdxC->getZExtValue();
10736     unsigned VectorWidth = 
10737       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10738       
10739     // If this is extracting an invalid index, turn this into undef, to avoid
10740     // crashing the code below.
10741     if (IndexVal >= VectorWidth)
10742       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10743     
10744     // This instruction only demands the single element from the input vector.
10745     // If the input vector has a single use, simplify it based on this use
10746     // property.
10747     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10748       uint64_t UndefElts;
10749       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10750                                                 1 << IndexVal,
10751                                                 UndefElts)) {
10752         EI.setOperand(0, V);
10753         return &EI;
10754       }
10755     }
10756     
10757     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10758       return ReplaceInstUsesWith(EI, Elt);
10759     
10760     // If the this extractelement is directly using a bitcast from a vector of
10761     // the same number of elements, see if we can find the source element from
10762     // it.  In this case, we will end up needing to bitcast the scalars.
10763     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10764       if (const VectorType *VT = 
10765               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10766         if (VT->getNumElements() == VectorWidth)
10767           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10768             return new BitCastInst(Elt, EI.getType());
10769     }
10770   }
10771   
10772   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10773     if (I->hasOneUse()) {
10774       // Push extractelement into predecessor operation if legal and
10775       // profitable to do so
10776       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10777         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10778         if (CheapToScalarize(BO, isConstantElt)) {
10779           ExtractElementInst *newEI0 = 
10780             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10781                                    EI.getName()+".lhs");
10782           ExtractElementInst *newEI1 =
10783             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10784                                    EI.getName()+".rhs");
10785           InsertNewInstBefore(newEI0, EI);
10786           InsertNewInstBefore(newEI1, EI);
10787           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10788         }
10789       } else if (isa<LoadInst>(I)) {
10790         unsigned AS = 
10791           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10792         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10793                                          PointerType::get(EI.getType(), AS),EI);
10794         GetElementPtrInst *GEP =
10795           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10796         InsertNewInstBefore(GEP, EI);
10797         return new LoadInst(GEP);
10798       }
10799     }
10800     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10801       // Extracting the inserted element?
10802       if (IE->getOperand(2) == EI.getOperand(1))
10803         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10804       // If the inserted and extracted elements are constants, they must not
10805       // be the same value, extract from the pre-inserted value instead.
10806       if (isa<Constant>(IE->getOperand(2)) &&
10807           isa<Constant>(EI.getOperand(1))) {
10808         AddUsesToWorkList(EI);
10809         EI.setOperand(0, IE->getOperand(0));
10810         return &EI;
10811       }
10812     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10813       // If this is extracting an element from a shufflevector, figure out where
10814       // it came from and extract from the appropriate input element instead.
10815       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10816         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10817         Value *Src;
10818         if (SrcIdx < SVI->getType()->getNumElements())
10819           Src = SVI->getOperand(0);
10820         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10821           SrcIdx -= SVI->getType()->getNumElements();
10822           Src = SVI->getOperand(1);
10823         } else {
10824           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10825         }
10826         return new ExtractElementInst(Src, SrcIdx);
10827       }
10828     }
10829   }
10830   return 0;
10831 }
10832
10833 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10834 /// elements from either LHS or RHS, return the shuffle mask and true. 
10835 /// Otherwise, return false.
10836 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10837                                          std::vector<Constant*> &Mask) {
10838   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10839          "Invalid CollectSingleShuffleElements");
10840   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10841
10842   if (isa<UndefValue>(V)) {
10843     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10844     return true;
10845   } else if (V == LHS) {
10846     for (unsigned i = 0; i != NumElts; ++i)
10847       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10848     return true;
10849   } else if (V == RHS) {
10850     for (unsigned i = 0; i != NumElts; ++i)
10851       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10852     return true;
10853   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10854     // If this is an insert of an extract from some other vector, include it.
10855     Value *VecOp    = IEI->getOperand(0);
10856     Value *ScalarOp = IEI->getOperand(1);
10857     Value *IdxOp    = IEI->getOperand(2);
10858     
10859     if (!isa<ConstantInt>(IdxOp))
10860       return false;
10861     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10862     
10863     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10864       // Okay, we can handle this if the vector we are insertinting into is
10865       // transitively ok.
10866       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10867         // If so, update the mask to reflect the inserted undef.
10868         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10869         return true;
10870       }      
10871     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10872       if (isa<ConstantInt>(EI->getOperand(1)) &&
10873           EI->getOperand(0)->getType() == V->getType()) {
10874         unsigned ExtractedIdx =
10875           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10876         
10877         // This must be extracting from either LHS or RHS.
10878         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10879           // Okay, we can handle this if the vector we are insertinting into is
10880           // transitively ok.
10881           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10882             // If so, update the mask to reflect the inserted value.
10883             if (EI->getOperand(0) == LHS) {
10884               Mask[InsertedIdx & (NumElts-1)] = 
10885                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10886             } else {
10887               assert(EI->getOperand(0) == RHS);
10888               Mask[InsertedIdx & (NumElts-1)] = 
10889                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10890               
10891             }
10892             return true;
10893           }
10894         }
10895       }
10896     }
10897   }
10898   // TODO: Handle shufflevector here!
10899   
10900   return false;
10901 }
10902
10903 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10904 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10905 /// that computes V and the LHS value of the shuffle.
10906 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10907                                      Value *&RHS) {
10908   assert(isa<VectorType>(V->getType()) && 
10909          (RHS == 0 || V->getType() == RHS->getType()) &&
10910          "Invalid shuffle!");
10911   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10912
10913   if (isa<UndefValue>(V)) {
10914     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10915     return V;
10916   } else if (isa<ConstantAggregateZero>(V)) {
10917     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10918     return V;
10919   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10920     // If this is an insert of an extract from some other vector, include it.
10921     Value *VecOp    = IEI->getOperand(0);
10922     Value *ScalarOp = IEI->getOperand(1);
10923     Value *IdxOp    = IEI->getOperand(2);
10924     
10925     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10926       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10927           EI->getOperand(0)->getType() == V->getType()) {
10928         unsigned ExtractedIdx =
10929           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10930         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10931         
10932         // Either the extracted from or inserted into vector must be RHSVec,
10933         // otherwise we'd end up with a shuffle of three inputs.
10934         if (EI->getOperand(0) == RHS || RHS == 0) {
10935           RHS = EI->getOperand(0);
10936           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10937           Mask[InsertedIdx & (NumElts-1)] = 
10938             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10939           return V;
10940         }
10941         
10942         if (VecOp == RHS) {
10943           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10944           // Everything but the extracted element is replaced with the RHS.
10945           for (unsigned i = 0; i != NumElts; ++i) {
10946             if (i != InsertedIdx)
10947               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10948           }
10949           return V;
10950         }
10951         
10952         // If this insertelement is a chain that comes from exactly these two
10953         // vectors, return the vector and the effective shuffle.
10954         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10955           return EI->getOperand(0);
10956         
10957       }
10958     }
10959   }
10960   // TODO: Handle shufflevector here!
10961   
10962   // Otherwise, can't do anything fancy.  Return an identity vector.
10963   for (unsigned i = 0; i != NumElts; ++i)
10964     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10965   return V;
10966 }
10967
10968 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10969   Value *VecOp    = IE.getOperand(0);
10970   Value *ScalarOp = IE.getOperand(1);
10971   Value *IdxOp    = IE.getOperand(2);
10972   
10973   // Inserting an undef or into an undefined place, remove this.
10974   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10975     ReplaceInstUsesWith(IE, VecOp);
10976   
10977   // If the inserted element was extracted from some other vector, and if the 
10978   // indexes are constant, try to turn this into a shufflevector operation.
10979   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10980     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10981         EI->getOperand(0)->getType() == IE.getType()) {
10982       unsigned NumVectorElts = IE.getType()->getNumElements();
10983       unsigned ExtractedIdx =
10984         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10985       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10986       
10987       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10988         return ReplaceInstUsesWith(IE, VecOp);
10989       
10990       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10991         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10992       
10993       // If we are extracting a value from a vector, then inserting it right
10994       // back into the same place, just use the input vector.
10995       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10996         return ReplaceInstUsesWith(IE, VecOp);      
10997       
10998       // We could theoretically do this for ANY input.  However, doing so could
10999       // turn chains of insertelement instructions into a chain of shufflevector
11000       // instructions, and right now we do not merge shufflevectors.  As such,
11001       // only do this in a situation where it is clear that there is benefit.
11002       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11003         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11004         // the values of VecOp, except then one read from EIOp0.
11005         // Build a new shuffle mask.
11006         std::vector<Constant*> Mask;
11007         if (isa<UndefValue>(VecOp))
11008           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11009         else {
11010           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11011           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11012                                                        NumVectorElts));
11013         } 
11014         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11015         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11016                                      ConstantVector::get(Mask));
11017       }
11018       
11019       // If this insertelement isn't used by some other insertelement, turn it
11020       // (and any insertelements it points to), into one big shuffle.
11021       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11022         std::vector<Constant*> Mask;
11023         Value *RHS = 0;
11024         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11025         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11026         // We now have a shuffle of LHS, RHS, Mask.
11027         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11028       }
11029     }
11030   }
11031
11032   return 0;
11033 }
11034
11035
11036 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11037   Value *LHS = SVI.getOperand(0);
11038   Value *RHS = SVI.getOperand(1);
11039   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11040
11041   bool MadeChange = false;
11042   
11043   // Undefined shuffle mask -> undefined value.
11044   if (isa<UndefValue>(SVI.getOperand(2)))
11045     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11046   
11047   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11048   // the undef, change them to undefs.
11049   if (isa<UndefValue>(SVI.getOperand(1))) {
11050     // Scan to see if there are any references to the RHS.  If so, replace them
11051     // with undef element refs and set MadeChange to true.
11052     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11053       if (Mask[i] >= e && Mask[i] != 2*e) {
11054         Mask[i] = 2*e;
11055         MadeChange = true;
11056       }
11057     }
11058     
11059     if (MadeChange) {
11060       // Remap any references to RHS to use LHS.
11061       std::vector<Constant*> Elts;
11062       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11063         if (Mask[i] == 2*e)
11064           Elts.push_back(UndefValue::get(Type::Int32Ty));
11065         else
11066           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11067       }
11068       SVI.setOperand(2, ConstantVector::get(Elts));
11069     }
11070   }
11071   
11072   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11073   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11074   if (LHS == RHS || isa<UndefValue>(LHS)) {
11075     if (isa<UndefValue>(LHS) && LHS == RHS) {
11076       // shuffle(undef,undef,mask) -> undef.
11077       return ReplaceInstUsesWith(SVI, LHS);
11078     }
11079     
11080     // Remap any references to RHS to use LHS.
11081     std::vector<Constant*> Elts;
11082     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11083       if (Mask[i] >= 2*e)
11084         Elts.push_back(UndefValue::get(Type::Int32Ty));
11085       else {
11086         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11087             (Mask[i] <  e && isa<UndefValue>(LHS)))
11088           Mask[i] = 2*e;     // Turn into undef.
11089         else
11090           Mask[i] &= (e-1);  // Force to LHS.
11091         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11092       }
11093     }
11094     SVI.setOperand(0, SVI.getOperand(1));
11095     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11096     SVI.setOperand(2, ConstantVector::get(Elts));
11097     LHS = SVI.getOperand(0);
11098     RHS = SVI.getOperand(1);
11099     MadeChange = true;
11100   }
11101   
11102   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11103   bool isLHSID = true, isRHSID = true;
11104     
11105   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11106     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11107     // Is this an identity shuffle of the LHS value?
11108     isLHSID &= (Mask[i] == i);
11109       
11110     // Is this an identity shuffle of the RHS value?
11111     isRHSID &= (Mask[i]-e == i);
11112   }
11113
11114   // Eliminate identity shuffles.
11115   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11116   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11117   
11118   // If the LHS is a shufflevector itself, see if we can combine it with this
11119   // one without producing an unusual shuffle.  Here we are really conservative:
11120   // we are absolutely afraid of producing a shuffle mask not in the input
11121   // program, because the code gen may not be smart enough to turn a merged
11122   // shuffle into two specific shuffles: it may produce worse code.  As such,
11123   // we only merge two shuffles if the result is one of the two input shuffle
11124   // masks.  In this case, merging the shuffles just removes one instruction,
11125   // which we know is safe.  This is good for things like turning:
11126   // (splat(splat)) -> splat.
11127   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11128     if (isa<UndefValue>(RHS)) {
11129       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11130
11131       std::vector<unsigned> NewMask;
11132       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11133         if (Mask[i] >= 2*e)
11134           NewMask.push_back(2*e);
11135         else
11136           NewMask.push_back(LHSMask[Mask[i]]);
11137       
11138       // If the result mask is equal to the src shuffle or this shuffle mask, do
11139       // the replacement.
11140       if (NewMask == LHSMask || NewMask == Mask) {
11141         std::vector<Constant*> Elts;
11142         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11143           if (NewMask[i] >= e*2) {
11144             Elts.push_back(UndefValue::get(Type::Int32Ty));
11145           } else {
11146             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11147           }
11148         }
11149         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11150                                      LHSSVI->getOperand(1),
11151                                      ConstantVector::get(Elts));
11152       }
11153     }
11154   }
11155
11156   return MadeChange ? &SVI : 0;
11157 }
11158
11159
11160
11161
11162 /// TryToSinkInstruction - Try to move the specified instruction from its
11163 /// current block into the beginning of DestBlock, which can only happen if it's
11164 /// safe to move the instruction past all of the instructions between it and the
11165 /// end of its block.
11166 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11167   assert(I->hasOneUse() && "Invariants didn't hold!");
11168
11169   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11170   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11171     return false;
11172
11173   // Do not sink alloca instructions out of the entry block.
11174   if (isa<AllocaInst>(I) && I->getParent() ==
11175         &DestBlock->getParent()->getEntryBlock())
11176     return false;
11177
11178   // We can only sink load instructions if there is nothing between the load and
11179   // the end of block that could change the value.
11180   if (I->mayReadFromMemory()) {
11181     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11182          Scan != E; ++Scan)
11183       if (Scan->mayWriteToMemory())
11184         return false;
11185   }
11186
11187   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11188
11189   I->moveBefore(InsertPos);
11190   ++NumSunkInst;
11191   return true;
11192 }
11193
11194
11195 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11196 /// all reachable code to the worklist.
11197 ///
11198 /// This has a couple of tricks to make the code faster and more powerful.  In
11199 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11200 /// them to the worklist (this significantly speeds up instcombine on code where
11201 /// many instructions are dead or constant).  Additionally, if we find a branch
11202 /// whose condition is a known constant, we only visit the reachable successors.
11203 ///
11204 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11205                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11206                                        InstCombiner &IC,
11207                                        const TargetData *TD) {
11208   std::vector<BasicBlock*> Worklist;
11209   Worklist.push_back(BB);
11210
11211   while (!Worklist.empty()) {
11212     BB = Worklist.back();
11213     Worklist.pop_back();
11214     
11215     // We have now visited this block!  If we've already been here, ignore it.
11216     if (!Visited.insert(BB)) continue;
11217     
11218     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11219       Instruction *Inst = BBI++;
11220       
11221       // DCE instruction if trivially dead.
11222       if (isInstructionTriviallyDead(Inst)) {
11223         ++NumDeadInst;
11224         DOUT << "IC: DCE: " << *Inst;
11225         Inst->eraseFromParent();
11226         continue;
11227       }
11228       
11229       // ConstantProp instruction if trivially constant.
11230       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11231         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11232         Inst->replaceAllUsesWith(C);
11233         ++NumConstProp;
11234         Inst->eraseFromParent();
11235         continue;
11236       }
11237      
11238       IC.AddToWorkList(Inst);
11239     }
11240
11241     // Recursively visit successors.  If this is a branch or switch on a
11242     // constant, only visit the reachable successor.
11243     TerminatorInst *TI = BB->getTerminator();
11244     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11245       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11246         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11247         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11248         Worklist.push_back(ReachableBB);
11249         continue;
11250       }
11251     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11252       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11253         // See if this is an explicit destination.
11254         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11255           if (SI->getCaseValue(i) == Cond) {
11256             BasicBlock *ReachableBB = SI->getSuccessor(i);
11257             Worklist.push_back(ReachableBB);
11258             continue;
11259           }
11260         
11261         // Otherwise it is the default destination.
11262         Worklist.push_back(SI->getSuccessor(0));
11263         continue;
11264       }
11265     }
11266     
11267     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11268       Worklist.push_back(TI->getSuccessor(i));
11269   }
11270 }
11271
11272 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11273   bool Changed = false;
11274   TD = &getAnalysis<TargetData>();
11275   
11276   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11277              << F.getNameStr() << "\n");
11278
11279   {
11280     // Do a depth-first traversal of the function, populate the worklist with
11281     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11282     // track of which blocks we visit.
11283     SmallPtrSet<BasicBlock*, 64> Visited;
11284     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11285
11286     // Do a quick scan over the function.  If we find any blocks that are
11287     // unreachable, remove any instructions inside of them.  This prevents
11288     // the instcombine code from having to deal with some bad special cases.
11289     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11290       if (!Visited.count(BB)) {
11291         Instruction *Term = BB->getTerminator();
11292         while (Term != BB->begin()) {   // Remove instrs bottom-up
11293           BasicBlock::iterator I = Term; --I;
11294
11295           DOUT << "IC: DCE: " << *I;
11296           ++NumDeadInst;
11297
11298           if (!I->use_empty())
11299             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11300           I->eraseFromParent();
11301         }
11302       }
11303   }
11304
11305   while (!Worklist.empty()) {
11306     Instruction *I = RemoveOneFromWorkList();
11307     if (I == 0) continue;  // skip null values.
11308
11309     // Check to see if we can DCE the instruction.
11310     if (isInstructionTriviallyDead(I)) {
11311       // Add operands to the worklist.
11312       if (I->getNumOperands() < 4)
11313         AddUsesToWorkList(*I);
11314       ++NumDeadInst;
11315
11316       DOUT << "IC: DCE: " << *I;
11317
11318       I->eraseFromParent();
11319       RemoveFromWorkList(I);
11320       continue;
11321     }
11322
11323     // Instruction isn't dead, see if we can constant propagate it.
11324     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11325       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11326
11327       // Add operands to the worklist.
11328       AddUsesToWorkList(*I);
11329       ReplaceInstUsesWith(*I, C);
11330
11331       ++NumConstProp;
11332       I->eraseFromParent();
11333       RemoveFromWorkList(I);
11334       continue;
11335     }
11336
11337     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11338       // See if we can constant fold its operands.
11339       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11340         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11341           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11342             i->set(NewC);
11343         }
11344       }
11345     }
11346
11347     // See if we can trivially sink this instruction to a successor basic block.
11348     // FIXME: Remove GetResultInst test when first class support for aggregates
11349     // is implemented.
11350     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11351       BasicBlock *BB = I->getParent();
11352       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11353       if (UserParent != BB) {
11354         bool UserIsSuccessor = false;
11355         // See if the user is one of our successors.
11356         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11357           if (*SI == UserParent) {
11358             UserIsSuccessor = true;
11359             break;
11360           }
11361
11362         // If the user is one of our immediate successors, and if that successor
11363         // only has us as a predecessors (we'd have to split the critical edge
11364         // otherwise), we can keep going.
11365         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11366             next(pred_begin(UserParent)) == pred_end(UserParent))
11367           // Okay, the CFG is simple enough, try to sink this instruction.
11368           Changed |= TryToSinkInstruction(I, UserParent);
11369       }
11370     }
11371
11372     // Now that we have an instruction, try combining it to simplify it...
11373 #ifndef NDEBUG
11374     std::string OrigI;
11375 #endif
11376     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11377     if (Instruction *Result = visit(*I)) {
11378       ++NumCombined;
11379       // Should we replace the old instruction with a new one?
11380       if (Result != I) {
11381         DOUT << "IC: Old = " << *I
11382              << "    New = " << *Result;
11383
11384         // Everything uses the new instruction now.
11385         I->replaceAllUsesWith(Result);
11386
11387         // Push the new instruction and any users onto the worklist.
11388         AddToWorkList(Result);
11389         AddUsersToWorkList(*Result);
11390
11391         // Move the name to the new instruction first.
11392         Result->takeName(I);
11393
11394         // Insert the new instruction into the basic block...
11395         BasicBlock *InstParent = I->getParent();
11396         BasicBlock::iterator InsertPos = I;
11397
11398         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11399           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11400             ++InsertPos;
11401
11402         InstParent->getInstList().insert(InsertPos, Result);
11403
11404         // Make sure that we reprocess all operands now that we reduced their
11405         // use counts.
11406         AddUsesToWorkList(*I);
11407
11408         // Instructions can end up on the worklist more than once.  Make sure
11409         // we do not process an instruction that has been deleted.
11410         RemoveFromWorkList(I);
11411
11412         // Erase the old instruction.
11413         InstParent->getInstList().erase(I);
11414       } else {
11415 #ifndef NDEBUG
11416         DOUT << "IC: Mod = " << OrigI
11417              << "    New = " << *I;
11418 #endif
11419
11420         // If the instruction was modified, it's possible that it is now dead.
11421         // if so, remove it.
11422         if (isInstructionTriviallyDead(I)) {
11423           // Make sure we process all operands now that we are reducing their
11424           // use counts.
11425           AddUsesToWorkList(*I);
11426
11427           // Instructions may end up in the worklist more than once.  Erase all
11428           // occurrences of this instruction.
11429           RemoveFromWorkList(I);
11430           I->eraseFromParent();
11431         } else {
11432           AddToWorkList(I);
11433           AddUsersToWorkList(*I);
11434         }
11435       }
11436       Changed = true;
11437     }
11438   }
11439
11440   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11441     
11442   // Do an explicit clear, this shrinks the map if needed.
11443   WorklistMap.clear();
11444   return Changed;
11445 }
11446
11447
11448 bool InstCombiner::runOnFunction(Function &F) {
11449   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11450   
11451   bool EverMadeChange = false;
11452
11453   // Iterate while there is work to do.
11454   unsigned Iteration = 0;
11455   while (DoOneIteration(F, Iteration++))
11456     EverMadeChange = true;
11457   return EverMadeChange;
11458 }
11459
11460 FunctionPass *llvm::createInstructionCombiningPass() {
11461   return new InstCombiner();
11462 }
11463