For PR1205:
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 algebraic
12 // 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/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <set>
60 using namespace llvm;
61 using namespace llvm::PatternMatch;
62
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
68
69 namespace {
70   class VISIBILITY_HIDDEN InstCombiner
71     : public FunctionPass,
72       public InstVisitor<InstCombiner, Instruction*> {
73     // Worklist of all of the instructions that need to be simplified.
74     std::vector<Instruction*> Worklist;
75     DenseMap<Instruction*, unsigned> WorklistMap;
76     TargetData *TD;
77     bool MustPreserveLCSSA;
78   public:
79     /// AddToWorkList - Add the specified instruction to the worklist if it
80     /// isn't already in it.
81     void AddToWorkList(Instruction *I) {
82       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83         Worklist.push_back(I);
84     }
85     
86     // RemoveFromWorkList - remove I from the worklist if it exists.
87     void RemoveFromWorkList(Instruction *I) {
88       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89       if (It == WorklistMap.end()) return; // Not in worklist.
90       
91       // Don't bother moving everything down, just null out the slot.
92       Worklist[It->second] = 0;
93       
94       WorklistMap.erase(It);
95     }
96     
97     Instruction *RemoveOneFromWorkList() {
98       Instruction *I = Worklist.back();
99       Worklist.pop_back();
100       WorklistMap.erase(I);
101       return I;
102     }
103
104     
105     /// AddUsersToWorkList - When an instruction is simplified, add all users of
106     /// the instruction to the work lists because they might get more simplified
107     /// now.
108     ///
109     void AddUsersToWorkList(Value &I) {
110       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
111            UI != UE; ++UI)
112         AddToWorkList(cast<Instruction>(*UI));
113     }
114
115     /// AddUsesToWorkList - When an instruction is simplified, add operands to
116     /// the work lists because they might get more simplified now.
117     ///
118     void AddUsesToWorkList(Instruction &I) {
119       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
121           AddToWorkList(Op);
122     }
123     
124     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125     /// dead.  Add all of its operands to the worklist, turning them into
126     /// undef's to reduce the number of uses of those instructions.
127     ///
128     /// Return the specified operand before it is turned into an undef.
129     ///
130     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131       Value *R = I.getOperand(op);
132       
133       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
135           AddToWorkList(Op);
136           // Set the operand to undef to drop the use.
137           I.setOperand(i, UndefValue::get(Op->getType()));
138         }
139       
140       return R;
141     }
142
143   public:
144     virtual bool runOnFunction(Function &F);
145     
146     bool DoOneIteration(Function &F, unsigned ItNum);
147
148     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149       AU.addRequired<TargetData>();
150       AU.addPreservedID(LCSSAID);
151       AU.setPreservesCFG();
152     }
153
154     TargetData &getTargetData() const { return *TD; }
155
156     // Visitation implementation - Implement instruction combining for different
157     // instruction types.  The semantics are as follows:
158     // Return Value:
159     //    null        - No change was made
160     //     I          - Change was made, I is still valid, I may be dead though
161     //   otherwise    - Change was made, replace I with returned instruction
162     //
163     Instruction *visitAdd(BinaryOperator &I);
164     Instruction *visitSub(BinaryOperator &I);
165     Instruction *visitMul(BinaryOperator &I);
166     Instruction *visitURem(BinaryOperator &I);
167     Instruction *visitSRem(BinaryOperator &I);
168     Instruction *visitFRem(BinaryOperator &I);
169     Instruction *commonRemTransforms(BinaryOperator &I);
170     Instruction *commonIRemTransforms(BinaryOperator &I);
171     Instruction *commonDivTransforms(BinaryOperator &I);
172     Instruction *commonIDivTransforms(BinaryOperator &I);
173     Instruction *visitUDiv(BinaryOperator &I);
174     Instruction *visitSDiv(BinaryOperator &I);
175     Instruction *visitFDiv(BinaryOperator &I);
176     Instruction *visitAnd(BinaryOperator &I);
177     Instruction *visitOr (BinaryOperator &I);
178     Instruction *visitXor(BinaryOperator &I);
179     Instruction *visitShl(BinaryOperator &I);
180     Instruction *visitAShr(BinaryOperator &I);
181     Instruction *visitLShr(BinaryOperator &I);
182     Instruction *commonShiftTransforms(BinaryOperator &I);
183     Instruction *visitFCmpInst(FCmpInst &I);
184     Instruction *visitICmpInst(ICmpInst &I);
185     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
186
187     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188                              ICmpInst::Predicate Cond, Instruction &I);
189     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
190                                      BinaryOperator &I);
191     Instruction *commonCastTransforms(CastInst &CI);
192     Instruction *commonIntCastTransforms(CastInst &CI);
193     Instruction *visitTrunc(CastInst &CI);
194     Instruction *visitZExt(CastInst &CI);
195     Instruction *visitSExt(CastInst &CI);
196     Instruction *visitFPTrunc(CastInst &CI);
197     Instruction *visitFPExt(CastInst &CI);
198     Instruction *visitFPToUI(CastInst &CI);
199     Instruction *visitFPToSI(CastInst &CI);
200     Instruction *visitUIToFP(CastInst &CI);
201     Instruction *visitSIToFP(CastInst &CI);
202     Instruction *visitPtrToInt(CastInst &CI);
203     Instruction *visitIntToPtr(CastInst &CI);
204     Instruction *visitBitCast(CastInst &CI);
205     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206                                 Instruction *FI);
207     Instruction *visitSelectInst(SelectInst &CI);
208     Instruction *visitCallInst(CallInst &CI);
209     Instruction *visitInvokeInst(InvokeInst &II);
210     Instruction *visitPHINode(PHINode &PN);
211     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
212     Instruction *visitAllocationInst(AllocationInst &AI);
213     Instruction *visitFreeInst(FreeInst &FI);
214     Instruction *visitLoadInst(LoadInst &LI);
215     Instruction *visitStoreInst(StoreInst &SI);
216     Instruction *visitBranchInst(BranchInst &BI);
217     Instruction *visitSwitchInst(SwitchInst &SI);
218     Instruction *visitInsertElementInst(InsertElementInst &IE);
219     Instruction *visitExtractElementInst(ExtractElementInst &EI);
220     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
221
222     // visitInstruction - Specify what to return for unhandled instructions...
223     Instruction *visitInstruction(Instruction &I) { return 0; }
224
225   private:
226     Instruction *visitCallSite(CallSite CS);
227     bool transformConstExprCastCall(CallSite CS);
228
229   public:
230     // InsertNewInstBefore - insert an instruction New before instruction Old
231     // in the program.  Add the new instruction to the worklist.
232     //
233     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
234       assert(New && New->getParent() == 0 &&
235              "New instruction already inserted into a basic block!");
236       BasicBlock *BB = Old.getParent();
237       BB->getInstList().insert(&Old, New);  // Insert inst
238       AddToWorkList(New);
239       return New;
240     }
241
242     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243     /// This also adds the cast to the worklist.  Finally, this returns the
244     /// cast.
245     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246                             Instruction &Pos) {
247       if (V->getType() == Ty) return V;
248
249       if (Constant *CV = dyn_cast<Constant>(V))
250         return ConstantExpr::getCast(opc, CV, Ty);
251       
252       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
253       AddToWorkList(C);
254       return C;
255     }
256
257     // ReplaceInstUsesWith - This method is to be used when an instruction is
258     // found to be dead, replacable with another preexisting expression.  Here
259     // we add all uses of I to the worklist, replace all uses of I with the new
260     // value, then return I, so that the inst combiner will know that I was
261     // modified.
262     //
263     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
264       AddUsersToWorkList(I);         // Add all modified instrs to worklist
265       if (&I != V) {
266         I.replaceAllUsesWith(V);
267         return &I;
268       } else {
269         // If we are replacing the instruction with itself, this must be in a
270         // segment of unreachable code, so just clobber the instruction.
271         I.replaceAllUsesWith(UndefValue::get(I.getType()));
272         return &I;
273       }
274     }
275
276     // UpdateValueUsesWith - This method is to be used when an value is
277     // found to be replacable with another preexisting expression or was
278     // updated.  Here we add all uses of I to the worklist, replace all uses of
279     // I with the new value (unless the instruction was just updated), then
280     // return true, so that the inst combiner will know that I was modified.
281     //
282     bool UpdateValueUsesWith(Value *Old, Value *New) {
283       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
284       if (Old != New)
285         Old->replaceAllUsesWith(New);
286       if (Instruction *I = dyn_cast<Instruction>(Old))
287         AddToWorkList(I);
288       if (Instruction *I = dyn_cast<Instruction>(New))
289         AddToWorkList(I);
290       return true;
291     }
292     
293     // EraseInstFromFunction - When dealing with an instruction that has side
294     // effects or produces a void value, we can't rely on DCE to delete the
295     // instruction.  Instead, visit methods should return the value returned by
296     // this function.
297     Instruction *EraseInstFromFunction(Instruction &I) {
298       assert(I.use_empty() && "Cannot erase instruction that is used!");
299       AddUsesToWorkList(I);
300       RemoveFromWorkList(&I);
301       I.eraseFromParent();
302       return 0;  // Don't do anything with FI
303     }
304
305   private:
306     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
308     /// casts that are known to not do anything...
309     ///
310     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311                                    Value *V, const Type *DestTy,
312                                    Instruction *InsertBefore);
313
314     /// SimplifyCommutative - This performs a few simplifications for 
315     /// commutative operators.
316     bool SimplifyCommutative(BinaryOperator &I);
317
318     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319     /// most-complex to least-complex order.
320     bool SimplifyCompare(CmpInst &I);
321
322     bool SimplifyDemandedBits(Value *V, uint64_t DemandedMask, 
323                               uint64_t &KnownZero, uint64_t &KnownOne,
324                               unsigned Depth = 0);
325
326     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
327                               APInt& KnownZero, APInt& KnownOne,
328                               unsigned Depth = 0);
329
330     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
331                                       uint64_t &UndefElts, unsigned Depth = 0);
332       
333     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
334     // PHI node as operand #0, see if we can fold the instruction into the PHI
335     // (which is only possible if all operands to the PHI are constants).
336     Instruction *FoldOpIntoPhi(Instruction &I);
337
338     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
339     // operator and they all are only used by the PHI, PHI together their
340     // inputs, and do the operation once, to the result of the PHI.
341     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
342     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
343     
344     
345     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
346                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
347     
348     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
349                               bool isSub, Instruction &I);
350     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
351                                  bool isSigned, bool Inside, Instruction &IB);
352     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
353     Instruction *MatchBSwap(BinaryOperator &I);
354
355     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
356   };
357
358   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
359 }
360
361 // getComplexity:  Assign a complexity or rank value to LLVM Values...
362 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
363 static unsigned getComplexity(Value *V) {
364   if (isa<Instruction>(V)) {
365     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
366       return 3;
367     return 4;
368   }
369   if (isa<Argument>(V)) return 3;
370   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
371 }
372
373 // isOnlyUse - Return true if this instruction will be deleted if we stop using
374 // it.
375 static bool isOnlyUse(Value *V) {
376   return V->hasOneUse() || isa<Constant>(V);
377 }
378
379 // getPromotedType - Return the specified type promoted as it would be to pass
380 // though a va_arg area...
381 static const Type *getPromotedType(const Type *Ty) {
382   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
383     if (ITy->getBitWidth() < 32)
384       return Type::Int32Ty;
385   } else if (Ty == Type::FloatTy)
386     return Type::DoubleTy;
387   return Ty;
388 }
389
390 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
391 /// expression bitcast,  return the operand value, otherwise return null.
392 static Value *getBitCastOperand(Value *V) {
393   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
394     return I->getOperand(0);
395   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
396     if (CE->getOpcode() == Instruction::BitCast)
397       return CE->getOperand(0);
398   return 0;
399 }
400
401 /// This function is a wrapper around CastInst::isEliminableCastPair. It
402 /// simply extracts arguments and returns what that function returns.
403 static Instruction::CastOps 
404 isEliminableCastPair(
405   const CastInst *CI, ///< The first cast instruction
406   unsigned opcode,       ///< The opcode of the second cast instruction
407   const Type *DstTy,     ///< The target type for the second cast instruction
408   TargetData *TD         ///< The target data for pointer size
409 ) {
410   
411   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
412   const Type *MidTy = CI->getType();                  // B from above
413
414   // Get the opcodes of the two Cast instructions
415   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
416   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
417
418   return Instruction::CastOps(
419       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
420                                      DstTy, TD->getIntPtrType()));
421 }
422
423 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
424 /// in any code being generated.  It does not require codegen if V is simple
425 /// enough or if the cast can be folded into other casts.
426 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
427                               const Type *Ty, TargetData *TD) {
428   if (V->getType() == Ty || isa<Constant>(V)) return false;
429   
430   // If this is another cast that can be eliminated, it isn't codegen either.
431   if (const CastInst *CI = dyn_cast<CastInst>(V))
432     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
433       return false;
434   return true;
435 }
436
437 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
438 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
439 /// casts that are known to not do anything...
440 ///
441 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
442                                              Value *V, const Type *DestTy,
443                                              Instruction *InsertBefore) {
444   if (V->getType() == DestTy) return V;
445   if (Constant *C = dyn_cast<Constant>(V))
446     return ConstantExpr::getCast(opcode, C, DestTy);
447   
448   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
449 }
450
451 // SimplifyCommutative - This performs a few simplifications for commutative
452 // operators:
453 //
454 //  1. Order operands such that they are listed from right (least complex) to
455 //     left (most complex).  This puts constants before unary operators before
456 //     binary operators.
457 //
458 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
459 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
460 //
461 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
462   bool Changed = false;
463   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
464     Changed = !I.swapOperands();
465
466   if (!I.isAssociative()) return Changed;
467   Instruction::BinaryOps Opcode = I.getOpcode();
468   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
469     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
470       if (isa<Constant>(I.getOperand(1))) {
471         Constant *Folded = ConstantExpr::get(I.getOpcode(),
472                                              cast<Constant>(I.getOperand(1)),
473                                              cast<Constant>(Op->getOperand(1)));
474         I.setOperand(0, Op->getOperand(0));
475         I.setOperand(1, Folded);
476         return true;
477       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
478         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
479             isOnlyUse(Op) && isOnlyUse(Op1)) {
480           Constant *C1 = cast<Constant>(Op->getOperand(1));
481           Constant *C2 = cast<Constant>(Op1->getOperand(1));
482
483           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
484           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
485           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
486                                                     Op1->getOperand(0),
487                                                     Op1->getName(), &I);
488           AddToWorkList(New);
489           I.setOperand(0, New);
490           I.setOperand(1, Folded);
491           return true;
492         }
493     }
494   return Changed;
495 }
496
497 /// SimplifyCompare - For a CmpInst this function just orders the operands
498 /// so that theyare listed from right (least complex) to left (most complex).
499 /// This puts constants before unary operators before binary operators.
500 bool InstCombiner::SimplifyCompare(CmpInst &I) {
501   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
502     return false;
503   I.swapOperands();
504   // Compare instructions are not associative so there's nothing else we can do.
505   return true;
506 }
507
508 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
509 // if the LHS is a constant zero (which is the 'negate' form).
510 //
511 static inline Value *dyn_castNegVal(Value *V) {
512   if (BinaryOperator::isNeg(V))
513     return BinaryOperator::getNegArgument(V);
514
515   // Constants can be considered to be negated values if they can be folded.
516   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
517     return ConstantExpr::getNeg(C);
518   return 0;
519 }
520
521 static inline Value *dyn_castNotVal(Value *V) {
522   if (BinaryOperator::isNot(V))
523     return BinaryOperator::getNotArgument(V);
524
525   // Constants can be considered to be not'ed values...
526   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527     return ConstantExpr::getNot(C);
528   return 0;
529 }
530
531 // dyn_castFoldableMul - If this value is a multiply that can be folded into
532 // other computations (because it has a constant operand), return the
533 // non-constant operand of the multiply, and set CST to point to the multiplier.
534 // Otherwise, return null.
535 //
536 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
537   if (V->hasOneUse() && V->getType()->isInteger())
538     if (Instruction *I = dyn_cast<Instruction>(V)) {
539       if (I->getOpcode() == Instruction::Mul)
540         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
541           return I->getOperand(0);
542       if (I->getOpcode() == Instruction::Shl)
543         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
544           // The multiplier is really 1 << CST.
545           Constant *One = ConstantInt::get(V->getType(), 1);
546           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
547           return I->getOperand(0);
548         }
549     }
550   return 0;
551 }
552
553 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554 /// expression, return it.
555 static User *dyn_castGetElementPtr(Value *V) {
556   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558     if (CE->getOpcode() == Instruction::GetElementPtr)
559       return cast<User>(V);
560   return false;
561 }
562
563 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
564 static ConstantInt *AddOne(ConstantInt *C) {
565   return cast<ConstantInt>(ConstantExpr::getAdd(C,
566                                          ConstantInt::get(C->getType(), 1)));
567 }
568 static ConstantInt *SubOne(ConstantInt *C) {
569   return cast<ConstantInt>(ConstantExpr::getSub(C,
570                                          ConstantInt::get(C->getType(), 1)));
571 }
572
573 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
574 /// known to be either zero or one and return them in the KnownZero/KnownOne
575 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
576 /// processing.
577 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
578 /// we cannot optimize based on the assumption that it is zero without changing
579 /// it to be an explicit zero.  If we don't change it to zero, other code could
580 /// optimized based on the contradictory assumption that it is non-zero.
581 /// Because instcombine aggressively folds operations with undef args anyway,
582 /// this won't lose us code quality.
583 static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero, 
584                               APInt& KnownOne, unsigned Depth = 0) {
585   assert(V && "No Value?");
586   assert(Depth <= 6 && "Limit Search Depth");
587   uint32_t BitWidth = Mask.getBitWidth();
588   const IntegerType *VTy = cast<IntegerType>(V->getType());
589   assert(VTy->getBitWidth() == BitWidth &&
590          KnownZero.getBitWidth() == BitWidth && 
591          KnownOne.getBitWidth() == BitWidth &&
592          "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
593   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
594     // We know all of the bits for a constant!
595     KnownOne = CI->getValue() & Mask;
596     KnownZero = ~KnownOne & Mask;
597     return;
598   }
599
600   if (Depth == 6 || Mask == 0)
601     return;  // Limit search depth.
602
603   Instruction *I = dyn_cast<Instruction>(V);
604   if (!I) return;
605
606   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
607   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
608   Mask &= APInt::getAllOnesValue(BitWidth);
609   
610   switch (I->getOpcode()) {
611   case Instruction::And:
612     // If either the LHS or the RHS are Zero, the result is zero.
613     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614     Mask &= ~KnownZero;
615     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
617     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
618     
619     // Output known-1 bits are only known if set in both the LHS & RHS.
620     KnownOne &= KnownOne2;
621     // Output known-0 are known to be clear if zero in either the LHS | RHS.
622     KnownZero |= KnownZero2;
623     return;
624   case Instruction::Or:
625     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626     Mask &= ~KnownOne;
627     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
628     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
629     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
630     
631     // Output known-0 bits are only known if clear in both the LHS & RHS.
632     KnownZero &= KnownZero2;
633     // Output known-1 are known to be set if set in either the LHS | RHS.
634     KnownOne |= KnownOne2;
635     return;
636   case Instruction::Xor: {
637     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
639     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
640     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
641     
642     // Output known-0 bits are known if clear or set in both the LHS & RHS.
643     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
644     // Output known-1 are known to be set if set in only one of the LHS, RHS.
645     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
646     KnownZero = KnownZeroOut;
647     return;
648   }
649   case Instruction::Select:
650     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
651     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
652     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
653     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
654
655     // Only known if known in both the LHS and RHS.
656     KnownOne &= KnownOne2;
657     KnownZero &= KnownZero2;
658     return;
659   case Instruction::FPTrunc:
660   case Instruction::FPExt:
661   case Instruction::FPToUI:
662   case Instruction::FPToSI:
663   case Instruction::SIToFP:
664   case Instruction::PtrToInt:
665   case Instruction::UIToFP:
666   case Instruction::IntToPtr:
667     return; // Can't work with floating point or pointers
668   case Instruction::Trunc: {
669     // All these have integer operands
670     uint32_t SrcBitWidth = 
671       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
672     ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth), 
673       KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
674     KnownZero.trunc(BitWidth);
675     KnownOne.trunc(BitWidth);
676     return;
677   }
678   case Instruction::BitCast: {
679     const Type *SrcTy = I->getOperand(0)->getType();
680     if (SrcTy->isInteger()) {
681       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682       return;
683     }
684     break;
685   }
686   case Instruction::ZExt:  {
687     // Compute the bits in the result that are not present in the input.
688     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
689     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
690       
691     uint32_t SrcBitWidth = SrcTy->getBitWidth();
692     ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth), 
693       KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
694     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
695     // The top bits are known to be zero.
696     KnownZero.zext(BitWidth);
697     KnownOne.zext(BitWidth);
698     KnownZero |= NewBits;
699     return;
700   }
701   case Instruction::SExt: {
702     // Compute the bits in the result that are not present in the input.
703     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
704     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
705       
706     uint32_t SrcBitWidth = SrcTy->getBitWidth();
707     ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth), 
708       KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
709     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
710     KnownZero.zext(BitWidth);
711     KnownOne.zext(BitWidth);
712
713     // If the sign bit of the input is known set or clear, then we know the
714     // top bits of the result.
715     APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
716     InSignBit.zext(BitWidth);
717     if ((KnownZero & InSignBit) != 0) {          // Input sign bit known zero
718       KnownZero |= NewBits;
719       KnownOne &= ~NewBits;
720     } else if ((KnownOne & InSignBit) != 0) {    // Input sign bit known set
721       KnownOne |= NewBits;
722       KnownZero &= ~NewBits;
723     } else {                              // Input sign bit unknown
724       KnownZero &= ~NewBits;
725       KnownOne &= ~NewBits;
726     }
727     return;
728   }
729   case Instruction::Shl:
730     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
731     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732       uint64_t ShiftAmt = SA->getZExtValue();
733       Mask = APIntOps::lshr(Mask, ShiftAmt);
734       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
735       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
736       KnownZero <<= ShiftAmt;
737       KnownOne  <<= ShiftAmt;
738       KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1;  // low bits known zero.
739       return;
740     }
741     break;
742   case Instruction::LShr:
743     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
744     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745       // Compute the new bits that are at the top now.
746       uint64_t ShiftAmt = SA->getZExtValue();
747       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748       
749       // Unsigned shift right.
750       Mask <<= ShiftAmt;
751       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
753       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
755       KnownZero |= HighBits;  // high bits known zero.
756       return;
757     }
758     break;
759   case Instruction::AShr:
760     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
761     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762       // Compute the new bits that are at the top now.
763       uint64_t ShiftAmt = SA->getZExtValue();
764       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
765       
766       // Signed shift right.
767       Mask <<= ShiftAmt;
768       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
769       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
770       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
772         
773       // Handle the sign bits and adjust to where it is now in the mask.
774       APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
775         
776       if ((KnownZero & SignBit) != 0) {       // New bits are known zero.
777         KnownZero |= HighBits;
778       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
779         KnownOne |= HighBits;
780       }
781       return;
782     }
783     break;
784   }
785 }
786
787 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
788 /// known to be either zero or one and return them in the KnownZero/KnownOne
789 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
790 /// processing.
791 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero, 
792                               uint64_t &KnownOne, unsigned Depth = 0) {
793   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
794   // we cannot optimize based on the assumption that it is zero without changing
795   // it to be an explicit zero.  If we don't change it to zero, other code could
796   // optimized based on the contradictory assumption that it is non-zero.
797   // Because instcombine aggressively folds operations with undef args anyway,
798   // this won't lose us code quality.
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800     // We know all of the bits for a constant!
801     KnownOne = CI->getZExtValue() & Mask;
802     KnownZero = ~KnownOne & Mask;
803     return;
804   }
805
806   KnownZero = KnownOne = 0;   // Don't know anything.
807   if (Depth == 6 || Mask == 0)
808     return;  // Limit search depth.
809
810   uint64_t KnownZero2, KnownOne2;
811   Instruction *I = dyn_cast<Instruction>(V);
812   if (!I) return;
813
814   Mask &= cast<IntegerType>(V->getType())->getBitMask();
815   
816   switch (I->getOpcode()) {
817   case Instruction::And:
818     // If either the LHS or the RHS are Zero, the result is zero.
819     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
820     Mask &= ~KnownZero;
821     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
822     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
823     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
824     
825     // Output known-1 bits are only known if set in both the LHS & RHS.
826     KnownOne &= KnownOne2;
827     // Output known-0 are known to be clear if zero in either the LHS | RHS.
828     KnownZero |= KnownZero2;
829     return;
830   case Instruction::Or:
831     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
832     Mask &= ~KnownOne;
833     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
834     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
835     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
836     
837     // Output known-0 bits are only known if clear in both the LHS & RHS.
838     KnownZero &= KnownZero2;
839     // Output known-1 are known to be set if set in either the LHS | RHS.
840     KnownOne |= KnownOne2;
841     return;
842   case Instruction::Xor: {
843     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
844     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
845     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
846     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
847     
848     // Output known-0 bits are known if clear or set in both the LHS & RHS.
849     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
850     // Output known-1 are known to be set if set in only one of the LHS, RHS.
851     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
852     KnownZero = KnownZeroOut;
853     return;
854   }
855   case Instruction::Select:
856     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
857     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
858     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
859     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
860
861     // Only known if known in both the LHS and RHS.
862     KnownOne &= KnownOne2;
863     KnownZero &= KnownZero2;
864     return;
865   case Instruction::FPTrunc:
866   case Instruction::FPExt:
867   case Instruction::FPToUI:
868   case Instruction::FPToSI:
869   case Instruction::SIToFP:
870   case Instruction::PtrToInt:
871   case Instruction::UIToFP:
872   case Instruction::IntToPtr:
873     return; // Can't work with floating point or pointers
874   case Instruction::Trunc: 
875     // All these have integer operands
876     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877     return;
878   case Instruction::BitCast: {
879     const Type *SrcTy = I->getOperand(0)->getType();
880     if (SrcTy->isInteger()) {
881       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
882       return;
883     }
884     break;
885   }
886   case Instruction::ZExt:  {
887     // Compute the bits in the result that are not present in the input.
888     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
889     uint64_t NotIn = ~SrcTy->getBitMask();
890     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
891       
892     Mask &= SrcTy->getBitMask();
893     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
894     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
895     // The top bits are known to be zero.
896     KnownZero |= NewBits;
897     return;
898   }
899   case Instruction::SExt: {
900     // Compute the bits in the result that are not present in the input.
901     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
902     uint64_t NotIn = ~SrcTy->getBitMask();
903     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
904       
905     Mask &= SrcTy->getBitMask();
906     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
907     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
908
909     // If the sign bit of the input is known set or clear, then we know the
910     // top bits of the result.
911     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
912     if (KnownZero & InSignBit) {          // Input sign bit known zero
913       KnownZero |= NewBits;
914       KnownOne &= ~NewBits;
915     } else if (KnownOne & InSignBit) {    // Input sign bit known set
916       KnownOne |= NewBits;
917       KnownZero &= ~NewBits;
918     } else {                              // Input sign bit unknown
919       KnownZero &= ~NewBits;
920       KnownOne &= ~NewBits;
921     }
922     return;
923   }
924   case Instruction::Shl:
925     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
926     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
927       uint64_t ShiftAmt = SA->getZExtValue();
928       Mask >>= ShiftAmt;
929       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
930       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
931       KnownZero <<= ShiftAmt;
932       KnownOne  <<= ShiftAmt;
933       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
934       return;
935     }
936     break;
937   case Instruction::LShr:
938     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
939     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
940       // Compute the new bits that are at the top now.
941       uint64_t ShiftAmt = SA->getZExtValue();
942       uint64_t HighBits = (1ULL << ShiftAmt)-1;
943       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
944       
945       // Unsigned shift right.
946       Mask <<= ShiftAmt;
947       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
948       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
949       KnownZero >>= ShiftAmt;
950       KnownOne  >>= ShiftAmt;
951       KnownZero |= HighBits;  // high bits known zero.
952       return;
953     }
954     break;
955   case Instruction::AShr:
956     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
957     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
958       // Compute the new bits that are at the top now.
959       uint64_t ShiftAmt = SA->getZExtValue();
960       uint64_t HighBits = (1ULL << ShiftAmt)-1;
961       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
962       
963       // Signed shift right.
964       Mask <<= ShiftAmt;
965       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
966       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
967       KnownZero >>= ShiftAmt;
968       KnownOne  >>= ShiftAmt;
969         
970       // Handle the sign bits.
971       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
972       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
973         
974       if (KnownZero & SignBit) {       // New bits are known zero.
975         KnownZero |= HighBits;
976       } else if (KnownOne & SignBit) { // New bits are known one.
977         KnownOne |= HighBits;
978       }
979       return;
980     }
981     break;
982   }
983 }
984
985 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
986 /// this predicate to simplify operations downstream.  Mask is known to be zero
987 /// for bits that V cannot have.
988 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
989   uint64_t KnownZero, KnownOne;
990   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
991   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
992   return (KnownZero & Mask) == Mask;
993 }
994
995 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
996 /// this predicate to simplify operations downstream.  Mask is known to be zero
997 /// for bits that V cannot have.
998 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
999   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1000   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1001   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1002   return (KnownZero & Mask) == Mask;
1003 }
1004
1005 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1006 /// specified instruction is a constant integer.  If so, check to see if there
1007 /// are any bits set in the constant that are not demanded.  If so, shrink the
1008 /// constant and return true.
1009 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1010                                    uint64_t Demanded) {
1011   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1012   if (!OpC) return false;
1013
1014   // If there are no bits set that aren't demanded, nothing to do.
1015   if ((~Demanded & OpC->getZExtValue()) == 0)
1016     return false;
1017
1018   // This is producing any bits that are not needed, shrink the RHS.
1019   uint64_t Val = Demanded & OpC->getZExtValue();
1020   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
1021   return true;
1022 }
1023
1024 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1025 /// specified instruction is a constant integer.  If so, check to see if there
1026 /// are any bits set in the constant that are not demanded.  If so, shrink the
1027 /// constant and return true.
1028 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1029                                    APInt Demanded) {
1030   assert(I && "No instruction?");
1031   assert(OpNo < I->getNumOperands() && "Operand index too large");
1032
1033   // If the operand is not a constant integer, nothing to do.
1034   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1035   if (!OpC) return false;
1036
1037   // If there are no bits set that aren't demanded, nothing to do.
1038   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1039   if ((~Demanded & OpC->getValue()) == 0)
1040     return false;
1041
1042   // This instruction is producing bits that are not demanded. Shrink the RHS.
1043   Demanded &= OpC->getValue();
1044   I->setOperand(OpNo, ConstantInt::get(Demanded));
1045   return true;
1046 }
1047
1048 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1049 // set of known zero and one bits, compute the maximum and minimum values that
1050 // could have the specified known zero and known one bits, returning them in
1051 // min/max.
1052 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1053                                                    const APInt& KnownZero,
1054                                                    const APInt& KnownOne,
1055                                                    APInt& Min, APInt& Max) {
1056   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1057   assert(KnownZero.getBitWidth() == BitWidth && 
1058          KnownOne.getBitWidth() == BitWidth &&
1059          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1060          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1061   APInt TypeBits(APInt::getAllOnesValue(BitWidth));
1062   APInt UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1063
1064   APInt SignBit(APInt::getSignBit(BitWidth));
1065   
1066   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1067   // bit if it is unknown.
1068   Min = KnownOne;
1069   Max = KnownOne|UnknownBits;
1070   
1071   if ((SignBit & UnknownBits) != 0) { // Sign bit is unknown
1072     Min |= SignBit;
1073     Max &= ~SignBit;
1074   }
1075 }
1076
1077 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1078 // a set of known zero and one bits, compute the maximum and minimum values that
1079 // could have the specified known zero and known one bits, returning them in
1080 // min/max.
1081 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1082                                                      const APInt& KnownZero,
1083                                                      const APInt& KnownOne,
1084                                                      APInt& Min,
1085                                                      APInt& Max) {
1086   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1087   assert(KnownZero.getBitWidth() == BitWidth && 
1088          KnownOne.getBitWidth() == BitWidth &&
1089          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1090          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1091   APInt TypeBits(APInt::getAllOnesValue(BitWidth));
1092   APInt UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1093   
1094   // The minimum value is when the unknown bits are all zeros.
1095   Min = KnownOne;
1096   // The maximum value is when the unknown bits are all ones.
1097   Max = KnownOne|UnknownBits;
1098 }
1099
1100 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
1101 /// DemandedMask bits of the result of V are ever used downstream.  If we can
1102 /// use this information to simplify V, do so and return true.  Otherwise,
1103 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
1104 /// the expression (used to simplify the caller).  The KnownZero/One bits may
1105 /// only be accurate for those bits in the DemandedMask.
1106 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1107                                         uint64_t &KnownZero, uint64_t &KnownOne,
1108                                         unsigned Depth) {
1109   const IntegerType *VTy = cast<IntegerType>(V->getType());
1110   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1111     // We know all of the bits for a constant!
1112     KnownOne = CI->getZExtValue() & DemandedMask;
1113     KnownZero = ~KnownOne & DemandedMask;
1114     return false;
1115   }
1116   
1117   KnownZero = KnownOne = 0;
1118   if (!V->hasOneUse()) {    // Other users may use these bits.
1119     if (Depth != 0) {       // Not at the root.
1120       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1121       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1122       return false;
1123     }
1124     // If this is the root being simplified, allow it to have multiple uses,
1125     // just set the DemandedMask to all bits.
1126     DemandedMask = VTy->getBitMask();
1127   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1128     if (V != UndefValue::get(VTy))
1129       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1130     return false;
1131   } else if (Depth == 6) {        // Limit search depth.
1132     return false;
1133   }
1134   
1135   Instruction *I = dyn_cast<Instruction>(V);
1136   if (!I) return false;        // Only analyze instructions.
1137
1138   DemandedMask &= VTy->getBitMask();
1139   
1140   uint64_t KnownZero2 = 0, KnownOne2 = 0;
1141   switch (I->getOpcode()) {
1142   default: break;
1143   case Instruction::And:
1144     // If either the LHS or the RHS are Zero, the result is zero.
1145     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1146                              KnownZero, KnownOne, Depth+1))
1147       return true;
1148     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1149
1150     // If something is known zero on the RHS, the bits aren't demanded on the
1151     // LHS.
1152     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1153                              KnownZero2, KnownOne2, Depth+1))
1154       return true;
1155     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1156
1157     // If all of the demanded bits are known 1 on one side, return the other.
1158     // These bits cannot contribute to the result of the 'and'.
1159     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1160       return UpdateValueUsesWith(I, I->getOperand(0));
1161     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1162       return UpdateValueUsesWith(I, I->getOperand(1));
1163     
1164     // If all of the demanded bits in the inputs are known zeros, return zero.
1165     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
1166       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1167       
1168     // If the RHS is a constant, see if we can simplify it.
1169     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
1170       return UpdateValueUsesWith(I, I);
1171       
1172     // Output known-1 bits are only known if set in both the LHS & RHS.
1173     KnownOne &= KnownOne2;
1174     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1175     KnownZero |= KnownZero2;
1176     break;
1177   case Instruction::Or:
1178     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1179                              KnownZero, KnownOne, Depth+1))
1180       return true;
1181     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1182     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
1183                              KnownZero2, KnownOne2, Depth+1))
1184       return true;
1185     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1186     
1187     // If all of the demanded bits are known zero on one side, return the other.
1188     // These bits cannot contribute to the result of the 'or'.
1189     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
1190       return UpdateValueUsesWith(I, I->getOperand(0));
1191     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
1192       return UpdateValueUsesWith(I, I->getOperand(1));
1193
1194     // If all of the potentially set bits on one side are known to be set on
1195     // the other side, just use the 'other' side.
1196     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
1197         (DemandedMask & (~KnownZero)))
1198       return UpdateValueUsesWith(I, I->getOperand(0));
1199     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
1200         (DemandedMask & (~KnownZero2)))
1201       return UpdateValueUsesWith(I, I->getOperand(1));
1202         
1203     // If the RHS is a constant, see if we can simplify it.
1204     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1205       return UpdateValueUsesWith(I, I);
1206           
1207     // Output known-0 bits are only known if clear in both the LHS & RHS.
1208     KnownZero &= KnownZero2;
1209     // Output known-1 are known to be set if set in either the LHS | RHS.
1210     KnownOne |= KnownOne2;
1211     break;
1212   case Instruction::Xor: {
1213     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1214                              KnownZero, KnownOne, Depth+1))
1215       return true;
1216     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1217     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1218                              KnownZero2, KnownOne2, Depth+1))
1219       return true;
1220     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1221     
1222     // If all of the demanded bits are known zero on one side, return the other.
1223     // These bits cannot contribute to the result of the 'xor'.
1224     if ((DemandedMask & KnownZero) == DemandedMask)
1225       return UpdateValueUsesWith(I, I->getOperand(0));
1226     if ((DemandedMask & KnownZero2) == DemandedMask)
1227       return UpdateValueUsesWith(I, I->getOperand(1));
1228     
1229     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1230     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1231     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1232     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1233     
1234     // If all of the demanded bits are known to be zero on one side or the
1235     // other, turn this into an *inclusive* or.
1236     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1237     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1238       Instruction *Or =
1239         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1240                                  I->getName());
1241       InsertNewInstBefore(Or, *I);
1242       return UpdateValueUsesWith(I, Or);
1243     }
1244     
1245     // If all of the demanded bits on one side are known, and all of the set
1246     // bits on that side are also known to be set on the other side, turn this
1247     // into an AND, as we know the bits will be cleared.
1248     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1249     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1250       if ((KnownOne & KnownOne2) == KnownOne) {
1251         Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
1252         Instruction *And = 
1253           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1254         InsertNewInstBefore(And, *I);
1255         return UpdateValueUsesWith(I, And);
1256       }
1257     }
1258     
1259     // If the RHS is a constant, see if we can simplify it.
1260     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1261     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1262       return UpdateValueUsesWith(I, I);
1263     
1264     KnownZero = KnownZeroOut;
1265     KnownOne  = KnownOneOut;
1266     break;
1267   }
1268   case Instruction::Select:
1269     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1270                              KnownZero, KnownOne, Depth+1))
1271       return true;
1272     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1273                              KnownZero2, KnownOne2, Depth+1))
1274       return true;
1275     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1276     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1277     
1278     // If the operands are constants, see if we can simplify them.
1279     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1280       return UpdateValueUsesWith(I, I);
1281     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1282       return UpdateValueUsesWith(I, I);
1283     
1284     // Only known if known in both the LHS and RHS.
1285     KnownOne &= KnownOne2;
1286     KnownZero &= KnownZero2;
1287     break;
1288   case Instruction::Trunc:
1289     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1290                              KnownZero, KnownOne, Depth+1))
1291       return true;
1292     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1293     break;
1294   case Instruction::BitCast:
1295     if (!I->getOperand(0)->getType()->isInteger())
1296       return false;
1297       
1298     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1299                              KnownZero, KnownOne, Depth+1))
1300       return true;
1301     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1302     break;
1303   case Instruction::ZExt: {
1304     // Compute the bits in the result that are not present in the input.
1305     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1306     uint64_t NotIn = ~SrcTy->getBitMask();
1307     uint64_t NewBits = VTy->getBitMask() & NotIn;
1308     
1309     DemandedMask &= SrcTy->getBitMask();
1310     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1311                              KnownZero, KnownOne, Depth+1))
1312       return true;
1313     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1314     // The top bits are known to be zero.
1315     KnownZero |= NewBits;
1316     break;
1317   }
1318   case Instruction::SExt: {
1319     // Compute the bits in the result that are not present in the input.
1320     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1321     uint64_t NotIn = ~SrcTy->getBitMask();
1322     uint64_t NewBits = VTy->getBitMask() & NotIn;
1323     
1324     // Get the sign bit for the source type
1325     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1326     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1327
1328     // If any of the sign extended bits are demanded, we know that the sign
1329     // bit is demanded.
1330     if (NewBits & DemandedMask)
1331       InputDemandedBits |= InSignBit;
1332       
1333     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1334                              KnownZero, KnownOne, Depth+1))
1335       return true;
1336     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1337       
1338     // If the sign bit of the input is known set or clear, then we know the
1339     // top bits of the result.
1340
1341     // If the input sign bit is known zero, or if the NewBits are not demanded
1342     // convert this into a zero extension.
1343     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1344       // Convert to ZExt cast
1345       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1346       return UpdateValueUsesWith(I, NewCast);
1347     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1348       KnownOne |= NewBits;
1349       KnownZero &= ~NewBits;
1350     } else {                              // Input sign bit unknown
1351       KnownZero &= ~NewBits;
1352       KnownOne &= ~NewBits;
1353     }
1354     break;
1355   }
1356   case Instruction::Add:
1357     // If there is a constant on the RHS, there are a variety of xformations
1358     // we can do.
1359     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1360       // If null, this should be simplified elsewhere.  Some of the xforms here
1361       // won't work if the RHS is zero.
1362       if (RHS->isNullValue())
1363         break;
1364       
1365       // Figure out what the input bits are.  If the top bits of the and result
1366       // are not demanded, then the add doesn't demand them from its input
1367       // either.
1368       
1369       // Shift the demanded mask up so that it's at the top of the uint64_t.
1370       unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1371       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1372       
1373       // If the top bit of the output is demanded, demand everything from the
1374       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1375       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1376
1377       // Find information about known zero/one bits in the input.
1378       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1379                                KnownZero2, KnownOne2, Depth+1))
1380         return true;
1381
1382       // If the RHS of the add has bits set that can't affect the input, reduce
1383       // the constant.
1384       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1385         return UpdateValueUsesWith(I, I);
1386       
1387       // Avoid excess work.
1388       if (KnownZero2 == 0 && KnownOne2 == 0)
1389         break;
1390       
1391       // Turn it into OR if input bits are zero.
1392       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1393         Instruction *Or =
1394           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1395                                    I->getName());
1396         InsertNewInstBefore(Or, *I);
1397         return UpdateValueUsesWith(I, Or);
1398       }
1399       
1400       // We can say something about the output known-zero and known-one bits,
1401       // depending on potential carries from the input constant and the
1402       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1403       // bits set and the RHS constant is 0x01001, then we know we have a known
1404       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1405       
1406       // To compute this, we first compute the potential carry bits.  These are
1407       // the bits which may be modified.  I'm not aware of a better way to do
1408       // this scan.
1409       uint64_t RHSVal = RHS->getZExtValue();
1410       
1411       bool CarryIn = false;
1412       uint64_t CarryBits = 0;
1413       uint64_t CurBit = 1;
1414       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1415         // Record the current carry in.
1416         if (CarryIn) CarryBits |= CurBit;
1417         
1418         bool CarryOut;
1419         
1420         // This bit has a carry out unless it is "zero + zero" or
1421         // "zero + anything" with no carry in.
1422         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1423           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1424         } else if (!CarryIn &&
1425                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1426           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1427         } else {
1428           // Otherwise, we have to assume we have a carry out.
1429           CarryOut = true;
1430         }
1431         
1432         // This stage's carry out becomes the next stage's carry-in.
1433         CarryIn = CarryOut;
1434       }
1435       
1436       // Now that we know which bits have carries, compute the known-1/0 sets.
1437       
1438       // Bits are known one if they are known zero in one operand and one in the
1439       // other, and there is no input carry.
1440       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1441       
1442       // Bits are known zero if they are known zero in both operands and there
1443       // is no input carry.
1444       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1445     } else {
1446       // If the high-bits of this ADD are not demanded, then it does not demand
1447       // the high bits of its LHS or RHS.
1448       if ((DemandedMask & VTy->getSignBit()) == 0) {
1449         // Right fill the mask of bits for this ADD to demand the most
1450         // significant bit and all those below it.
1451         unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1452         uint64_t DemandedFromOps = ~0ULL >> NLZ;
1453         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1454                                  KnownZero2, KnownOne2, Depth+1))
1455           return true;
1456         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1457                                  KnownZero2, KnownOne2, Depth+1))
1458           return true;
1459       }
1460     }
1461     break;
1462   case Instruction::Sub:
1463     // If the high-bits of this SUB are not demanded, then it does not demand
1464     // the high bits of its LHS or RHS.
1465     if ((DemandedMask & VTy->getSignBit()) == 0) {
1466       // Right fill the mask of bits for this SUB to demand the most
1467       // significant bit and all those below it.
1468       unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1469       uint64_t DemandedFromOps = ~0ULL >> NLZ;
1470       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1471                                KnownZero2, KnownOne2, Depth+1))
1472         return true;
1473       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1474                                KnownZero2, KnownOne2, Depth+1))
1475         return true;
1476     }
1477     break;
1478   case Instruction::Shl:
1479     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1480       uint64_t ShiftAmt = SA->getZExtValue();
1481       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1482                                KnownZero, KnownOne, Depth+1))
1483         return true;
1484       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1485       KnownZero <<= ShiftAmt;
1486       KnownOne  <<= ShiftAmt;
1487       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1488     }
1489     break;
1490   case Instruction::LShr:
1491     // For a logical shift right
1492     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1493       unsigned ShiftAmt = SA->getZExtValue();
1494       
1495       // Compute the new bits that are at the top now.
1496       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1497       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1498       uint64_t TypeMask = VTy->getBitMask();
1499       // Unsigned shift right.
1500       if (SimplifyDemandedBits(I->getOperand(0),
1501                               (DemandedMask << ShiftAmt) & TypeMask,
1502                                KnownZero, KnownOne, Depth+1))
1503         return true;
1504       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1505       KnownZero &= TypeMask;
1506       KnownOne  &= TypeMask;
1507       KnownZero >>= ShiftAmt;
1508       KnownOne  >>= ShiftAmt;
1509       KnownZero |= HighBits;  // high bits known zero.
1510     }
1511     break;
1512   case Instruction::AShr:
1513     // If this is an arithmetic shift right and only the low-bit is set, we can
1514     // always convert this into a logical shr, even if the shift amount is
1515     // variable.  The low bit of the shift cannot be an input sign bit unless
1516     // the shift amount is >= the size of the datatype, which is undefined.
1517     if (DemandedMask == 1) {
1518       // Perform the logical shift right.
1519       Value *NewVal = BinaryOperator::createLShr(
1520                         I->getOperand(0), I->getOperand(1), I->getName());
1521       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1522       return UpdateValueUsesWith(I, NewVal);
1523     }    
1524     
1525     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1526       unsigned ShiftAmt = SA->getZExtValue();
1527       
1528       // Compute the new bits that are at the top now.
1529       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1530       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1531       uint64_t TypeMask = VTy->getBitMask();
1532       // Signed shift right.
1533       if (SimplifyDemandedBits(I->getOperand(0),
1534                                (DemandedMask << ShiftAmt) & TypeMask,
1535                                KnownZero, KnownOne, Depth+1))
1536         return true;
1537       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1538       KnownZero &= TypeMask;
1539       KnownOne  &= TypeMask;
1540       KnownZero >>= ShiftAmt;
1541       KnownOne  >>= ShiftAmt;
1542         
1543       // Handle the sign bits.
1544       uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
1545       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1546         
1547       // If the input sign bit is known to be zero, or if none of the top bits
1548       // are demanded, turn this into an unsigned shift right.
1549       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1550         // Perform the logical shift right.
1551         Value *NewVal = BinaryOperator::createLShr(
1552                           I->getOperand(0), SA, I->getName());
1553         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1554         return UpdateValueUsesWith(I, NewVal);
1555       } else if (KnownOne & SignBit) { // New bits are known one.
1556         KnownOne |= HighBits;
1557       }
1558     }
1559     break;
1560   }
1561   
1562   // If the client is only demanding bits that we know, return the known
1563   // constant.
1564   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1565     return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
1566   return false;
1567 }  
1568
1569 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1570 /// value based on the demanded bits. When this function is called, it is known
1571 /// that only the bits set in DemandedMask of the result of V are ever used
1572 /// downstream. Consequently, depending on the mask and V, it may be possible
1573 /// to replace V with a constant or one of its operands. In such cases, this
1574 /// function does the replacement and returns true. In all other cases, it
1575 /// returns false after analyzing the expression and setting KnownOne and known
1576 /// to be one in the expression. KnownZero contains all the bits that are known
1577 /// to be zero in the expression. These are provided to potentially allow the
1578 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1579 /// the expression. KnownOne and KnownZero always follow the invariant that 
1580 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1581 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1582 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1583 /// and KnownOne must all be the same.
1584 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1585                                         APInt& KnownZero, APInt& KnownOne,
1586                                         unsigned Depth) {
1587   assert(V != 0 && "Null pointer of Value???");
1588   assert(Depth <= 6 && "Limit Search Depth");
1589   uint32_t BitWidth = DemandedMask.getBitWidth();
1590   const IntegerType *VTy = cast<IntegerType>(V->getType());
1591   assert(VTy->getBitWidth() == BitWidth && 
1592          KnownZero.getBitWidth() == BitWidth && 
1593          KnownOne.getBitWidth() == BitWidth &&
1594          "Value *V, DemandedMask, KnownZero and KnownOne \
1595           must have same BitWidth");
1596   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1597     // We know all of the bits for a constant!
1598     KnownOne = CI->getValue() & DemandedMask;
1599     KnownZero = ~KnownOne & DemandedMask;
1600     return false;
1601   }
1602   
1603   KnownZero.clear(); 
1604   KnownOne.clear();
1605   if (!V->hasOneUse()) {    // Other users may use these bits.
1606     if (Depth != 0) {       // Not at the root.
1607       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1608       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1609       return false;
1610     }
1611     // If this is the root being simplified, allow it to have multiple uses,
1612     // just set the DemandedMask to all bits.
1613     DemandedMask = APInt::getAllOnesValue(BitWidth);
1614   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1615     if (V != UndefValue::get(VTy))
1616       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1617     return false;
1618   } else if (Depth == 6) {        // Limit search depth.
1619     return false;
1620   }
1621   
1622   Instruction *I = dyn_cast<Instruction>(V);
1623   if (!I) return false;        // Only analyze instructions.
1624
1625   DemandedMask &= APInt::getAllOnesValue(BitWidth);
1626   
1627   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1628   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1629   switch (I->getOpcode()) {
1630   default: break;
1631   case Instruction::And:
1632     // If either the LHS or the RHS are Zero, the result is zero.
1633     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1634                              RHSKnownZero, RHSKnownOne, Depth+1))
1635       return true;
1636     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1637            "Bits known to be one AND zero?"); 
1638
1639     // If something is known zero on the RHS, the bits aren't demanded on the
1640     // LHS.
1641     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1642                              LHSKnownZero, LHSKnownOne, Depth+1))
1643       return true;
1644     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1645            "Bits known to be one AND zero?"); 
1646
1647     // If all of the demanded bits are known 1 on one side, return the other.
1648     // These bits cannot contribute to the result of the 'and'.
1649     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1650         (DemandedMask & ~LHSKnownZero))
1651       return UpdateValueUsesWith(I, I->getOperand(0));
1652     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1653         (DemandedMask & ~RHSKnownZero))
1654       return UpdateValueUsesWith(I, I->getOperand(1));
1655     
1656     // If all of the demanded bits in the inputs are known zeros, return zero.
1657     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1658       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1659       
1660     // If the RHS is a constant, see if we can simplify it.
1661     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1662       return UpdateValueUsesWith(I, I);
1663       
1664     // Output known-1 bits are only known if set in both the LHS & RHS.
1665     RHSKnownOne &= LHSKnownOne;
1666     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1667     RHSKnownZero |= LHSKnownZero;
1668     break;
1669   case Instruction::Or:
1670     // If either the LHS or the RHS are One, the result is One.
1671     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1672                              RHSKnownZero, RHSKnownOne, Depth+1))
1673       return true;
1674     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1675            "Bits known to be one AND zero?"); 
1676     // If something is known one on the RHS, the bits aren't demanded on the
1677     // LHS.
1678     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1679                              LHSKnownZero, LHSKnownOne, Depth+1))
1680       return true;
1681     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1682            "Bits known to be one AND zero?"); 
1683     
1684     // If all of the demanded bits are known zero on one side, return the other.
1685     // These bits cannot contribute to the result of the 'or'.
1686     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1687         (DemandedMask & ~LHSKnownOne))
1688       return UpdateValueUsesWith(I, I->getOperand(0));
1689     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1690         (DemandedMask & ~RHSKnownOne))
1691       return UpdateValueUsesWith(I, I->getOperand(1));
1692
1693     // If all of the potentially set bits on one side are known to be set on
1694     // the other side, just use the 'other' side.
1695     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1696         (DemandedMask & (~RHSKnownZero)))
1697       return UpdateValueUsesWith(I, I->getOperand(0));
1698     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1699         (DemandedMask & (~LHSKnownZero)))
1700       return UpdateValueUsesWith(I, I->getOperand(1));
1701         
1702     // If the RHS is a constant, see if we can simplify it.
1703     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1704       return UpdateValueUsesWith(I, I);
1705           
1706     // Output known-0 bits are only known if clear in both the LHS & RHS.
1707     RHSKnownZero &= LHSKnownZero;
1708     // Output known-1 are known to be set if set in either the LHS | RHS.
1709     RHSKnownOne |= LHSKnownOne;
1710     break;
1711   case Instruction::Xor: {
1712     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1713                              RHSKnownZero, RHSKnownOne, Depth+1))
1714       return true;
1715     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1716            "Bits known to be one AND zero?"); 
1717     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1718                              LHSKnownZero, LHSKnownOne, Depth+1))
1719       return true;
1720     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1721            "Bits known to be one AND zero?"); 
1722     
1723     // If all of the demanded bits are known zero on one side, return the other.
1724     // These bits cannot contribute to the result of the 'xor'.
1725     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1726       return UpdateValueUsesWith(I, I->getOperand(0));
1727     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1728       return UpdateValueUsesWith(I, I->getOperand(1));
1729     
1730     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1731     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1732                          (RHSKnownOne & LHSKnownOne);
1733     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1734     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1735                         (RHSKnownOne & LHSKnownZero);
1736     
1737     // If all of the demanded bits are known to be zero on one side or the
1738     // other, turn this into an *inclusive* or.
1739     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1740     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1741       Instruction *Or =
1742         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1743                                  I->getName());
1744       InsertNewInstBefore(Or, *I);
1745       return UpdateValueUsesWith(I, Or);
1746     }
1747     
1748     // If all of the demanded bits on one side are known, and all of the set
1749     // bits on that side are also known to be set on the other side, turn this
1750     // into an AND, as we know the bits will be cleared.
1751     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1752     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1753       // all known
1754       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1755         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1756         Instruction *And = 
1757           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1758         InsertNewInstBefore(And, *I);
1759         return UpdateValueUsesWith(I, And);
1760       }
1761     }
1762     
1763     // If the RHS is a constant, see if we can simplify it.
1764     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1765     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1766       return UpdateValueUsesWith(I, I);
1767     
1768     RHSKnownZero = KnownZeroOut;
1769     RHSKnownOne  = KnownOneOut;
1770     break;
1771   }
1772   case Instruction::Select:
1773     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1774                              RHSKnownZero, RHSKnownOne, Depth+1))
1775       return true;
1776     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1777                              LHSKnownZero, LHSKnownOne, Depth+1))
1778       return true;
1779     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1780            "Bits known to be one AND zero?"); 
1781     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1782            "Bits known to be one AND zero?"); 
1783     
1784     // If the operands are constants, see if we can simplify them.
1785     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1786       return UpdateValueUsesWith(I, I);
1787     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1788       return UpdateValueUsesWith(I, I);
1789     
1790     // Only known if known in both the LHS and RHS.
1791     RHSKnownOne &= LHSKnownOne;
1792     RHSKnownZero &= LHSKnownZero;
1793     break;
1794   case Instruction::Trunc: {
1795     uint32_t truncBf = 
1796       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1797     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1798         RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1799       return true;
1800     DemandedMask.trunc(BitWidth);
1801     RHSKnownZero.trunc(BitWidth);
1802     RHSKnownOne.trunc(BitWidth);
1803     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1804            "Bits known to be one AND zero?"); 
1805     break;
1806   }
1807   case Instruction::BitCast:
1808     if (!I->getOperand(0)->getType()->isInteger())
1809       return false;
1810       
1811     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1812                              RHSKnownZero, RHSKnownOne, Depth+1))
1813       return true;
1814     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1815            "Bits known to be one AND zero?"); 
1816     break;
1817   case Instruction::ZExt: {
1818     // Compute the bits in the result that are not present in the input.
1819     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1820     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1821     
1822     DemandedMask &= SrcTy->getMask().zext(BitWidth);
1823     uint32_t zextBf = SrcTy->getBitWidth();
1824     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1825           RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1826       return true;
1827     DemandedMask.zext(BitWidth);
1828     RHSKnownZero.zext(BitWidth);
1829     RHSKnownOne.zext(BitWidth);
1830     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1831            "Bits known to be one AND zero?"); 
1832     // The top bits are known to be zero.
1833     RHSKnownZero |= NewBits;
1834     break;
1835   }
1836   case Instruction::SExt: {
1837     // Compute the bits in the result that are not present in the input.
1838     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1839     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1840     
1841     // Get the sign bit for the source type
1842     APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1843     InSignBit.zext(BitWidth);
1844     APInt InputDemandedBits = DemandedMask & 
1845                               SrcTy->getMask().zext(BitWidth);
1846
1847     // If any of the sign extended bits are demanded, we know that the sign
1848     // bit is demanded.
1849     if ((NewBits & DemandedMask) != 0)
1850       InputDemandedBits |= InSignBit;
1851       
1852     uint32_t sextBf = SrcTy->getBitWidth();
1853     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1854           RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1855       return true;
1856     InputDemandedBits.zext(BitWidth);
1857     RHSKnownZero.zext(BitWidth);
1858     RHSKnownOne.zext(BitWidth);
1859     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1860            "Bits known to be one AND zero?"); 
1861       
1862     // If the sign bit of the input is known set or clear, then we know the
1863     // top bits of the result.
1864
1865     // If the input sign bit is known zero, or if the NewBits are not demanded
1866     // convert this into a zero extension.
1867     if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1868     {
1869       // Convert to ZExt cast
1870       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1871       return UpdateValueUsesWith(I, NewCast);
1872     } else if ((RHSKnownOne & InSignBit) != 0) {    // Input sign bit known set
1873       RHSKnownOne |= NewBits;
1874       RHSKnownZero &= ~NewBits;
1875     } else {                              // Input sign bit unknown
1876       RHSKnownZero &= ~NewBits;
1877       RHSKnownOne &= ~NewBits;
1878     }
1879     break;
1880   }
1881   case Instruction::Add: {
1882     // Figure out what the input bits are.  If the top bits of the and result
1883     // are not demanded, then the add doesn't demand them from its input
1884     // either.
1885     unsigned NLZ = DemandedMask.countLeadingZeros();
1886       
1887     // If there is a constant on the RHS, there are a variety of xformations
1888     // we can do.
1889     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1890       // If null, this should be simplified elsewhere.  Some of the xforms here
1891       // won't work if the RHS is zero.
1892       if (RHS->isZero())
1893         break;
1894       
1895       // If the top bit of the output is demanded, demand everything from the
1896       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1897       APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1898
1899       // Find information about known zero/one bits in the input.
1900       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1901                                LHSKnownZero, LHSKnownOne, Depth+1))
1902         return true;
1903
1904       // If the RHS of the add has bits set that can't affect the input, reduce
1905       // the constant.
1906       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1907         return UpdateValueUsesWith(I, I);
1908       
1909       // Avoid excess work.
1910       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1911         break;
1912       
1913       // Turn it into OR if input bits are zero.
1914       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1915         Instruction *Or =
1916           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1917                                    I->getName());
1918         InsertNewInstBefore(Or, *I);
1919         return UpdateValueUsesWith(I, Or);
1920       }
1921       
1922       // We can say something about the output known-zero and known-one bits,
1923       // depending on potential carries from the input constant and the
1924       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1925       // bits set and the RHS constant is 0x01001, then we know we have a known
1926       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1927       
1928       // To compute this, we first compute the potential carry bits.  These are
1929       // the bits which may be modified.  I'm not aware of a better way to do
1930       // this scan.
1931       APInt RHSVal(RHS->getValue());
1932       
1933       bool CarryIn = false;
1934       APInt CarryBits(BitWidth, 0);
1935       const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1936                      *RHSRawVal = RHSVal.getRawData();
1937       for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1938         uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1939                  XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1940         uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1941         if (AddVal < RHSRawVal[i])
1942           CarryIn = true;
1943         else
1944           CarryIn = false;
1945         CarryBits.setWordToValue(i, WordCarryBits);
1946       }
1947       
1948       // Now that we know which bits have carries, compute the known-1/0 sets.
1949       
1950       // Bits are known one if they are known zero in one operand and one in the
1951       // other, and there is no input carry.
1952       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1953                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1954       
1955       // Bits are known zero if they are known zero in both operands and there
1956       // is no input carry.
1957       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1958     } else {
1959       // If the high-bits of this ADD are not demanded, then it does not demand
1960       // the high bits of its LHS or RHS.
1961       if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1962         // Right fill the mask of bits for this ADD to demand the most
1963         // significant bit and all those below it.
1964         APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1965         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1966                                  LHSKnownZero, LHSKnownOne, Depth+1))
1967           return true;
1968         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1969                                  LHSKnownZero, LHSKnownOne, Depth+1))
1970           return true;
1971       }
1972     }
1973     break;
1974   }
1975   case Instruction::Sub:
1976     // If the high-bits of this SUB are not demanded, then it does not demand
1977     // the high bits of its LHS or RHS.
1978     if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1979       // Right fill the mask of bits for this SUB to demand the most
1980       // significant bit and all those below it.
1981       unsigned NLZ = DemandedMask.countLeadingZeros();
1982       APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1983       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1984                                LHSKnownZero, LHSKnownOne, Depth+1))
1985         return true;
1986       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1987                                LHSKnownZero, LHSKnownOne, Depth+1))
1988         return true;
1989     }
1990     break;
1991   case Instruction::Shl:
1992     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1993       uint64_t ShiftAmt = SA->getZExtValue();
1994       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt), 
1995                                RHSKnownZero, RHSKnownOne, Depth+1))
1996         return true;
1997       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1998              "Bits known to be one AND zero?"); 
1999       RHSKnownZero <<= ShiftAmt;
2000       RHSKnownOne  <<= ShiftAmt;
2001       // low bits known zero.
2002       if (ShiftAmt)
2003         RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
2004     }
2005     break;
2006   case Instruction::LShr:
2007     // For a logical shift right
2008     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2009       unsigned ShiftAmt = SA->getZExtValue();
2010       
2011       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2012       // Unsigned shift right.
2013       if (SimplifyDemandedBits(I->getOperand(0),
2014                               (DemandedMask.shl(ShiftAmt)) & TypeMask,
2015                                RHSKnownZero, RHSKnownOne, Depth+1))
2016         return true;
2017       assert((RHSKnownZero & RHSKnownOne) == 0 && 
2018              "Bits known to be one AND zero?"); 
2019       RHSKnownZero &= TypeMask;
2020       RHSKnownOne  &= TypeMask;
2021       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2022       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2023       if (ShiftAmt) {
2024         // Compute the new bits that are at the top now.
2025         APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
2026                          BitWidth - ShiftAmt));
2027         RHSKnownZero |= HighBits;  // high bits known zero.
2028       }
2029     }
2030     break;
2031   case Instruction::AShr:
2032     // If this is an arithmetic shift right and only the low-bit is set, we can
2033     // always convert this into a logical shr, even if the shift amount is
2034     // variable.  The low bit of the shift cannot be an input sign bit unless
2035     // the shift amount is >= the size of the datatype, which is undefined.
2036     if (DemandedMask == 1) {
2037       // Perform the logical shift right.
2038       Value *NewVal = BinaryOperator::createLShr(
2039                         I->getOperand(0), I->getOperand(1), I->getName());
2040       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2041       return UpdateValueUsesWith(I, NewVal);
2042     }    
2043     
2044     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2045       unsigned ShiftAmt = SA->getZExtValue();
2046       
2047       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2048       // Signed shift right.
2049       if (SimplifyDemandedBits(I->getOperand(0),
2050                                (DemandedMask.shl(ShiftAmt)) & TypeMask,
2051                                RHSKnownZero, RHSKnownOne, Depth+1))
2052         return true;
2053       assert((RHSKnownZero & RHSKnownOne) == 0 && 
2054              "Bits known to be one AND zero?"); 
2055       // Compute the new bits that are at the top now.
2056       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
2057       RHSKnownZero &= TypeMask;
2058       RHSKnownOne  &= TypeMask;
2059       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2060       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2061         
2062       // Handle the sign bits.
2063       APInt SignBit(APInt::getSignBit(BitWidth));
2064       // Adjust to where it is now in the mask.
2065       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
2066         
2067       // If the input sign bit is known to be zero, or if none of the top bits
2068       // are demanded, turn this into an unsigned shift right.
2069       if ((RHSKnownZero & SignBit) != 0 || 
2070           (HighBits & ~DemandedMask) == HighBits) {
2071         // Perform the logical shift right.
2072         Value *NewVal = BinaryOperator::createLShr(
2073                           I->getOperand(0), SA, I->getName());
2074         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2075         return UpdateValueUsesWith(I, NewVal);
2076       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2077         RHSKnownOne |= HighBits;
2078       }
2079     }
2080     break;
2081   }
2082   
2083   // If the client is only demanding bits that we know, return the known
2084   // constant.
2085   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2086     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2087   return false;
2088 }
2089
2090
2091 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
2092 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
2093 /// actually used by the caller.  This method analyzes which elements of the
2094 /// operand are undef and returns that information in UndefElts.
2095 ///
2096 /// If the information about demanded elements can be used to simplify the
2097 /// operation, the operation is simplified, then the resultant value is
2098 /// returned.  This returns null if no change was made.
2099 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2100                                                 uint64_t &UndefElts,
2101                                                 unsigned Depth) {
2102   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
2103   assert(VWidth <= 64 && "Vector too wide to analyze!");
2104   uint64_t EltMask = ~0ULL >> (64-VWidth);
2105   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2106          "Invalid DemandedElts!");
2107
2108   if (isa<UndefValue>(V)) {
2109     // If the entire vector is undefined, just return this info.
2110     UndefElts = EltMask;
2111     return 0;
2112   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2113     UndefElts = EltMask;
2114     return UndefValue::get(V->getType());
2115   }
2116   
2117   UndefElts = 0;
2118   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2119     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
2120     Constant *Undef = UndefValue::get(EltTy);
2121
2122     std::vector<Constant*> Elts;
2123     for (unsigned i = 0; i != VWidth; ++i)
2124       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
2125         Elts.push_back(Undef);
2126         UndefElts |= (1ULL << i);
2127       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
2128         Elts.push_back(Undef);
2129         UndefElts |= (1ULL << i);
2130       } else {                               // Otherwise, defined.
2131         Elts.push_back(CP->getOperand(i));
2132       }
2133         
2134     // If we changed the constant, return it.
2135     Constant *NewCP = ConstantVector::get(Elts);
2136     return NewCP != CP ? NewCP : 0;
2137   } else if (isa<ConstantAggregateZero>(V)) {
2138     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
2139     // set to undef.
2140     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
2141     Constant *Zero = Constant::getNullValue(EltTy);
2142     Constant *Undef = UndefValue::get(EltTy);
2143     std::vector<Constant*> Elts;
2144     for (unsigned i = 0; i != VWidth; ++i)
2145       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2146     UndefElts = DemandedElts ^ EltMask;
2147     return ConstantVector::get(Elts);
2148   }
2149   
2150   if (!V->hasOneUse()) {    // Other users may use these bits.
2151     if (Depth != 0) {       // Not at the root.
2152       // TODO: Just compute the UndefElts information recursively.
2153       return false;
2154     }
2155     return false;
2156   } else if (Depth == 10) {        // Limit search depth.
2157     return false;
2158   }
2159   
2160   Instruction *I = dyn_cast<Instruction>(V);
2161   if (!I) return false;        // Only analyze instructions.
2162   
2163   bool MadeChange = false;
2164   uint64_t UndefElts2;
2165   Value *TmpV;
2166   switch (I->getOpcode()) {
2167   default: break;
2168     
2169   case Instruction::InsertElement: {
2170     // If this is a variable index, we don't know which element it overwrites.
2171     // demand exactly the same input as we produce.
2172     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
2173     if (Idx == 0) {
2174       // Note that we can't propagate undef elt info, because we don't know
2175       // which elt is getting updated.
2176       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2177                                         UndefElts2, Depth+1);
2178       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2179       break;
2180     }
2181     
2182     // If this is inserting an element that isn't demanded, remove this
2183     // insertelement.
2184     unsigned IdxNo = Idx->getZExtValue();
2185     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2186       return AddSoonDeadInstToWorklist(*I, 0);
2187     
2188     // Otherwise, the element inserted overwrites whatever was there, so the
2189     // input demanded set is simpler than the output set.
2190     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2191                                       DemandedElts & ~(1ULL << IdxNo),
2192                                       UndefElts, Depth+1);
2193     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2194
2195     // The inserted element is defined.
2196     UndefElts |= 1ULL << IdxNo;
2197     break;
2198   }
2199     
2200   case Instruction::And:
2201   case Instruction::Or:
2202   case Instruction::Xor:
2203   case Instruction::Add:
2204   case Instruction::Sub:
2205   case Instruction::Mul:
2206     // div/rem demand all inputs, because they don't want divide by zero.
2207     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2208                                       UndefElts, Depth+1);
2209     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2210     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2211                                       UndefElts2, Depth+1);
2212     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2213       
2214     // Output elements are undefined if both are undefined.  Consider things
2215     // like undef&0.  The result is known zero, not undef.
2216     UndefElts &= UndefElts2;
2217     break;
2218     
2219   case Instruction::Call: {
2220     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2221     if (!II) break;
2222     switch (II->getIntrinsicID()) {
2223     default: break;
2224       
2225     // Binary vector operations that work column-wise.  A dest element is a
2226     // function of the corresponding input elements from the two inputs.
2227     case Intrinsic::x86_sse_sub_ss:
2228     case Intrinsic::x86_sse_mul_ss:
2229     case Intrinsic::x86_sse_min_ss:
2230     case Intrinsic::x86_sse_max_ss:
2231     case Intrinsic::x86_sse2_sub_sd:
2232     case Intrinsic::x86_sse2_mul_sd:
2233     case Intrinsic::x86_sse2_min_sd:
2234     case Intrinsic::x86_sse2_max_sd:
2235       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2236                                         UndefElts, Depth+1);
2237       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2238       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2239                                         UndefElts2, Depth+1);
2240       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2241
2242       // If only the low elt is demanded and this is a scalarizable intrinsic,
2243       // scalarize it now.
2244       if (DemandedElts == 1) {
2245         switch (II->getIntrinsicID()) {
2246         default: break;
2247         case Intrinsic::x86_sse_sub_ss:
2248         case Intrinsic::x86_sse_mul_ss:
2249         case Intrinsic::x86_sse2_sub_sd:
2250         case Intrinsic::x86_sse2_mul_sd:
2251           // TODO: Lower MIN/MAX/ABS/etc
2252           Value *LHS = II->getOperand(1);
2253           Value *RHS = II->getOperand(2);
2254           // Extract the element as scalars.
2255           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2256           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2257           
2258           switch (II->getIntrinsicID()) {
2259           default: assert(0 && "Case stmts out of sync!");
2260           case Intrinsic::x86_sse_sub_ss:
2261           case Intrinsic::x86_sse2_sub_sd:
2262             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2263                                                         II->getName()), *II);
2264             break;
2265           case Intrinsic::x86_sse_mul_ss:
2266           case Intrinsic::x86_sse2_mul_sd:
2267             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2268                                                          II->getName()), *II);
2269             break;
2270           }
2271           
2272           Instruction *New =
2273             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2274                                   II->getName());
2275           InsertNewInstBefore(New, *II);
2276           AddSoonDeadInstToWorklist(*II, 0);
2277           return New;
2278         }            
2279       }
2280         
2281       // Output elements are undefined if both are undefined.  Consider things
2282       // like undef&0.  The result is known zero, not undef.
2283       UndefElts &= UndefElts2;
2284       break;
2285     }
2286     break;
2287   }
2288   }
2289   return MadeChange ? I : 0;
2290 }
2291
2292 /// @returns true if the specified compare instruction is
2293 /// true when both operands are equal...
2294 /// @brief Determine if the ICmpInst returns true if both operands are equal
2295 static bool isTrueWhenEqual(ICmpInst &ICI) {
2296   ICmpInst::Predicate pred = ICI.getPredicate();
2297   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
2298          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2299          pred == ICmpInst::ICMP_SLE;
2300 }
2301
2302 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2303 /// function is designed to check a chain of associative operators for a
2304 /// potential to apply a certain optimization.  Since the optimization may be
2305 /// applicable if the expression was reassociated, this checks the chain, then
2306 /// reassociates the expression as necessary to expose the optimization
2307 /// opportunity.  This makes use of a special Functor, which must define
2308 /// 'shouldApply' and 'apply' methods.
2309 ///
2310 template<typename Functor>
2311 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2312   unsigned Opcode = Root.getOpcode();
2313   Value *LHS = Root.getOperand(0);
2314
2315   // Quick check, see if the immediate LHS matches...
2316   if (F.shouldApply(LHS))
2317     return F.apply(Root);
2318
2319   // Otherwise, if the LHS is not of the same opcode as the root, return.
2320   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2321   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2322     // Should we apply this transform to the RHS?
2323     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2324
2325     // If not to the RHS, check to see if we should apply to the LHS...
2326     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2327       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2328       ShouldApply = true;
2329     }
2330
2331     // If the functor wants to apply the optimization to the RHS of LHSI,
2332     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2333     if (ShouldApply) {
2334       BasicBlock *BB = Root.getParent();
2335
2336       // Now all of the instructions are in the current basic block, go ahead
2337       // and perform the reassociation.
2338       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2339
2340       // First move the selected RHS to the LHS of the root...
2341       Root.setOperand(0, LHSI->getOperand(1));
2342
2343       // Make what used to be the LHS of the root be the user of the root...
2344       Value *ExtraOperand = TmpLHSI->getOperand(1);
2345       if (&Root == TmpLHSI) {
2346         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2347         return 0;
2348       }
2349       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2350       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2351       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2352       BasicBlock::iterator ARI = &Root; ++ARI;
2353       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2354       ARI = Root;
2355
2356       // Now propagate the ExtraOperand down the chain of instructions until we
2357       // get to LHSI.
2358       while (TmpLHSI != LHSI) {
2359         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2360         // Move the instruction to immediately before the chain we are
2361         // constructing to avoid breaking dominance properties.
2362         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2363         BB->getInstList().insert(ARI, NextLHSI);
2364         ARI = NextLHSI;
2365
2366         Value *NextOp = NextLHSI->getOperand(1);
2367         NextLHSI->setOperand(1, ExtraOperand);
2368         TmpLHSI = NextLHSI;
2369         ExtraOperand = NextOp;
2370       }
2371
2372       // Now that the instructions are reassociated, have the functor perform
2373       // the transformation...
2374       return F.apply(Root);
2375     }
2376
2377     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2378   }
2379   return 0;
2380 }
2381
2382
2383 // AddRHS - Implements: X + X --> X << 1
2384 struct AddRHS {
2385   Value *RHS;
2386   AddRHS(Value *rhs) : RHS(rhs) {}
2387   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2388   Instruction *apply(BinaryOperator &Add) const {
2389     return BinaryOperator::createShl(Add.getOperand(0),
2390                                   ConstantInt::get(Add.getType(), 1));
2391   }
2392 };
2393
2394 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2395 //                 iff C1&C2 == 0
2396 struct AddMaskingAnd {
2397   Constant *C2;
2398   AddMaskingAnd(Constant *c) : C2(c) {}
2399   bool shouldApply(Value *LHS) const {
2400     ConstantInt *C1;
2401     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2402            ConstantExpr::getAnd(C1, C2)->isNullValue();
2403   }
2404   Instruction *apply(BinaryOperator &Add) const {
2405     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
2406   }
2407 };
2408
2409 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2410                                              InstCombiner *IC) {
2411   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2412     if (Constant *SOC = dyn_cast<Constant>(SO))
2413       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2414
2415     return IC->InsertNewInstBefore(CastInst::create(
2416           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2417   }
2418
2419   // Figure out if the constant is the left or the right argument.
2420   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2421   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2422
2423   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2424     if (ConstIsRHS)
2425       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2426     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2427   }
2428
2429   Value *Op0 = SO, *Op1 = ConstOperand;
2430   if (!ConstIsRHS)
2431     std::swap(Op0, Op1);
2432   Instruction *New;
2433   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2434     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2435   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2436     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2437                           SO->getName()+".cmp");
2438   else {
2439     assert(0 && "Unknown binary instruction type!");
2440     abort();
2441   }
2442   return IC->InsertNewInstBefore(New, I);
2443 }
2444
2445 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2446 // constant as the other operand, try to fold the binary operator into the
2447 // select arguments.  This also works for Cast instructions, which obviously do
2448 // not have a second operand.
2449 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2450                                      InstCombiner *IC) {
2451   // Don't modify shared select instructions
2452   if (!SI->hasOneUse()) return 0;
2453   Value *TV = SI->getOperand(1);
2454   Value *FV = SI->getOperand(2);
2455
2456   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2457     // Bool selects with constant operands can be folded to logical ops.
2458     if (SI->getType() == Type::Int1Ty) return 0;
2459
2460     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2461     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2462
2463     return new SelectInst(SI->getCondition(), SelectTrueVal,
2464                           SelectFalseVal);
2465   }
2466   return 0;
2467 }
2468
2469
2470 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2471 /// node as operand #0, see if we can fold the instruction into the PHI (which
2472 /// is only possible if all operands to the PHI are constants).
2473 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2474   PHINode *PN = cast<PHINode>(I.getOperand(0));
2475   unsigned NumPHIValues = PN->getNumIncomingValues();
2476   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2477
2478   // Check to see if all of the operands of the PHI are constants.  If there is
2479   // one non-constant value, remember the BB it is.  If there is more than one
2480   // or if *it* is a PHI, bail out.
2481   BasicBlock *NonConstBB = 0;
2482   for (unsigned i = 0; i != NumPHIValues; ++i)
2483     if (!isa<Constant>(PN->getIncomingValue(i))) {
2484       if (NonConstBB) return 0;  // More than one non-const value.
2485       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2486       NonConstBB = PN->getIncomingBlock(i);
2487       
2488       // If the incoming non-constant value is in I's block, we have an infinite
2489       // loop.
2490       if (NonConstBB == I.getParent())
2491         return 0;
2492     }
2493   
2494   // If there is exactly one non-constant value, we can insert a copy of the
2495   // operation in that block.  However, if this is a critical edge, we would be
2496   // inserting the computation one some other paths (e.g. inside a loop).  Only
2497   // do this if the pred block is unconditionally branching into the phi block.
2498   if (NonConstBB) {
2499     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2500     if (!BI || !BI->isUnconditional()) return 0;
2501   }
2502
2503   // Okay, we can do the transformation: create the new PHI node.
2504   PHINode *NewPN = new PHINode(I.getType(), "");
2505   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2506   InsertNewInstBefore(NewPN, *PN);
2507   NewPN->takeName(PN);
2508
2509   // Next, add all of the operands to the PHI.
2510   if (I.getNumOperands() == 2) {
2511     Constant *C = cast<Constant>(I.getOperand(1));
2512     for (unsigned i = 0; i != NumPHIValues; ++i) {
2513       Value *InV;
2514       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2515         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2516           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2517         else
2518           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2519       } else {
2520         assert(PN->getIncomingBlock(i) == NonConstBB);
2521         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2522           InV = BinaryOperator::create(BO->getOpcode(),
2523                                        PN->getIncomingValue(i), C, "phitmp",
2524                                        NonConstBB->getTerminator());
2525         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2526           InV = CmpInst::create(CI->getOpcode(), 
2527                                 CI->getPredicate(),
2528                                 PN->getIncomingValue(i), C, "phitmp",
2529                                 NonConstBB->getTerminator());
2530         else
2531           assert(0 && "Unknown binop!");
2532         
2533         AddToWorkList(cast<Instruction>(InV));
2534       }
2535       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2536     }
2537   } else { 
2538     CastInst *CI = cast<CastInst>(&I);
2539     const Type *RetTy = CI->getType();
2540     for (unsigned i = 0; i != NumPHIValues; ++i) {
2541       Value *InV;
2542       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2543         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2544       } else {
2545         assert(PN->getIncomingBlock(i) == NonConstBB);
2546         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
2547                                I.getType(), "phitmp", 
2548                                NonConstBB->getTerminator());
2549         AddToWorkList(cast<Instruction>(InV));
2550       }
2551       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2552     }
2553   }
2554   return ReplaceInstUsesWith(I, NewPN);
2555 }
2556
2557 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2558   bool Changed = SimplifyCommutative(I);
2559   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2560
2561   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2562     // X + undef -> undef
2563     if (isa<UndefValue>(RHS))
2564       return ReplaceInstUsesWith(I, RHS);
2565
2566     // X + 0 --> X
2567     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2568       if (RHSC->isNullValue())
2569         return ReplaceInstUsesWith(I, LHS);
2570     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2571       if (CFP->isExactlyValue(-0.0))
2572         return ReplaceInstUsesWith(I, LHS);
2573     }
2574
2575     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2576       // X + (signbit) --> X ^ signbit
2577       uint64_t Val = CI->getZExtValue();
2578       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
2579         return BinaryOperator::createXor(LHS, RHS);
2580       
2581       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2582       // (X & 254)+1 -> (X&254)|1
2583       uint64_t KnownZero, KnownOne;
2584       if (!isa<VectorType>(I.getType()) &&
2585           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
2586                                KnownZero, KnownOne))
2587         return &I;
2588     }
2589
2590     if (isa<PHINode>(LHS))
2591       if (Instruction *NV = FoldOpIntoPhi(I))
2592         return NV;
2593     
2594     ConstantInt *XorRHS = 0;
2595     Value *XorLHS = 0;
2596     if (isa<ConstantInt>(RHSC) &&
2597         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2598       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2599       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2600       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2601       
2602       uint64_t C0080Val = 1ULL << 31;
2603       int64_t CFF80Val = -C0080Val;
2604       unsigned Size = 32;
2605       do {
2606         if (TySizeBits > Size) {
2607           bool Found = false;
2608           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2609           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2610           if (RHSSExt == CFF80Val) {
2611             if (XorRHS->getZExtValue() == C0080Val)
2612               Found = true;
2613           } else if (RHSZExt == C0080Val) {
2614             if (XorRHS->getSExtValue() == CFF80Val)
2615               Found = true;
2616           }
2617           if (Found) {
2618             // This is a sign extend if the top bits are known zero.
2619             uint64_t Mask = ~0ULL;
2620             Mask <<= 64-(TySizeBits-Size);
2621             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
2622             if (!MaskedValueIsZero(XorLHS, Mask))
2623               Size = 0;  // Not a sign ext, but can't be any others either.
2624             goto FoundSExt;
2625           }
2626         }
2627         Size >>= 1;
2628         C0080Val >>= Size;
2629         CFF80Val >>= Size;
2630       } while (Size >= 8);
2631       
2632 FoundSExt:
2633       const Type *MiddleType = 0;
2634       switch (Size) {
2635       default: break;
2636       case 32: MiddleType = Type::Int32Ty; break;
2637       case 16: MiddleType = Type::Int16Ty; break;
2638       case 8:  MiddleType = Type::Int8Ty; break;
2639       }
2640       if (MiddleType) {
2641         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2642         InsertNewInstBefore(NewTrunc, I);
2643         return new SExtInst(NewTrunc, I.getType());
2644       }
2645     }
2646   }
2647
2648   // X + X --> X << 1
2649   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2650     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2651
2652     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2653       if (RHSI->getOpcode() == Instruction::Sub)
2654         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2655           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2656     }
2657     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2658       if (LHSI->getOpcode() == Instruction::Sub)
2659         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2660           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2661     }
2662   }
2663
2664   // -A + B  -->  B - A
2665   if (Value *V = dyn_castNegVal(LHS))
2666     return BinaryOperator::createSub(RHS, V);
2667
2668   // A + -B  -->  A - B
2669   if (!isa<Constant>(RHS))
2670     if (Value *V = dyn_castNegVal(RHS))
2671       return BinaryOperator::createSub(LHS, V);
2672
2673
2674   ConstantInt *C2;
2675   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2676     if (X == RHS)   // X*C + X --> X * (C+1)
2677       return BinaryOperator::createMul(RHS, AddOne(C2));
2678
2679     // X*C1 + X*C2 --> X * (C1+C2)
2680     ConstantInt *C1;
2681     if (X == dyn_castFoldableMul(RHS, C1))
2682       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
2683   }
2684
2685   // X + X*C --> X * (C+1)
2686   if (dyn_castFoldableMul(RHS, C2) == LHS)
2687     return BinaryOperator::createMul(LHS, AddOne(C2));
2688
2689   // X + ~X --> -1   since   ~X = -X-1
2690   if (dyn_castNotVal(LHS) == RHS ||
2691       dyn_castNotVal(RHS) == LHS)
2692     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2693   
2694
2695   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2696   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2697     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2698       return R;
2699
2700   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2701     Value *X = 0;
2702     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
2703       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2704       return BinaryOperator::createSub(C, X);
2705     }
2706
2707     // (X & FF00) + xx00  -> (X+xx00) & FF00
2708     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2709       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2710       if (Anded == CRHS) {
2711         // See if all bits from the first bit set in the Add RHS up are included
2712         // in the mask.  First, get the rightmost bit.
2713         uint64_t AddRHSV = CRHS->getZExtValue();
2714
2715         // Form a mask of all bits from the lowest bit added through the top.
2716         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2717         AddRHSHighBits &= C2->getType()->getBitMask();
2718
2719         // See if the and mask includes all of these bits.
2720         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
2721
2722         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2723           // Okay, the xform is safe.  Insert the new add pronto.
2724           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2725                                                             LHS->getName()), I);
2726           return BinaryOperator::createAnd(NewAdd, C2);
2727         }
2728       }
2729     }
2730
2731     // Try to fold constant add into select arguments.
2732     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2733       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2734         return R;
2735   }
2736
2737   // add (cast *A to intptrtype) B -> 
2738   //   cast (GEP (cast *A to sbyte*) B) -> 
2739   //     intptrtype
2740   {
2741     CastInst *CI = dyn_cast<CastInst>(LHS);
2742     Value *Other = RHS;
2743     if (!CI) {
2744       CI = dyn_cast<CastInst>(RHS);
2745       Other = LHS;
2746     }
2747     if (CI && CI->getType()->isSized() && 
2748         (CI->getType()->getPrimitiveSizeInBits() == 
2749          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2750         && isa<PointerType>(CI->getOperand(0)->getType())) {
2751       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2752                                    PointerType::get(Type::Int8Ty), I);
2753       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2754       return new PtrToIntInst(I2, CI->getType());
2755     }
2756   }
2757
2758   return Changed ? &I : 0;
2759 }
2760
2761 // isSignBit - Return true if the value represented by the constant only has the
2762 // highest order bit set.
2763 static bool isSignBit(ConstantInt *CI) {
2764   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
2765   return CI->getValue() == APInt::getSignBit(NumBits);
2766 }
2767
2768 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2769   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2770
2771   if (Op0 == Op1)         // sub X, X  -> 0
2772     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2773
2774   // If this is a 'B = x-(-A)', change to B = x+A...
2775   if (Value *V = dyn_castNegVal(Op1))
2776     return BinaryOperator::createAdd(Op0, V);
2777
2778   if (isa<UndefValue>(Op0))
2779     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2780   if (isa<UndefValue>(Op1))
2781     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2782
2783   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2784     // Replace (-1 - A) with (~A)...
2785     if (C->isAllOnesValue())
2786       return BinaryOperator::createNot(Op1);
2787
2788     // C - ~X == X + (1+C)
2789     Value *X = 0;
2790     if (match(Op1, m_Not(m_Value(X))))
2791       return BinaryOperator::createAdd(X,
2792                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2793     // -(X >>u 31) -> (X >>s 31)
2794     // -(X >>s 31) -> (X >>u 31)
2795     if (C->isNullValue()) {
2796       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2797         if (SI->getOpcode() == Instruction::LShr) {
2798           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2799             // Check to see if we are shifting out everything but the sign bit.
2800             if (CU->getZExtValue() == 
2801                 SI->getType()->getPrimitiveSizeInBits()-1) {
2802               // Ok, the transformation is safe.  Insert AShr.
2803               return BinaryOperator::create(Instruction::AShr, 
2804                                           SI->getOperand(0), CU, SI->getName());
2805             }
2806           }
2807         }
2808         else if (SI->getOpcode() == Instruction::AShr) {
2809           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2810             // Check to see if we are shifting out everything but the sign bit.
2811             if (CU->getZExtValue() == 
2812                 SI->getType()->getPrimitiveSizeInBits()-1) {
2813               // Ok, the transformation is safe.  Insert LShr. 
2814               return BinaryOperator::createLShr(
2815                                           SI->getOperand(0), CU, SI->getName());
2816             }
2817           }
2818         } 
2819     }
2820
2821     // Try to fold constant sub into select arguments.
2822     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2823       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2824         return R;
2825
2826     if (isa<PHINode>(Op0))
2827       if (Instruction *NV = FoldOpIntoPhi(I))
2828         return NV;
2829   }
2830
2831   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2832     if (Op1I->getOpcode() == Instruction::Add &&
2833         !Op0->getType()->isFPOrFPVector()) {
2834       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2835         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2836       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2837         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2838       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2839         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2840           // C1-(X+C2) --> (C1-C2)-X
2841           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2842                                            Op1I->getOperand(0));
2843       }
2844     }
2845
2846     if (Op1I->hasOneUse()) {
2847       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2848       // is not used by anyone else...
2849       //
2850       if (Op1I->getOpcode() == Instruction::Sub &&
2851           !Op1I->getType()->isFPOrFPVector()) {
2852         // Swap the two operands of the subexpr...
2853         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2854         Op1I->setOperand(0, IIOp1);
2855         Op1I->setOperand(1, IIOp0);
2856
2857         // Create the new top level add instruction...
2858         return BinaryOperator::createAdd(Op0, Op1);
2859       }
2860
2861       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2862       //
2863       if (Op1I->getOpcode() == Instruction::And &&
2864           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2865         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2866
2867         Value *NewNot =
2868           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2869         return BinaryOperator::createAnd(Op0, NewNot);
2870       }
2871
2872       // 0 - (X sdiv C)  -> (X sdiv -C)
2873       if (Op1I->getOpcode() == Instruction::SDiv)
2874         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2875           if (CSI->isNullValue())
2876             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2877               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2878                                                ConstantExpr::getNeg(DivRHS));
2879
2880       // X - X*C --> X * (1-C)
2881       ConstantInt *C2 = 0;
2882       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2883         Constant *CP1 =
2884           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2885         return BinaryOperator::createMul(Op0, CP1);
2886       }
2887     }
2888   }
2889
2890   if (!Op0->getType()->isFPOrFPVector())
2891     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2892       if (Op0I->getOpcode() == Instruction::Add) {
2893         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2894           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2895         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2896           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2897       } else if (Op0I->getOpcode() == Instruction::Sub) {
2898         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2899           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2900       }
2901
2902   ConstantInt *C1;
2903   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2904     if (X == Op1) { // X*C - X --> X * (C-1)
2905       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2906       return BinaryOperator::createMul(Op1, CP1);
2907     }
2908
2909     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2910     if (X == dyn_castFoldableMul(Op1, C2))
2911       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2912   }
2913   return 0;
2914 }
2915
2916 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2917 /// really just returns true if the most significant (sign) bit is set.
2918 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2919   switch (pred) {
2920     case ICmpInst::ICMP_SLT: 
2921       // True if LHS s< RHS and RHS == 0
2922       return RHS->isNullValue();
2923     case ICmpInst::ICMP_SLE: 
2924       // True if LHS s<= RHS and RHS == -1
2925       return RHS->isAllOnesValue();
2926     case ICmpInst::ICMP_UGE: 
2927       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2928       return RHS->getZExtValue() == (1ULL << 
2929         (RHS->getType()->getPrimitiveSizeInBits()-1));
2930     case ICmpInst::ICMP_UGT:
2931       // True if LHS u> RHS and RHS == high-bit-mask - 1
2932       return RHS->getZExtValue() ==
2933         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2934     default:
2935       return false;
2936   }
2937 }
2938
2939 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2940   bool Changed = SimplifyCommutative(I);
2941   Value *Op0 = I.getOperand(0);
2942
2943   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2944     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2945
2946   // Simplify mul instructions with a constant RHS...
2947   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2948     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2949
2950       // ((X << C1)*C2) == (X * (C2 << C1))
2951       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2952         if (SI->getOpcode() == Instruction::Shl)
2953           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2954             return BinaryOperator::createMul(SI->getOperand(0),
2955                                              ConstantExpr::getShl(CI, ShOp));
2956
2957       if (CI->isNullValue())
2958         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2959       if (CI->equalsInt(1))                  // X * 1  == X
2960         return ReplaceInstUsesWith(I, Op0);
2961       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2962         return BinaryOperator::createNeg(Op0, I.getName());
2963
2964       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2965       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2966         uint64_t C = Log2_64(Val);
2967         return BinaryOperator::createShl(Op0,
2968                                       ConstantInt::get(Op0->getType(), C));
2969       }
2970     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2971       if (Op1F->isNullValue())
2972         return ReplaceInstUsesWith(I, Op1);
2973
2974       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2975       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2976       if (Op1F->getValue() == 1.0)
2977         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2978     }
2979     
2980     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2981       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2982           isa<ConstantInt>(Op0I->getOperand(1))) {
2983         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2984         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2985                                                      Op1, "tmp");
2986         InsertNewInstBefore(Add, I);
2987         Value *C1C2 = ConstantExpr::getMul(Op1, 
2988                                            cast<Constant>(Op0I->getOperand(1)));
2989         return BinaryOperator::createAdd(Add, C1C2);
2990         
2991       }
2992
2993     // Try to fold constant mul into select arguments.
2994     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2995       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2996         return R;
2997
2998     if (isa<PHINode>(Op0))
2999       if (Instruction *NV = FoldOpIntoPhi(I))
3000         return NV;
3001   }
3002
3003   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3004     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3005       return BinaryOperator::createMul(Op0v, Op1v);
3006
3007   // If one of the operands of the multiply is a cast from a boolean value, then
3008   // we know the bool is either zero or one, so this is a 'masking' multiply.
3009   // See if we can simplify things based on how the boolean was originally
3010   // formed.
3011   CastInst *BoolCast = 0;
3012   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3013     if (CI->getOperand(0)->getType() == Type::Int1Ty)
3014       BoolCast = CI;
3015   if (!BoolCast)
3016     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3017       if (CI->getOperand(0)->getType() == Type::Int1Ty)
3018         BoolCast = CI;
3019   if (BoolCast) {
3020     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3021       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3022       const Type *SCOpTy = SCIOp0->getType();
3023
3024       // If the icmp is true iff the sign bit of X is set, then convert this
3025       // multiply into a shift/and combination.
3026       if (isa<ConstantInt>(SCIOp1) &&
3027           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
3028         // Shift the X value right to turn it into "all signbits".
3029         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3030                                           SCOpTy->getPrimitiveSizeInBits()-1);
3031         Value *V =
3032           InsertNewInstBefore(
3033             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
3034                                             BoolCast->getOperand(0)->getName()+
3035                                             ".mask"), I);
3036
3037         // If the multiply type is not the same as the source type, sign extend
3038         // or truncate to the multiply type.
3039         if (I.getType() != V->getType()) {
3040           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3041           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3042           Instruction::CastOps opcode = 
3043             (SrcBits == DstBits ? Instruction::BitCast : 
3044              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3045           V = InsertCastBefore(opcode, V, I.getType(), I);
3046         }
3047
3048         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3049         return BinaryOperator::createAnd(V, OtherOp);
3050       }
3051     }
3052   }
3053
3054   return Changed ? &I : 0;
3055 }
3056
3057 /// This function implements the transforms on div instructions that work
3058 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3059 /// used by the visitors to those instructions.
3060 /// @brief Transforms common to all three div instructions
3061 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3062   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3063
3064   // undef / X -> 0
3065   if (isa<UndefValue>(Op0))
3066     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3067
3068   // X / undef -> undef
3069   if (isa<UndefValue>(Op1))
3070     return ReplaceInstUsesWith(I, Op1);
3071
3072   // Handle cases involving: div X, (select Cond, Y, Z)
3073   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3074     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
3075     // same basic block, then we replace the select with Y, and the condition 
3076     // of the select with false (if the cond value is in the same BB).  If the
3077     // select has uses other than the div, this allows them to be simplified
3078     // also. Note that div X, Y is just as good as div X, 0 (undef)
3079     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3080       if (ST->isNullValue()) {
3081         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3082         if (CondI && CondI->getParent() == I.getParent())
3083           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3084         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3085           I.setOperand(1, SI->getOperand(2));
3086         else
3087           UpdateValueUsesWith(SI, SI->getOperand(2));
3088         return &I;
3089       }
3090
3091     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3092     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3093       if (ST->isNullValue()) {
3094         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3095         if (CondI && CondI->getParent() == I.getParent())
3096           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3097         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3098           I.setOperand(1, SI->getOperand(1));
3099         else
3100           UpdateValueUsesWith(SI, SI->getOperand(1));
3101         return &I;
3102       }
3103   }
3104
3105   return 0;
3106 }
3107
3108 /// This function implements the transforms common to both integer division
3109 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3110 /// division instructions.
3111 /// @brief Common integer divide transforms
3112 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3113   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3114
3115   if (Instruction *Common = commonDivTransforms(I))
3116     return Common;
3117
3118   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3119     // div X, 1 == X
3120     if (RHS->equalsInt(1))
3121       return ReplaceInstUsesWith(I, Op0);
3122
3123     // (X / C1) / C2  -> X / (C1*C2)
3124     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3125       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3126         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3127           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3128                                         ConstantExpr::getMul(RHS, LHSRHS));
3129         }
3130
3131     if (!RHS->isNullValue()) { // avoid X udiv 0
3132       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3133         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3134           return R;
3135       if (isa<PHINode>(Op0))
3136         if (Instruction *NV = FoldOpIntoPhi(I))
3137           return NV;
3138     }
3139   }
3140
3141   // 0 / X == 0, we don't need to preserve faults!
3142   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3143     if (LHS->equalsInt(0))
3144       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3145
3146   return 0;
3147 }
3148
3149 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3150   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3151
3152   // Handle the integer div common cases
3153   if (Instruction *Common = commonIDivTransforms(I))
3154     return Common;
3155
3156   // X udiv C^2 -> X >> C
3157   // Check to see if this is an unsigned division with an exact power of 2,
3158   // if so, convert to a right shift.
3159   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3160     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
3161       if (isPowerOf2_64(Val)) {
3162         uint64_t ShiftAmt = Log2_64(Val);
3163         return BinaryOperator::createLShr(Op0, 
3164                                     ConstantInt::get(Op0->getType(), ShiftAmt));
3165       }
3166   }
3167
3168   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3169   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3170     if (RHSI->getOpcode() == Instruction::Shl &&
3171         isa<ConstantInt>(RHSI->getOperand(0))) {
3172       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3173       if (isPowerOf2_64(C1)) {
3174         Value *N = RHSI->getOperand(1);
3175         const Type *NTy = N->getType();
3176         if (uint64_t C2 = Log2_64(C1)) {
3177           Constant *C2V = ConstantInt::get(NTy, C2);
3178           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
3179         }
3180         return BinaryOperator::createLShr(Op0, N);
3181       }
3182     }
3183   }
3184   
3185   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3186   // where C1&C2 are powers of two.
3187   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3188     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3189       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3190         uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3191         if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3192           // Compute the shift amounts
3193           unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3194           // Construct the "on true" case of the select
3195           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3196           Instruction *TSI = BinaryOperator::createLShr(
3197                                                  Op0, TC, SI->getName()+".t");
3198           TSI = InsertNewInstBefore(TSI, I);
3199   
3200           // Construct the "on false" case of the select
3201           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3202           Instruction *FSI = BinaryOperator::createLShr(
3203                                                  Op0, FC, SI->getName()+".f");
3204           FSI = InsertNewInstBefore(FSI, I);
3205
3206           // construct the select instruction and return it.
3207           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
3208         }
3209       }
3210   return 0;
3211 }
3212
3213 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3214   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3215
3216   // Handle the integer div common cases
3217   if (Instruction *Common = commonIDivTransforms(I))
3218     return Common;
3219
3220   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3221     // sdiv X, -1 == -X
3222     if (RHS->isAllOnesValue())
3223       return BinaryOperator::createNeg(Op0);
3224
3225     // -X/C -> X/-C
3226     if (Value *LHSNeg = dyn_castNegVal(Op0))
3227       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3228   }
3229
3230   // If the sign bits of both operands are zero (i.e. we can prove they are
3231   // unsigned inputs), turn this into a udiv.
3232   if (I.getType()->isInteger()) {
3233     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3234     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3235       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3236     }
3237   }      
3238   
3239   return 0;
3240 }
3241
3242 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3243   return commonDivTransforms(I);
3244 }
3245
3246 /// GetFactor - If we can prove that the specified value is at least a multiple
3247 /// of some factor, return that factor.
3248 static Constant *GetFactor(Value *V) {
3249   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3250     return CI;
3251   
3252   // Unless we can be tricky, we know this is a multiple of 1.
3253   Constant *Result = ConstantInt::get(V->getType(), 1);
3254   
3255   Instruction *I = dyn_cast<Instruction>(V);
3256   if (!I) return Result;
3257   
3258   if (I->getOpcode() == Instruction::Mul) {
3259     // Handle multiplies by a constant, etc.
3260     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3261                                 GetFactor(I->getOperand(1)));
3262   } else if (I->getOpcode() == Instruction::Shl) {
3263     // (X<<C) -> X * (1 << C)
3264     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3265       ShRHS = ConstantExpr::getShl(Result, ShRHS);
3266       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3267     }
3268   } else if (I->getOpcode() == Instruction::And) {
3269     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3270       // X & 0xFFF0 is known to be a multiple of 16.
3271       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3272       if (Zeros != V->getType()->getPrimitiveSizeInBits())
3273         return ConstantExpr::getShl(Result, 
3274                                     ConstantInt::get(Result->getType(), Zeros));
3275     }
3276   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3277     // Only handle int->int casts.
3278     if (!CI->isIntegerCast())
3279       return Result;
3280     Value *Op = CI->getOperand(0);
3281     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
3282   }    
3283   return Result;
3284 }
3285
3286 /// This function implements the transforms on rem instructions that work
3287 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3288 /// is used by the visitors to those instructions.
3289 /// @brief Transforms common to all three rem instructions
3290 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3291   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3292
3293   // 0 % X == 0, we don't need to preserve faults!
3294   if (Constant *LHS = dyn_cast<Constant>(Op0))
3295     if (LHS->isNullValue())
3296       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3297
3298   if (isa<UndefValue>(Op0))              // undef % X -> 0
3299     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3300   if (isa<UndefValue>(Op1))
3301     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3302
3303   // Handle cases involving: rem X, (select Cond, Y, Z)
3304   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3305     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3306     // the same basic block, then we replace the select with Y, and the
3307     // condition of the select with false (if the cond value is in the same
3308     // BB).  If the select has uses other than the div, this allows them to be
3309     // simplified also.
3310     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3311       if (ST->isNullValue()) {
3312         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3313         if (CondI && CondI->getParent() == I.getParent())
3314           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3315         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3316           I.setOperand(1, SI->getOperand(2));
3317         else
3318           UpdateValueUsesWith(SI, SI->getOperand(2));
3319         return &I;
3320       }
3321     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3322     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3323       if (ST->isNullValue()) {
3324         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3325         if (CondI && CondI->getParent() == I.getParent())
3326           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3327         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3328           I.setOperand(1, SI->getOperand(1));
3329         else
3330           UpdateValueUsesWith(SI, SI->getOperand(1));
3331         return &I;
3332       }
3333   }
3334
3335   return 0;
3336 }
3337
3338 /// This function implements the transforms common to both integer remainder
3339 /// instructions (urem and srem). It is called by the visitors to those integer
3340 /// remainder instructions.
3341 /// @brief Common integer remainder transforms
3342 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3343   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3344
3345   if (Instruction *common = commonRemTransforms(I))
3346     return common;
3347
3348   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3349     // X % 0 == undef, we don't need to preserve faults!
3350     if (RHS->equalsInt(0))
3351       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3352     
3353     if (RHS->equalsInt(1))  // X % 1 == 0
3354       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355
3356     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3357       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3358         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3359           return R;
3360       } else if (isa<PHINode>(Op0I)) {
3361         if (Instruction *NV = FoldOpIntoPhi(I))
3362           return NV;
3363       }
3364       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
3365       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
3366         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3367     }
3368   }
3369
3370   return 0;
3371 }
3372
3373 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3374   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3375
3376   if (Instruction *common = commonIRemTransforms(I))
3377     return common;
3378   
3379   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3380     // X urem C^2 -> X and C
3381     // Check to see if this is an unsigned remainder with an exact power of 2,
3382     // if so, convert to a bitwise and.
3383     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3384       if (isPowerOf2_64(C->getZExtValue()))
3385         return BinaryOperator::createAnd(Op0, SubOne(C));
3386   }
3387
3388   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3389     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3390     if (RHSI->getOpcode() == Instruction::Shl &&
3391         isa<ConstantInt>(RHSI->getOperand(0))) {
3392       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3393       if (isPowerOf2_64(C1)) {
3394         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3395         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3396                                                                    "tmp"), I);
3397         return BinaryOperator::createAnd(Op0, Add);
3398       }
3399     }
3400   }
3401
3402   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3403   // where C1&C2 are powers of two.
3404   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3405     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3406       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3407         // STO == 0 and SFO == 0 handled above.
3408         if (isPowerOf2_64(STO->getZExtValue()) && 
3409             isPowerOf2_64(SFO->getZExtValue())) {
3410           Value *TrueAnd = InsertNewInstBefore(
3411             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3412           Value *FalseAnd = InsertNewInstBefore(
3413             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3414           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3415         }
3416       }
3417   }
3418   
3419   return 0;
3420 }
3421
3422 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3423   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3424
3425   if (Instruction *common = commonIRemTransforms(I))
3426     return common;
3427   
3428   if (Value *RHSNeg = dyn_castNegVal(Op1))
3429     if (!isa<ConstantInt>(RHSNeg) || 
3430         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3431       // X % -Y -> X % Y
3432       AddUsesToWorkList(I);
3433       I.setOperand(1, RHSNeg);
3434       return &I;
3435     }
3436  
3437   // If the top bits of both operands are zero (i.e. we can prove they are
3438   // unsigned inputs), turn this into a urem.
3439   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3440   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3441     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3442     return BinaryOperator::createURem(Op0, Op1, I.getName());
3443   }
3444
3445   return 0;
3446 }
3447
3448 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3449   return commonRemTransforms(I);
3450 }
3451
3452 // isMaxValueMinusOne - return true if this is Max-1
3453 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3454   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3455   if (isSigned) {
3456     // Calculate 0111111111..11111
3457     APInt Val(APInt::getSignedMaxValue(TypeBits));
3458     return C->getValue() == Val-1;
3459   }
3460   return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3461 }
3462
3463 // isMinValuePlusOne - return true if this is Min+1
3464 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3465   if (isSigned) {
3466     // Calculate 1111111111000000000000
3467     uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3468     APInt Val(APInt::getSignedMinValue(TypeBits));
3469     return C->getValue() == Val+1;
3470   }
3471   return C->getValue() == 1; // unsigned
3472 }
3473
3474 // isOneBitSet - Return true if there is exactly one bit set in the specified
3475 // constant.
3476 static bool isOneBitSet(const ConstantInt *CI) {
3477   return CI->getValue().isPowerOf2();
3478 }
3479
3480 #if 0   // Currently unused
3481 // isLowOnes - Return true if the constant is of the form 0+1+.
3482 static bool isLowOnes(const ConstantInt *CI) {
3483   uint64_t V = CI->getZExtValue();
3484
3485   // There won't be bits set in parts that the type doesn't contain.
3486   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
3487
3488   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
3489   return U && V && (U & V) == 0;
3490 }
3491 #endif
3492
3493 // isHighOnes - Return true if the constant is of the form 1+0+.
3494 // This is the same as lowones(~X).
3495 static bool isHighOnes(const ConstantInt *CI) {
3496   return (~CI->getValue() + 1).isPowerOf2();
3497 }
3498
3499 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3500 /// are carefully arranged to allow folding of expressions such as:
3501 ///
3502 ///      (A < B) | (A > B) --> (A != B)
3503 ///
3504 /// Note that this is only valid if the first and second predicates have the
3505 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3506 ///
3507 /// Three bits are used to represent the condition, as follows:
3508 ///   0  A > B
3509 ///   1  A == B
3510 ///   2  A < B
3511 ///
3512 /// <=>  Value  Definition
3513 /// 000     0   Always false
3514 /// 001     1   A >  B
3515 /// 010     2   A == B
3516 /// 011     3   A >= B
3517 /// 100     4   A <  B
3518 /// 101     5   A != B
3519 /// 110     6   A <= B
3520 /// 111     7   Always true
3521 ///  
3522 static unsigned getICmpCode(const ICmpInst *ICI) {
3523   switch (ICI->getPredicate()) {
3524     // False -> 0
3525   case ICmpInst::ICMP_UGT: return 1;  // 001
3526   case ICmpInst::ICMP_SGT: return 1;  // 001
3527   case ICmpInst::ICMP_EQ:  return 2;  // 010
3528   case ICmpInst::ICMP_UGE: return 3;  // 011
3529   case ICmpInst::ICMP_SGE: return 3;  // 011
3530   case ICmpInst::ICMP_ULT: return 4;  // 100
3531   case ICmpInst::ICMP_SLT: return 4;  // 100
3532   case ICmpInst::ICMP_NE:  return 5;  // 101
3533   case ICmpInst::ICMP_ULE: return 6;  // 110
3534   case ICmpInst::ICMP_SLE: return 6;  // 110
3535     // True -> 7
3536   default:
3537     assert(0 && "Invalid ICmp predicate!");
3538     return 0;
3539   }
3540 }
3541
3542 /// getICmpValue - This is the complement of getICmpCode, which turns an
3543 /// opcode and two operands into either a constant true or false, or a brand 
3544 /// new /// ICmp instruction. The sign is passed in to determine which kind
3545 /// of predicate to use in new icmp instructions.
3546 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3547   switch (code) {
3548   default: assert(0 && "Illegal ICmp code!");
3549   case  0: return ConstantInt::getFalse();
3550   case  1: 
3551     if (sign)
3552       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3553     else
3554       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3555   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3556   case  3: 
3557     if (sign)
3558       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3559     else
3560       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3561   case  4: 
3562     if (sign)
3563       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3564     else
3565       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3566   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3567   case  6: 
3568     if (sign)
3569       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3570     else
3571       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3572   case  7: return ConstantInt::getTrue();
3573   }
3574 }
3575
3576 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3577   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3578     (ICmpInst::isSignedPredicate(p1) && 
3579      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3580     (ICmpInst::isSignedPredicate(p2) && 
3581      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3582 }
3583
3584 namespace { 
3585 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3586 struct FoldICmpLogical {
3587   InstCombiner &IC;
3588   Value *LHS, *RHS;
3589   ICmpInst::Predicate pred;
3590   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3591     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3592       pred(ICI->getPredicate()) {}
3593   bool shouldApply(Value *V) const {
3594     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3595       if (PredicatesFoldable(pred, ICI->getPredicate()))
3596         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3597                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3598     return false;
3599   }
3600   Instruction *apply(Instruction &Log) const {
3601     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3602     if (ICI->getOperand(0) != LHS) {
3603       assert(ICI->getOperand(1) == LHS);
3604       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3605     }
3606
3607     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3608     unsigned LHSCode = getICmpCode(ICI);
3609     unsigned RHSCode = getICmpCode(RHSICI);
3610     unsigned Code;
3611     switch (Log.getOpcode()) {
3612     case Instruction::And: Code = LHSCode & RHSCode; break;
3613     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3614     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3615     default: assert(0 && "Illegal logical opcode!"); return 0;
3616     }
3617
3618     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3619                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3620       
3621     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3622     if (Instruction *I = dyn_cast<Instruction>(RV))
3623       return I;
3624     // Otherwise, it's a constant boolean value...
3625     return IC.ReplaceInstUsesWith(Log, RV);
3626   }
3627 };
3628 } // end anonymous namespace
3629
3630 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3631 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3632 // guaranteed to be a binary operator.
3633 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3634                                     ConstantInt *OpRHS,
3635                                     ConstantInt *AndRHS,
3636                                     BinaryOperator &TheAnd) {
3637   Value *X = Op->getOperand(0);
3638   Constant *Together = 0;
3639   if (!Op->isShift())
3640     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3641
3642   switch (Op->getOpcode()) {
3643   case Instruction::Xor:
3644     if (Op->hasOneUse()) {
3645       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3646       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3647       InsertNewInstBefore(And, TheAnd);
3648       And->takeName(Op);
3649       return BinaryOperator::createXor(And, Together);
3650     }
3651     break;
3652   case Instruction::Or:
3653     if (Together == AndRHS) // (X | C) & C --> C
3654       return ReplaceInstUsesWith(TheAnd, AndRHS);
3655
3656     if (Op->hasOneUse() && Together != OpRHS) {
3657       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3658       Instruction *Or = BinaryOperator::createOr(X, Together);
3659       InsertNewInstBefore(Or, TheAnd);
3660       Or->takeName(Op);
3661       return BinaryOperator::createAnd(Or, AndRHS);
3662     }
3663     break;
3664   case Instruction::Add:
3665     if (Op->hasOneUse()) {
3666       // Adding a one to a single bit bit-field should be turned into an XOR
3667       // of the bit.  First thing to check is to see if this AND is with a
3668       // single bit constant.
3669       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
3670
3671       // Clear bits that are not part of the constant.
3672       AndRHSV &= AndRHS->getType()->getBitMask();
3673
3674       // If there is only one bit set...
3675       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3676         // Ok, at this point, we know that we are masking the result of the
3677         // ADD down to exactly one bit.  If the constant we are adding has
3678         // no bits set below this bit, then we can eliminate the ADD.
3679         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
3680
3681         // Check to see if any bits below the one bit set in AndRHSV are set.
3682         if ((AddRHS & (AndRHSV-1)) == 0) {
3683           // If not, the only thing that can effect the output of the AND is
3684           // the bit specified by AndRHSV.  If that bit is set, the effect of
3685           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3686           // no effect.
3687           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3688             TheAnd.setOperand(0, X);
3689             return &TheAnd;
3690           } else {
3691             // Pull the XOR out of the AND.
3692             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3693             InsertNewInstBefore(NewAnd, TheAnd);
3694             NewAnd->takeName(Op);
3695             return BinaryOperator::createXor(NewAnd, AndRHS);
3696           }
3697         }
3698       }
3699     }
3700     break;
3701
3702   case Instruction::Shl: {
3703     // We know that the AND will not produce any of the bits shifted in, so if
3704     // the anded constant includes them, clear them now!
3705     //
3706     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3707     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3708     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
3709
3710     if (CI == ShlMask) {   // Masking out bits that the shift already masks
3711       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3712     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3713       TheAnd.setOperand(1, CI);
3714       return &TheAnd;
3715     }
3716     break;
3717   }
3718   case Instruction::LShr:
3719   {
3720     // We know that the AND will not produce any of the bits shifted in, so if
3721     // the anded constant includes them, clear them now!  This only applies to
3722     // unsigned shifts, because a signed shr may bring in set bits!
3723     //
3724     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3725     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3726     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
3727
3728     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
3729       return ReplaceInstUsesWith(TheAnd, Op);
3730     } else if (CI != AndRHS) {
3731       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3732       return &TheAnd;
3733     }
3734     break;
3735   }
3736   case Instruction::AShr:
3737     // Signed shr.
3738     // See if this is shifting in some sign extension, then masking it out
3739     // with an and.
3740     if (Op->hasOneUse()) {
3741       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3742       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3743       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3744       if (C == AndRHS) {          // Masking out bits shifted in.
3745         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3746         // Make the argument unsigned.
3747         Value *ShVal = Op->getOperand(0);
3748         ShVal = InsertNewInstBefore(
3749             BinaryOperator::createLShr(ShVal, OpRHS, 
3750                                    Op->getName()), TheAnd);
3751         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3752       }
3753     }
3754     break;
3755   }
3756   return 0;
3757 }
3758
3759
3760 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3761 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3762 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3763 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3764 /// insert new instructions.
3765 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3766                                            bool isSigned, bool Inside, 
3767                                            Instruction &IB) {
3768   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3769             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3770          "Lo is not <= Hi in range emission code!");
3771     
3772   if (Inside) {
3773     if (Lo == Hi)  // Trivially false.
3774       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3775
3776     // V >= Min && V < Hi --> V < Hi
3777     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3778       ICmpInst::Predicate pred = (isSigned ? 
3779         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3780       return new ICmpInst(pred, V, Hi);
3781     }
3782
3783     // Emit V-Lo <u Hi-Lo
3784     Constant *NegLo = ConstantExpr::getNeg(Lo);
3785     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3786     InsertNewInstBefore(Add, IB);
3787     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3788     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3789   }
3790
3791   if (Lo == Hi)  // Trivially true.
3792     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3793
3794   // V < Min || V >= Hi -> V > Hi-1
3795   Hi = SubOne(cast<ConstantInt>(Hi));
3796   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3797     ICmpInst::Predicate pred = (isSigned ? 
3798         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3799     return new ICmpInst(pred, V, Hi);
3800   }
3801
3802   // Emit V-Lo >u Hi-1-Lo
3803   // Note that Hi has already had one subtracted from it, above.
3804   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3805   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3806   InsertNewInstBefore(Add, IB);
3807   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3808   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3809 }
3810
3811 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3812 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3813 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3814 // not, since all 1s are not contiguous.
3815 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3816   uint64_t V = Val->getZExtValue();
3817   if (!isShiftedMask_64(V)) return false;
3818
3819   // look for the first zero bit after the run of ones
3820   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3821   // look for the first non-zero bit
3822   ME = 64-CountLeadingZeros_64(V);
3823   return true;
3824 }
3825
3826
3827
3828 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3829 /// where isSub determines whether the operator is a sub.  If we can fold one of
3830 /// the following xforms:
3831 /// 
3832 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3833 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3834 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3835 ///
3836 /// return (A +/- B).
3837 ///
3838 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3839                                         ConstantInt *Mask, bool isSub,
3840                                         Instruction &I) {
3841   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3842   if (!LHSI || LHSI->getNumOperands() != 2 ||
3843       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3844
3845   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3846
3847   switch (LHSI->getOpcode()) {
3848   default: return 0;
3849   case Instruction::And:
3850     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3851       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3852       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3853         break;
3854
3855       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3856       // part, we don't need any explicit masks to take them out of A.  If that
3857       // is all N is, ignore it.
3858       unsigned MB, ME;
3859       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3860         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3861         Mask >>= 64-MB+1;
3862         if (MaskedValueIsZero(RHS, Mask))
3863           break;
3864       }
3865     }
3866     return 0;
3867   case Instruction::Or:
3868   case Instruction::Xor:
3869     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3870     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3871         ConstantExpr::getAnd(N, Mask)->isNullValue())
3872       break;
3873     return 0;
3874   }
3875   
3876   Instruction *New;
3877   if (isSub)
3878     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3879   else
3880     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3881   return InsertNewInstBefore(New, I);
3882 }
3883
3884 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3885   bool Changed = SimplifyCommutative(I);
3886   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3887
3888   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3889     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3890
3891   // and X, X = X
3892   if (Op0 == Op1)
3893     return ReplaceInstUsesWith(I, Op1);
3894
3895   // See if we can simplify any instructions used by the instruction whose sole 
3896   // purpose is to compute bits we don't care about.
3897   uint64_t KnownZero, KnownOne;
3898   if (!isa<VectorType>(I.getType())) {
3899     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3900                              KnownZero, KnownOne))
3901     return &I;
3902   } else {
3903     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3904       if (CP->isAllOnesValue())
3905         return ReplaceInstUsesWith(I, I.getOperand(0));
3906     }
3907   }
3908   
3909   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3910     uint64_t AndRHSMask = AndRHS->getZExtValue();
3911     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3912     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3913
3914     // Optimize a variety of ((val OP C1) & C2) combinations...
3915     if (isa<BinaryOperator>(Op0)) {
3916       Instruction *Op0I = cast<Instruction>(Op0);
3917       Value *Op0LHS = Op0I->getOperand(0);
3918       Value *Op0RHS = Op0I->getOperand(1);
3919       switch (Op0I->getOpcode()) {
3920       case Instruction::Xor:
3921       case Instruction::Or:
3922         // If the mask is only needed on one incoming arm, push it up.
3923         if (Op0I->hasOneUse()) {
3924           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3925             // Not masking anything out for the LHS, move to RHS.
3926             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3927                                                    Op0RHS->getName()+".masked");
3928             InsertNewInstBefore(NewRHS, I);
3929             return BinaryOperator::create(
3930                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3931           }
3932           if (!isa<Constant>(Op0RHS) &&
3933               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3934             // Not masking anything out for the RHS, move to LHS.
3935             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3936                                                    Op0LHS->getName()+".masked");
3937             InsertNewInstBefore(NewLHS, I);
3938             return BinaryOperator::create(
3939                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3940           }
3941         }
3942
3943         break;
3944       case Instruction::Add:
3945         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3946         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3947         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3948         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3949           return BinaryOperator::createAnd(V, AndRHS);
3950         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3951           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3952         break;
3953
3954       case Instruction::Sub:
3955         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3956         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3957         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3958         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3959           return BinaryOperator::createAnd(V, AndRHS);
3960         break;
3961       }
3962
3963       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3964         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3965           return Res;
3966     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3967       // If this is an integer truncation or change from signed-to-unsigned, and
3968       // if the source is an and/or with immediate, transform it.  This
3969       // frequently occurs for bitfield accesses.
3970       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3971         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3972             CastOp->getNumOperands() == 2)
3973           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3974             if (CastOp->getOpcode() == Instruction::And) {
3975               // Change: and (cast (and X, C1) to T), C2
3976               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3977               // This will fold the two constants together, which may allow 
3978               // other simplifications.
3979               Instruction *NewCast = CastInst::createTruncOrBitCast(
3980                 CastOp->getOperand(0), I.getType(), 
3981                 CastOp->getName()+".shrunk");
3982               NewCast = InsertNewInstBefore(NewCast, I);
3983               // trunc_or_bitcast(C1)&C2
3984               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3985               C3 = ConstantExpr::getAnd(C3, AndRHS);
3986               return BinaryOperator::createAnd(NewCast, C3);
3987             } else if (CastOp->getOpcode() == Instruction::Or) {
3988               // Change: and (cast (or X, C1) to T), C2
3989               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3990               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3991               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3992                 return ReplaceInstUsesWith(I, AndRHS);
3993             }
3994       }
3995     }
3996
3997     // Try to fold constant and into select arguments.
3998     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3999       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4000         return R;
4001     if (isa<PHINode>(Op0))
4002       if (Instruction *NV = FoldOpIntoPhi(I))
4003         return NV;
4004   }
4005
4006   Value *Op0NotVal = dyn_castNotVal(Op0);
4007   Value *Op1NotVal = dyn_castNotVal(Op1);
4008
4009   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4010     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4011
4012   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4013   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4014     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4015                                                I.getName()+".demorgan");
4016     InsertNewInstBefore(Or, I);
4017     return BinaryOperator::createNot(Or);
4018   }
4019   
4020   {
4021     Value *A = 0, *B = 0;
4022     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4023       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4024         return ReplaceInstUsesWith(I, Op1);
4025     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4026       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4027         return ReplaceInstUsesWith(I, Op0);
4028     
4029     if (Op0->hasOneUse() &&
4030         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4031       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4032         I.swapOperands();     // Simplify below
4033         std::swap(Op0, Op1);
4034       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4035         cast<BinaryOperator>(Op0)->swapOperands();
4036         I.swapOperands();     // Simplify below
4037         std::swap(Op0, Op1);
4038       }
4039     }
4040     if (Op1->hasOneUse() &&
4041         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4042       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4043         cast<BinaryOperator>(Op1)->swapOperands();
4044         std::swap(A, B);
4045       }
4046       if (A == Op0) {                                // A&(A^B) -> A & ~B
4047         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4048         InsertNewInstBefore(NotB, I);
4049         return BinaryOperator::createAnd(A, NotB);
4050       }
4051     }
4052   }
4053   
4054   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4055     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4056     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4057       return R;
4058
4059     Value *LHSVal, *RHSVal;
4060     ConstantInt *LHSCst, *RHSCst;
4061     ICmpInst::Predicate LHSCC, RHSCC;
4062     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4063       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4064         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
4065             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4066             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4067             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4068             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4069             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
4070           // Ensure that the larger constant is on the RHS.
4071           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
4072             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4073           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4074           ICmpInst *LHS = cast<ICmpInst>(Op0);
4075           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4076             std::swap(LHS, RHS);
4077             std::swap(LHSCst, RHSCst);
4078             std::swap(LHSCC, RHSCC);
4079           }
4080
4081           // At this point, we know we have have two icmp instructions
4082           // comparing a value against two constants and and'ing the result
4083           // together.  Because of the above check, we know that we only have
4084           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4085           // (from the FoldICmpLogical check above), that the two constants 
4086           // are not equal and that the larger constant is on the RHS
4087           assert(LHSCst != RHSCst && "Compares not folded above?");
4088
4089           switch (LHSCC) {
4090           default: assert(0 && "Unknown integer condition code!");
4091           case ICmpInst::ICMP_EQ:
4092             switch (RHSCC) {
4093             default: assert(0 && "Unknown integer condition code!");
4094             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4095             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4096             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4097               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4099             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4100             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4101               return ReplaceInstUsesWith(I, LHS);
4102             }
4103           case ICmpInst::ICMP_NE:
4104             switch (RHSCC) {
4105             default: assert(0 && "Unknown integer condition code!");
4106             case ICmpInst::ICMP_ULT:
4107               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4108                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4109               break;                        // (X != 13 & X u< 15) -> no change
4110             case ICmpInst::ICMP_SLT:
4111               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4112                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4113               break;                        // (X != 13 & X s< 15) -> no change
4114             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4115             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4116             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4117               return ReplaceInstUsesWith(I, RHS);
4118             case ICmpInst::ICMP_NE:
4119               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4120                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4121                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4122                                                       LHSVal->getName()+".off");
4123                 InsertNewInstBefore(Add, I);
4124                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4125                                     ConstantInt::get(Add->getType(), 1));
4126               }
4127               break;                        // (X != 13 & X != 15) -> no change
4128             }
4129             break;
4130           case ICmpInst::ICMP_ULT:
4131             switch (RHSCC) {
4132             default: assert(0 && "Unknown integer condition code!");
4133             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4134             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4135               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4136             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4137               break;
4138             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4139             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4140               return ReplaceInstUsesWith(I, LHS);
4141             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4142               break;
4143             }
4144             break;
4145           case ICmpInst::ICMP_SLT:
4146             switch (RHSCC) {
4147             default: assert(0 && "Unknown integer condition code!");
4148             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4149             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4150               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4151             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4152               break;
4153             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4154             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4155               return ReplaceInstUsesWith(I, LHS);
4156             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4157               break;
4158             }
4159             break;
4160           case ICmpInst::ICMP_UGT:
4161             switch (RHSCC) {
4162             default: assert(0 && "Unknown integer condition code!");
4163             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4164               return ReplaceInstUsesWith(I, LHS);
4165             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4166               return ReplaceInstUsesWith(I, RHS);
4167             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4168               break;
4169             case ICmpInst::ICMP_NE:
4170               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4171                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4172               break;                        // (X u> 13 & X != 15) -> no change
4173             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4174               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4175                                      true, I);
4176             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4177               break;
4178             }
4179             break;
4180           case ICmpInst::ICMP_SGT:
4181             switch (RHSCC) {
4182             default: assert(0 && "Unknown integer condition code!");
4183             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
4184               return ReplaceInstUsesWith(I, LHS);
4185             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4186               return ReplaceInstUsesWith(I, RHS);
4187             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4188               break;
4189             case ICmpInst::ICMP_NE:
4190               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4191                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4192               break;                        // (X s> 13 & X != 15) -> no change
4193             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4194               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4195                                      true, I);
4196             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4197               break;
4198             }
4199             break;
4200           }
4201         }
4202   }
4203
4204   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4205   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4206     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4207       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4208         const Type *SrcTy = Op0C->getOperand(0)->getType();
4209         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4210             // Only do this if the casts both really cause code to be generated.
4211             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4212                               I.getType(), TD) &&
4213             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4214                               I.getType(), TD)) {
4215           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4216                                                          Op1C->getOperand(0),
4217                                                          I.getName());
4218           InsertNewInstBefore(NewOp, I);
4219           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4220         }
4221       }
4222     
4223   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4224   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4225     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4226       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4227           SI0->getOperand(1) == SI1->getOperand(1) &&
4228           (SI0->hasOneUse() || SI1->hasOneUse())) {
4229         Instruction *NewOp =
4230           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4231                                                         SI1->getOperand(0),
4232                                                         SI0->getName()), I);
4233         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4234                                       SI1->getOperand(1));
4235       }
4236   }
4237
4238   return Changed ? &I : 0;
4239 }
4240
4241 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4242 /// in the result.  If it does, and if the specified byte hasn't been filled in
4243 /// yet, fill it in and return false.
4244 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4245   Instruction *I = dyn_cast<Instruction>(V);
4246   if (I == 0) return true;
4247
4248   // If this is an or instruction, it is an inner node of the bswap.
4249   if (I->getOpcode() == Instruction::Or)
4250     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4251            CollectBSwapParts(I->getOperand(1), ByteValues);
4252   
4253   // If this is a shift by a constant int, and it is "24", then its operand
4254   // defines a byte.  We only handle unsigned types here.
4255   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4256     // Not shifting the entire input by N-1 bytes?
4257     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
4258         8*(ByteValues.size()-1))
4259       return true;
4260     
4261     unsigned DestNo;
4262     if (I->getOpcode() == Instruction::Shl) {
4263       // X << 24 defines the top byte with the lowest of the input bytes.
4264       DestNo = ByteValues.size()-1;
4265     } else {
4266       // X >>u 24 defines the low byte with the highest of the input bytes.
4267       DestNo = 0;
4268     }
4269     
4270     // If the destination byte value is already defined, the values are or'd
4271     // together, which isn't a bswap (unless it's an or of the same bits).
4272     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4273       return true;
4274     ByteValues[DestNo] = I->getOperand(0);
4275     return false;
4276   }
4277   
4278   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4279   // don't have this.
4280   Value *Shift = 0, *ShiftLHS = 0;
4281   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4282   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4283       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4284     return true;
4285   Instruction *SI = cast<Instruction>(Shift);
4286
4287   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4288   if (ShiftAmt->getZExtValue() & 7 ||
4289       ShiftAmt->getZExtValue() > 8*ByteValues.size())
4290     return true;
4291   
4292   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4293   unsigned DestByte;
4294   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4295     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
4296       break;
4297   // Unknown mask for bswap.
4298   if (DestByte == ByteValues.size()) return true;
4299   
4300   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4301   unsigned SrcByte;
4302   if (SI->getOpcode() == Instruction::Shl)
4303     SrcByte = DestByte - ShiftBytes;
4304   else
4305     SrcByte = DestByte + ShiftBytes;
4306   
4307   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4308   if (SrcByte != ByteValues.size()-DestByte-1)
4309     return true;
4310   
4311   // If the destination byte value is already defined, the values are or'd
4312   // together, which isn't a bswap (unless it's an or of the same bits).
4313   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4314     return true;
4315   ByteValues[DestByte] = SI->getOperand(0);
4316   return false;
4317 }
4318
4319 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4320 /// If so, insert the new bswap intrinsic and return it.
4321 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4322   // We cannot bswap one byte.
4323   if (I.getType() == Type::Int8Ty)
4324     return 0;
4325   
4326   /// ByteValues - For each byte of the result, we keep track of which value
4327   /// defines each byte.
4328   SmallVector<Value*, 8> ByteValues;
4329   ByteValues.resize(TD->getTypeSize(I.getType()));
4330     
4331   // Try to find all the pieces corresponding to the bswap.
4332   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4333       CollectBSwapParts(I.getOperand(1), ByteValues))
4334     return 0;
4335   
4336   // Check to see if all of the bytes come from the same value.
4337   Value *V = ByteValues[0];
4338   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4339   
4340   // Check to make sure that all of the bytes come from the same value.
4341   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4342     if (ByteValues[i] != V)
4343       return 0;
4344     
4345   // If they do then *success* we can turn this into a bswap.  Figure out what
4346   // bswap to make it into.
4347   Module *M = I.getParent()->getParent()->getParent();
4348   const char *FnName = 0;
4349   if (I.getType() == Type::Int16Ty)
4350     FnName = "llvm.bswap.i16";
4351   else if (I.getType() == Type::Int32Ty)
4352     FnName = "llvm.bswap.i32";
4353   else if (I.getType() == Type::Int64Ty)
4354     FnName = "llvm.bswap.i64";
4355   else
4356     assert(0 && "Unknown integer type!");
4357   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
4358   return new CallInst(F, V);
4359 }
4360
4361
4362 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4363   bool Changed = SimplifyCommutative(I);
4364   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4365
4366   if (isa<UndefValue>(Op1))
4367     return ReplaceInstUsesWith(I,                         // X | undef -> -1
4368                                ConstantInt::getAllOnesValue(I.getType()));
4369
4370   // or X, X = X
4371   if (Op0 == Op1)
4372     return ReplaceInstUsesWith(I, Op0);
4373
4374   // See if we can simplify any instructions used by the instruction whose sole 
4375   // purpose is to compute bits we don't care about.
4376   uint64_t KnownZero, KnownOne;
4377   if (!isa<VectorType>(I.getType()) &&
4378       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4379                            KnownZero, KnownOne))
4380     return &I;
4381   
4382   // or X, -1 == -1
4383   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4384     ConstantInt *C1 = 0; Value *X = 0;
4385     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4386     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4387       Instruction *Or = BinaryOperator::createOr(X, RHS);
4388       InsertNewInstBefore(Or, I);
4389       Or->takeName(Op0);
4390       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4391     }
4392
4393     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4394     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4395       Instruction *Or = BinaryOperator::createOr(X, RHS);
4396       InsertNewInstBefore(Or, I);
4397       Or->takeName(Op0);
4398       return BinaryOperator::createXor(Or,
4399                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
4400     }
4401
4402     // Try to fold constant and into select arguments.
4403     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4404       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4405         return R;
4406     if (isa<PHINode>(Op0))
4407       if (Instruction *NV = FoldOpIntoPhi(I))
4408         return NV;
4409   }
4410
4411   Value *A = 0, *B = 0;
4412   ConstantInt *C1 = 0, *C2 = 0;
4413
4414   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4415     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4416       return ReplaceInstUsesWith(I, Op1);
4417   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4418     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4419       return ReplaceInstUsesWith(I, Op0);
4420
4421   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4422   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4423   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4424       match(Op1, m_Or(m_Value(), m_Value())) ||
4425       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4426        match(Op1, m_Shift(m_Value(), m_Value())))) {
4427     if (Instruction *BSwap = MatchBSwap(I))
4428       return BSwap;
4429   }
4430   
4431   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4432   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4433       MaskedValueIsZero(Op1, C1->getZExtValue())) {
4434     Instruction *NOr = BinaryOperator::createOr(A, Op1);
4435     InsertNewInstBefore(NOr, I);
4436     NOr->takeName(Op0);
4437     return BinaryOperator::createXor(NOr, C1);
4438   }
4439
4440   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4441   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4442       MaskedValueIsZero(Op0, C1->getZExtValue())) {
4443     Instruction *NOr = BinaryOperator::createOr(A, Op0);
4444     InsertNewInstBefore(NOr, I);
4445     NOr->takeName(Op0);
4446     return BinaryOperator::createXor(NOr, C1);
4447   }
4448
4449   // (A & C1)|(B & C2)
4450   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
4451       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4452
4453     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
4454       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4455
4456
4457     // If we have: ((V + N) & C1) | (V & C2)
4458     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4459     // replace with V+N.
4460     if (C1 == ConstantExpr::getNot(C2)) {
4461       Value *V1 = 0, *V2 = 0;
4462       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
4463           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4464         // Add commutes, try both ways.
4465         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
4466           return ReplaceInstUsesWith(I, A);
4467         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
4468           return ReplaceInstUsesWith(I, A);
4469       }
4470       // Or commutes, try both ways.
4471       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
4472           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4473         // Add commutes, try both ways.
4474         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
4475           return ReplaceInstUsesWith(I, B);
4476         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
4477           return ReplaceInstUsesWith(I, B);
4478       }
4479     }
4480   }
4481   
4482   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4483   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4484     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4485       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4486           SI0->getOperand(1) == SI1->getOperand(1) &&
4487           (SI0->hasOneUse() || SI1->hasOneUse())) {
4488         Instruction *NewOp =
4489         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4490                                                      SI1->getOperand(0),
4491                                                      SI0->getName()), I);
4492         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4493                                       SI1->getOperand(1));
4494       }
4495   }
4496
4497   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4498     if (A == Op1)   // ~A | A == -1
4499       return ReplaceInstUsesWith(I,
4500                                 ConstantInt::getAllOnesValue(I.getType()));
4501   } else {
4502     A = 0;
4503   }
4504   // Note, A is still live here!
4505   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4506     if (Op0 == B)
4507       return ReplaceInstUsesWith(I,
4508                                 ConstantInt::getAllOnesValue(I.getType()));
4509
4510     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4511     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4512       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4513                                               I.getName()+".demorgan"), I);
4514       return BinaryOperator::createNot(And);
4515     }
4516   }
4517
4518   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4519   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4520     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4521       return R;
4522
4523     Value *LHSVal, *RHSVal;
4524     ConstantInt *LHSCst, *RHSCst;
4525     ICmpInst::Predicate LHSCC, RHSCC;
4526     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4527       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4528         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4529             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4530             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4531             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4532             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4533             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
4534           // Ensure that the larger constant is on the RHS.
4535           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
4536             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4537           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4538           ICmpInst *LHS = cast<ICmpInst>(Op0);
4539           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4540             std::swap(LHS, RHS);
4541             std::swap(LHSCst, RHSCst);
4542             std::swap(LHSCC, RHSCC);
4543           }
4544
4545           // At this point, we know we have have two icmp instructions
4546           // comparing a value against two constants and or'ing the result
4547           // together.  Because of the above check, we know that we only have
4548           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4549           // FoldICmpLogical check above), that the two constants are not
4550           // equal.
4551           assert(LHSCst != RHSCst && "Compares not folded above?");
4552
4553           switch (LHSCC) {
4554           default: assert(0 && "Unknown integer condition code!");
4555           case ICmpInst::ICMP_EQ:
4556             switch (RHSCC) {
4557             default: assert(0 && "Unknown integer condition code!");
4558             case ICmpInst::ICMP_EQ:
4559               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4560                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4561                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4562                                                       LHSVal->getName()+".off");
4563                 InsertNewInstBefore(Add, I);
4564                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4565                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4566               }
4567               break;                         // (X == 13 | X == 15) -> no change
4568             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4569             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4570               break;
4571             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4572             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4573             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4574               return ReplaceInstUsesWith(I, RHS);
4575             }
4576             break;
4577           case ICmpInst::ICMP_NE:
4578             switch (RHSCC) {
4579             default: assert(0 && "Unknown integer condition code!");
4580             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4581             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4582             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4583               return ReplaceInstUsesWith(I, LHS);
4584             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4585             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4586             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4587               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4588             }
4589             break;
4590           case ICmpInst::ICMP_ULT:
4591             switch (RHSCC) {
4592             default: assert(0 && "Unknown integer condition code!");
4593             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4594               break;
4595             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4596               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4597                                      false, I);
4598             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4599               break;
4600             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4601             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4602               return ReplaceInstUsesWith(I, RHS);
4603             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4604               break;
4605             }
4606             break;
4607           case ICmpInst::ICMP_SLT:
4608             switch (RHSCC) {
4609             default: assert(0 && "Unknown integer condition code!");
4610             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4611               break;
4612             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4613               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4614                                      false, I);
4615             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4616               break;
4617             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4618             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4619               return ReplaceInstUsesWith(I, RHS);
4620             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4621               break;
4622             }
4623             break;
4624           case ICmpInst::ICMP_UGT:
4625             switch (RHSCC) {
4626             default: assert(0 && "Unknown integer condition code!");
4627             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4628             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4629               return ReplaceInstUsesWith(I, LHS);
4630             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4631               break;
4632             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4633             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4634               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4635             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4636               break;
4637             }
4638             break;
4639           case ICmpInst::ICMP_SGT:
4640             switch (RHSCC) {
4641             default: assert(0 && "Unknown integer condition code!");
4642             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4643             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4644               return ReplaceInstUsesWith(I, LHS);
4645             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4646               break;
4647             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4648             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4649               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4650             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4651               break;
4652             }
4653             break;
4654           }
4655         }
4656   }
4657     
4658   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4659   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4660     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4661       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4662         const Type *SrcTy = Op0C->getOperand(0)->getType();
4663         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4664             // Only do this if the casts both really cause code to be generated.
4665             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4666                               I.getType(), TD) &&
4667             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4668                               I.getType(), TD)) {
4669           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4670                                                         Op1C->getOperand(0),
4671                                                         I.getName());
4672           InsertNewInstBefore(NewOp, I);
4673           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4674         }
4675       }
4676       
4677
4678   return Changed ? &I : 0;
4679 }
4680
4681 // XorSelf - Implements: X ^ X --> 0
4682 struct XorSelf {
4683   Value *RHS;
4684   XorSelf(Value *rhs) : RHS(rhs) {}
4685   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4686   Instruction *apply(BinaryOperator &Xor) const {
4687     return &Xor;
4688   }
4689 };
4690
4691
4692 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4693   bool Changed = SimplifyCommutative(I);
4694   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4695
4696   if (isa<UndefValue>(Op1))
4697     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4698
4699   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4700   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4701     assert(Result == &I && "AssociativeOpt didn't work?");
4702     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4703   }
4704   
4705   // See if we can simplify any instructions used by the instruction whose sole 
4706   // purpose is to compute bits we don't care about.
4707   uint64_t KnownZero, KnownOne;
4708   if (!isa<VectorType>(I.getType()) &&
4709       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4710                            KnownZero, KnownOne))
4711     return &I;
4712
4713   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4714     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4715     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4716       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4717         return new ICmpInst(ICI->getInversePredicate(),
4718                             ICI->getOperand(0), ICI->getOperand(1));
4719
4720     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4721       // ~(c-X) == X-c-1 == X+(-c-1)
4722       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4723         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4724           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4725           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4726                                               ConstantInt::get(I.getType(), 1));
4727           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4728         }
4729
4730       // ~(~X & Y) --> (X | ~Y)
4731       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4732         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4733         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4734           Instruction *NotY =
4735             BinaryOperator::createNot(Op0I->getOperand(1),
4736                                       Op0I->getOperand(1)->getName()+".not");
4737           InsertNewInstBefore(NotY, I);
4738           return BinaryOperator::createOr(Op0NotVal, NotY);
4739         }
4740       }
4741
4742       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4743         if (Op0I->getOpcode() == Instruction::Add) {
4744           // ~(X-c) --> (-c-1)-X
4745           if (RHS->isAllOnesValue()) {
4746             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4747             return BinaryOperator::createSub(
4748                            ConstantExpr::getSub(NegOp0CI,
4749                                              ConstantInt::get(I.getType(), 1)),
4750                                           Op0I->getOperand(0));
4751           }
4752         } else if (Op0I->getOpcode() == Instruction::Or) {
4753           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4754           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4755             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4756             // Anything in both C1 and C2 is known to be zero, remove it from
4757             // NewRHS.
4758             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4759             NewRHS = ConstantExpr::getAnd(NewRHS, 
4760                                           ConstantExpr::getNot(CommonBits));
4761             AddToWorkList(Op0I);
4762             I.setOperand(0, Op0I->getOperand(0));
4763             I.setOperand(1, NewRHS);
4764             return &I;
4765           }
4766         }
4767     }
4768
4769     // Try to fold constant and into select arguments.
4770     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4771       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4772         return R;
4773     if (isa<PHINode>(Op0))
4774       if (Instruction *NV = FoldOpIntoPhi(I))
4775         return NV;
4776   }
4777
4778   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4779     if (X == Op1)
4780       return ReplaceInstUsesWith(I,
4781                                 ConstantInt::getAllOnesValue(I.getType()));
4782
4783   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4784     if (X == Op0)
4785       return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
4786
4787   
4788   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4789   if (Op1I) {
4790     Value *A, *B;
4791     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4792       if (A == Op0) {              // B^(B|A) == (A|B)^B
4793         Op1I->swapOperands();
4794         I.swapOperands();
4795         std::swap(Op0, Op1);
4796       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4797         I.swapOperands();     // Simplified below.
4798         std::swap(Op0, Op1);
4799       }
4800     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4801       if (Op0 == A)                                          // A^(A^B) == B
4802         return ReplaceInstUsesWith(I, B);
4803       else if (Op0 == B)                                     // A^(B^A) == B
4804         return ReplaceInstUsesWith(I, A);
4805     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4806       if (A == Op0)                                        // A^(A&B) -> A^(B&A)
4807         Op1I->swapOperands();
4808       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4809         I.swapOperands();     // Simplified below.
4810         std::swap(Op0, Op1);
4811       }
4812     }
4813   }
4814   
4815   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4816   if (Op0I) {
4817     Value *A, *B;
4818     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4819       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4820         std::swap(A, B);
4821       if (B == Op1) {                                // (A|B)^B == A & ~B
4822         Instruction *NotB =
4823           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4824         return BinaryOperator::createAnd(A, NotB);
4825       }
4826     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4827       if (Op1 == A)                                          // (A^B)^A == B
4828         return ReplaceInstUsesWith(I, B);
4829       else if (Op1 == B)                                     // (B^A)^A == B
4830         return ReplaceInstUsesWith(I, A);
4831     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4832       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4833         std::swap(A, B);
4834       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4835           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4836         Instruction *N =
4837           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4838         return BinaryOperator::createAnd(N, Op1);
4839       }
4840     }
4841   }
4842   
4843   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4844   if (Op0I && Op1I && Op0I->isShift() && 
4845       Op0I->getOpcode() == Op1I->getOpcode() && 
4846       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4847       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4848     Instruction *NewOp =
4849       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4850                                                     Op1I->getOperand(0),
4851                                                     Op0I->getName()), I);
4852     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4853                                   Op1I->getOperand(1));
4854   }
4855     
4856   if (Op0I && Op1I) {
4857     Value *A, *B, *C, *D;
4858     // (A & B)^(A | B) -> A ^ B
4859     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4860         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4861       if ((A == C && B == D) || (A == D && B == C)) 
4862         return BinaryOperator::createXor(A, B);
4863     }
4864     // (A | B)^(A & B) -> A ^ B
4865     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4866         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4867       if ((A == C && B == D) || (A == D && B == C)) 
4868         return BinaryOperator::createXor(A, B);
4869     }
4870     
4871     // (A & B)^(C & D)
4872     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4873         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4874         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4875       // (X & Y)^(X & Y) -> (Y^Z) & X
4876       Value *X = 0, *Y = 0, *Z = 0;
4877       if (A == C)
4878         X = A, Y = B, Z = D;
4879       else if (A == D)
4880         X = A, Y = B, Z = C;
4881       else if (B == C)
4882         X = B, Y = A, Z = D;
4883       else if (B == D)
4884         X = B, Y = A, Z = C;
4885       
4886       if (X) {
4887         Instruction *NewOp =
4888         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4889         return BinaryOperator::createAnd(NewOp, X);
4890       }
4891     }
4892   }
4893     
4894   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4895   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4896     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4897       return R;
4898
4899   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4900   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4901     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4902       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4903         const Type *SrcTy = Op0C->getOperand(0)->getType();
4904         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4905             // Only do this if the casts both really cause code to be generated.
4906             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4907                               I.getType(), TD) &&
4908             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4909                               I.getType(), TD)) {
4910           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4911                                                          Op1C->getOperand(0),
4912                                                          I.getName());
4913           InsertNewInstBefore(NewOp, I);
4914           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4915         }
4916       }
4917
4918   return Changed ? &I : 0;
4919 }
4920
4921 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4922 /// overflowed for this type.
4923 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4924                             ConstantInt *In2, bool IsSigned = false) {
4925   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4926
4927   if (IsSigned)
4928     if (In2->getValue().isNegative())
4929       return Result->getValue().sgt(In1->getValue());
4930     else
4931       return Result->getValue().slt(In1->getValue());
4932   else
4933     return Result->getValue().ult(In1->getValue());
4934 }
4935
4936 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4937 /// code necessary to compute the offset from the base pointer (without adding
4938 /// in the base pointer).  Return the result as a signed integer of intptr size.
4939 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4940   TargetData &TD = IC.getTargetData();
4941   gep_type_iterator GTI = gep_type_begin(GEP);
4942   const Type *IntPtrTy = TD.getIntPtrType();
4943   Value *Result = Constant::getNullValue(IntPtrTy);
4944
4945   // Build a mask for high order bits.
4946   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4947
4948   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4949     Value *Op = GEP->getOperand(i);
4950     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4951     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4952     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4953       if (!OpC->isNullValue()) {
4954         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4955         Scale = ConstantExpr::getMul(OpC, Scale);
4956         if (Constant *RC = dyn_cast<Constant>(Result))
4957           Result = ConstantExpr::getAdd(RC, Scale);
4958         else {
4959           // Emit an add instruction.
4960           Result = IC.InsertNewInstBefore(
4961              BinaryOperator::createAdd(Result, Scale,
4962                                        GEP->getName()+".offs"), I);
4963         }
4964       }
4965     } else {
4966       // Convert to correct type.
4967       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4968                                                Op->getName()+".c"), I);
4969       if (Size != 1)
4970         // We'll let instcombine(mul) convert this to a shl if possible.
4971         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4972                                                     GEP->getName()+".idx"), I);
4973
4974       // Emit an add instruction.
4975       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4976                                                     GEP->getName()+".offs"), I);
4977     }
4978   }
4979   return Result;
4980 }
4981
4982 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4983 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4984 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4985                                        ICmpInst::Predicate Cond,
4986                                        Instruction &I) {
4987   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4988
4989   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4990     if (isa<PointerType>(CI->getOperand(0)->getType()))
4991       RHS = CI->getOperand(0);
4992
4993   Value *PtrBase = GEPLHS->getOperand(0);
4994   if (PtrBase == RHS) {
4995     // As an optimization, we don't actually have to compute the actual value of
4996     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4997     // each index is zero or not.
4998     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4999       Instruction *InVal = 0;
5000       gep_type_iterator GTI = gep_type_begin(GEPLHS);
5001       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
5002         bool EmitIt = true;
5003         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
5004           if (isa<UndefValue>(C))  // undef index -> undef.
5005             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5006           if (C->isNullValue())
5007             EmitIt = false;
5008           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
5009             EmitIt = false;  // This is indexing into a zero sized array?
5010           } else if (isa<ConstantInt>(C))
5011             return ReplaceInstUsesWith(I, // No comparison is needed here.
5012                                  ConstantInt::get(Type::Int1Ty, 
5013                                                   Cond == ICmpInst::ICMP_NE));
5014         }
5015
5016         if (EmitIt) {
5017           Instruction *Comp =
5018             new ICmpInst(Cond, GEPLHS->getOperand(i),
5019                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
5020           if (InVal == 0)
5021             InVal = Comp;
5022           else {
5023             InVal = InsertNewInstBefore(InVal, I);
5024             InsertNewInstBefore(Comp, I);
5025             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
5026               InVal = BinaryOperator::createOr(InVal, Comp);
5027             else                              // True if all are equal
5028               InVal = BinaryOperator::createAnd(InVal, Comp);
5029           }
5030         }
5031       }
5032
5033       if (InVal)
5034         return InVal;
5035       else
5036         // No comparison is needed here, all indexes = 0
5037         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5038                                                 Cond == ICmpInst::ICMP_EQ));
5039     }
5040
5041     // Only lower this if the icmp is the only user of the GEP or if we expect
5042     // the result to fold to a constant!
5043     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5044       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5045       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
5046       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5047                           Constant::getNullValue(Offset->getType()));
5048     }
5049   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5050     // If the base pointers are different, but the indices are the same, just
5051     // compare the base pointer.
5052     if (PtrBase != GEPRHS->getOperand(0)) {
5053       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5054       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5055                         GEPRHS->getOperand(0)->getType();
5056       if (IndicesTheSame)
5057         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5058           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5059             IndicesTheSame = false;
5060             break;
5061           }
5062
5063       // If all indices are the same, just compare the base pointers.
5064       if (IndicesTheSame)
5065         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5066                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5067
5068       // Otherwise, the base pointers are different and the indices are
5069       // different, bail out.
5070       return 0;
5071     }
5072
5073     // If one of the GEPs has all zero indices, recurse.
5074     bool AllZeros = true;
5075     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5076       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5077           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5078         AllZeros = false;
5079         break;
5080       }
5081     if (AllZeros)
5082       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5083                           ICmpInst::getSwappedPredicate(Cond), I);
5084
5085     // If the other GEP has all zero indices, recurse.
5086     AllZeros = true;
5087     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5088       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5089           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5090         AllZeros = false;
5091         break;
5092       }
5093     if (AllZeros)
5094       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5095
5096     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5097       // If the GEPs only differ by one index, compare it.
5098       unsigned NumDifferences = 0;  // Keep track of # differences.
5099       unsigned DiffOperand = 0;     // The operand that differs.
5100       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5101         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5102           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5103                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5104             // Irreconcilable differences.
5105             NumDifferences = 2;
5106             break;
5107           } else {
5108             if (NumDifferences++) break;
5109             DiffOperand = i;
5110           }
5111         }
5112
5113       if (NumDifferences == 0)   // SAME GEP?
5114         return ReplaceInstUsesWith(I, // No comparison is needed here.
5115                                    ConstantInt::get(Type::Int1Ty, 
5116                                                     Cond == ICmpInst::ICMP_EQ));
5117       else if (NumDifferences == 1) {
5118         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5119         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5120         // Make sure we do a signed comparison here.
5121         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5122       }
5123     }
5124
5125     // Only lower this if the icmp is the only user of the GEP or if we expect
5126     // the result to fold to a constant!
5127     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5128         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5129       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5130       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5131       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5132       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5133     }
5134   }
5135   return 0;
5136 }
5137
5138 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5139   bool Changed = SimplifyCompare(I);
5140   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5141
5142   // Fold trivial predicates.
5143   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5144     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5145   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5146     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5147   
5148   // Simplify 'fcmp pred X, X'
5149   if (Op0 == Op1) {
5150     switch (I.getPredicate()) {
5151     default: assert(0 && "Unknown predicate!");
5152     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5153     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5154     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5155       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5156     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5157     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5158     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5159       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5160       
5161     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5162     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5163     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5164     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5165       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5166       I.setPredicate(FCmpInst::FCMP_UNO);
5167       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5168       return &I;
5169       
5170     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5171     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5172     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5173     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5174       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5175       I.setPredicate(FCmpInst::FCMP_ORD);
5176       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5177       return &I;
5178     }
5179   }
5180     
5181   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5182     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5183
5184   // Handle fcmp with constant RHS
5185   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5186     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5187       switch (LHSI->getOpcode()) {
5188       case Instruction::PHI:
5189         if (Instruction *NV = FoldOpIntoPhi(I))
5190           return NV;
5191         break;
5192       case Instruction::Select:
5193         // If either operand of the select is a constant, we can fold the
5194         // comparison into the select arms, which will cause one to be
5195         // constant folded and the select turned into a bitwise or.
5196         Value *Op1 = 0, *Op2 = 0;
5197         if (LHSI->hasOneUse()) {
5198           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5199             // Fold the known value into the constant operand.
5200             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5201             // Insert a new FCmp of the other select operand.
5202             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5203                                                       LHSI->getOperand(2), RHSC,
5204                                                       I.getName()), I);
5205           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5206             // Fold the known value into the constant operand.
5207             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5208             // Insert a new FCmp of the other select operand.
5209             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5210                                                       LHSI->getOperand(1), RHSC,
5211                                                       I.getName()), I);
5212           }
5213         }
5214
5215         if (Op1)
5216           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5217         break;
5218       }
5219   }
5220
5221   return Changed ? &I : 0;
5222 }
5223
5224 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5225   bool Changed = SimplifyCompare(I);
5226   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5227   const Type *Ty = Op0->getType();
5228
5229   // icmp X, X
5230   if (Op0 == Op1)
5231     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5232                                                    isTrueWhenEqual(I)));
5233
5234   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5235     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5236
5237   // icmp of GlobalValues can never equal each other as long as they aren't
5238   // external weak linkage type.
5239   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5240     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5241       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
5242         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5243                                                        !isTrueWhenEqual(I)));
5244
5245   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5246   // addresses never equal each other!  We already know that Op0 != Op1.
5247   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5248        isa<ConstantPointerNull>(Op0)) &&
5249       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5250        isa<ConstantPointerNull>(Op1)))
5251     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5252                                                    !isTrueWhenEqual(I)));
5253
5254   // icmp's with boolean values can always be turned into bitwise operations
5255   if (Ty == Type::Int1Ty) {
5256     switch (I.getPredicate()) {
5257     default: assert(0 && "Invalid icmp instruction!");
5258     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5259       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
5260       InsertNewInstBefore(Xor, I);
5261       return BinaryOperator::createNot(Xor);
5262     }
5263     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5264       return BinaryOperator::createXor(Op0, Op1);
5265
5266     case ICmpInst::ICMP_UGT:
5267     case ICmpInst::ICMP_SGT:
5268       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5269       // FALL THROUGH
5270     case ICmpInst::ICMP_ULT:
5271     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5272       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5273       InsertNewInstBefore(Not, I);
5274       return BinaryOperator::createAnd(Not, Op1);
5275     }
5276     case ICmpInst::ICMP_UGE:
5277     case ICmpInst::ICMP_SGE:
5278       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5279       // FALL THROUGH
5280     case ICmpInst::ICMP_ULE:
5281     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5282       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5283       InsertNewInstBefore(Not, I);
5284       return BinaryOperator::createOr(Not, Op1);
5285     }
5286     }
5287   }
5288
5289   // See if we are doing a comparison between a constant and an instruction that
5290   // can be folded into the comparison.
5291   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5292     switch (I.getPredicate()) {
5293     default: break;
5294     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5295       if (CI->isMinValue(false))
5296         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5297       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5298         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5299       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5300         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5301       break;
5302
5303     case ICmpInst::ICMP_SLT:
5304       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5305         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5306       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5307         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5308       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5309         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5310       break;
5311
5312     case ICmpInst::ICMP_UGT:
5313       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5314         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5315       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5316         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5317       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5318         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5319       break;
5320
5321     case ICmpInst::ICMP_SGT:
5322       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5323         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5324       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5325         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5326       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5327         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5328       break;
5329
5330     case ICmpInst::ICMP_ULE:
5331       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5332         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5333       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5334         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5335       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5336         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5337       break;
5338
5339     case ICmpInst::ICMP_SLE:
5340       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5341         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5342       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5343         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5344       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5345         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5346       break;
5347
5348     case ICmpInst::ICMP_UGE:
5349       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5350         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5351       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5352         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5353       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5354         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5355       break;
5356
5357     case ICmpInst::ICMP_SGE:
5358       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5359         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5360       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5361         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5362       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5363         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5364       break;
5365     }
5366
5367     // If we still have a icmp le or icmp ge instruction, turn it into the
5368     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5369     // already been handled above, this requires little checking.
5370     //
5371     if (I.getPredicate() == ICmpInst::ICMP_ULE)
5372       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5373     if (I.getPredicate() == ICmpInst::ICMP_SLE)
5374       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5375     if (I.getPredicate() == ICmpInst::ICMP_UGE)
5376       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5377     if (I.getPredicate() == ICmpInst::ICMP_SGE)
5378       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5379     
5380     // See if we can fold the comparison based on bits known to be zero or one
5381     // in the input.
5382     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5383     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5384     if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
5385                              KnownZero, KnownOne, 0))
5386       return &I;
5387         
5388     // Given the known and unknown bits, compute a range that the LHS could be
5389     // in.
5390     if ((KnownOne | KnownZero) != 0) {
5391       // Compute the Min, Max and RHS values based on the known bits. For the
5392       // EQ and NE we use unsigned values.
5393       APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
5394       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5395         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5396                                                Max);
5397       } else {
5398         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5399                                                  Max);
5400       }
5401       switch (I.getPredicate()) {  // LE/GE have been folded already.
5402       default: assert(0 && "Unknown icmp opcode!");
5403       case ICmpInst::ICMP_EQ:
5404         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5405           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5406         break;
5407       case ICmpInst::ICMP_NE:
5408         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5409           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5410         break;
5411       case ICmpInst::ICMP_ULT:
5412         if (Max.ult(RHSVal))
5413           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5414         if (Min.ugt(RHSVal))
5415           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5416         break;
5417       case ICmpInst::ICMP_UGT:
5418         if (Min.ugt(RHSVal))
5419           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5420         if (Max.ult(RHSVal))
5421           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5422         break;
5423       case ICmpInst::ICMP_SLT:
5424         if (Max.slt(RHSVal))
5425           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5426         if (Min.sgt(RHSVal))
5427           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5428         break;
5429       case ICmpInst::ICMP_SGT: 
5430         if (Min.sgt(RHSVal))
5431           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5432         if (Max.slt(RHSVal))
5433           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5434         break;
5435       }
5436     }
5437           
5438     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5439     // instruction, see if that instruction also has constants so that the 
5440     // instruction can be folded into the icmp 
5441     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5442       switch (LHSI->getOpcode()) {
5443       case Instruction::And:
5444         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5445             LHSI->getOperand(0)->hasOneUse()) {
5446           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5447
5448           // If the LHS is an AND of a truncating cast, we can widen the
5449           // and/compare to be the input width without changing the value
5450           // produced, eliminating a cast.
5451           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5452             // We can do this transformation if either the AND constant does not
5453             // have its sign bit set or if it is an equality comparison. 
5454             // Extending a relational comparison when we're checking the sign
5455             // bit would not work.
5456             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
5457                 (I.isEquality() || AndCST->getValue().isPositive() && 
5458                  CI->getValue().isPositive())) {
5459               ConstantInt *NewCST;
5460               ConstantInt *NewCI;
5461               APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
5462               uint32_t BitWidth = cast<IntegerType>(
5463                 Cast->getOperand(0)->getType())->getBitWidth();
5464               NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
5465               NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
5466               Instruction *NewAnd = 
5467                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
5468                                           LHSI->getName());
5469               InsertNewInstBefore(NewAnd, I);
5470               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
5471             }
5472           }
5473           
5474           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5475           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5476           // happens a LOT in code produced by the C front-end, for bitfield
5477           // access.
5478           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5479           if (Shift && !Shift->isShift())
5480             Shift = 0;
5481
5482           ConstantInt *ShAmt;
5483           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5484           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5485           const Type *AndTy = AndCST->getType();          // Type of the and.
5486
5487           // We can fold this as long as we can't shift unknown bits
5488           // into the mask.  This can only happen with signed shift
5489           // rights, as they sign-extend.
5490           if (ShAmt) {
5491             bool CanFold = Shift->isLogicalShift();
5492             if (!CanFold) {
5493               // To test for the bad case of the signed shr, see if any
5494               // of the bits shifted in could be tested after the mask.
5495               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
5496               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5497
5498               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
5499               Constant *ShVal =
5500                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
5501                                      OShAmt);
5502               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5503                 CanFold = true;
5504             }
5505
5506             if (CanFold) {
5507               Constant *NewCst;
5508               if (Shift->getOpcode() == Instruction::Shl)
5509                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
5510               else
5511                 NewCst = ConstantExpr::getShl(CI, ShAmt);
5512
5513               // Check to see if we are shifting out any of the bits being
5514               // compared.
5515               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5516                 // If we shifted bits out, the fold is not going to work out.
5517                 // As a special case, check to see if this means that the
5518                 // result is always true or false now.
5519                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5520                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5521                 if (I.getPredicate() == ICmpInst::ICMP_NE)
5522                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5523               } else {
5524                 I.setOperand(1, NewCst);
5525                 Constant *NewAndCST;
5526                 if (Shift->getOpcode() == Instruction::Shl)
5527                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5528                 else
5529                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5530                 LHSI->setOperand(1, NewAndCST);
5531                 LHSI->setOperand(0, Shift->getOperand(0));
5532                 AddToWorkList(Shift); // Shift is dead.
5533                 AddUsesToWorkList(I);
5534                 return &I;
5535               }
5536             }
5537           }
5538           
5539           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5540           // preferable because it allows the C<<Y expression to be hoisted out
5541           // of a loop if Y is invariant and X is not.
5542           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
5543               I.isEquality() && !Shift->isArithmeticShift() &&
5544               isa<Instruction>(Shift->getOperand(0))) {
5545             // Compute C << Y.
5546             Value *NS;
5547             if (Shift->getOpcode() == Instruction::LShr) {
5548               NS = BinaryOperator::createShl(AndCST, 
5549                                           Shift->getOperand(1), "tmp");
5550             } else {
5551               // Insert a logical shift.
5552               NS = BinaryOperator::createLShr(AndCST,
5553                                           Shift->getOperand(1), "tmp");
5554             }
5555             InsertNewInstBefore(cast<Instruction>(NS), I);
5556
5557             // Compute X & (C << Y).
5558             Instruction *NewAnd = BinaryOperator::createAnd(
5559                 Shift->getOperand(0), NS, LHSI->getName());
5560             InsertNewInstBefore(NewAnd, I);
5561             
5562             I.setOperand(0, NewAnd);
5563             return &I;
5564           }
5565         }
5566         break;
5567
5568       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
5569         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5570           if (I.isEquality()) {
5571             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5572
5573             // Check that the shift amount is in range.  If not, don't perform
5574             // undefined shifts.  When the shift is visited it will be
5575             // simplified.
5576             if (ShAmt->getZExtValue() >= TypeBits)
5577               break;
5578
5579             // If we are comparing against bits always shifted out, the
5580             // comparison cannot succeed.
5581             Constant *Comp =
5582               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
5583             if (Comp != CI) {// Comparing against a bit that we know is zero.
5584               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5585               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5586               return ReplaceInstUsesWith(I, Cst);
5587             }
5588
5589             if (LHSI->hasOneUse()) {
5590               // Otherwise strength reduce the shift into an and.
5591               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5592               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
5593               Constant *Mask = ConstantInt::get(CI->getType(), Val);
5594
5595               Instruction *AndI =
5596                 BinaryOperator::createAnd(LHSI->getOperand(0),
5597                                           Mask, LHSI->getName()+".mask");
5598               Value *And = InsertNewInstBefore(AndI, I);
5599               return new ICmpInst(I.getPredicate(), And,
5600                                      ConstantExpr::getLShr(CI, ShAmt));
5601             }
5602           }
5603         }
5604         break;
5605
5606       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5607       case Instruction::AShr:
5608         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5609           if (I.isEquality()) {
5610             // Check that the shift amount is in range.  If not, don't perform
5611             // undefined shifts.  When the shift is visited it will be
5612             // simplified.
5613             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5614             if (ShAmt->getZExtValue() >= TypeBits)
5615               break;
5616
5617             // If we are comparing against bits always shifted out, the
5618             // comparison cannot succeed.
5619             Constant *Comp;
5620             if (LHSI->getOpcode() == Instruction::LShr) 
5621               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
5622                                            ShAmt);
5623             else
5624               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
5625                                            ShAmt);
5626
5627             if (Comp != CI) {// Comparing against a bit that we know is zero.
5628               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5629               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5630               return ReplaceInstUsesWith(I, Cst);
5631             }
5632
5633             if (LHSI->hasOneUse() || CI->isNullValue()) {
5634               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5635
5636               // Otherwise strength reduce the shift into an and.
5637               APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
5638               Constant *Mask = ConstantInt::get(Val);
5639
5640               Instruction *AndI =
5641                 BinaryOperator::createAnd(LHSI->getOperand(0),
5642                                           Mask, LHSI->getName()+".mask");
5643               Value *And = InsertNewInstBefore(AndI, I);
5644               return new ICmpInst(I.getPredicate(), And,
5645                                      ConstantExpr::getShl(CI, ShAmt));
5646             }
5647           }
5648         }
5649         break;
5650
5651       case Instruction::SDiv:
5652       case Instruction::UDiv:
5653         // Fold: icmp pred ([us]div X, C1), C2 -> range test
5654         // Fold this div into the comparison, producing a range check. 
5655         // Determine, based on the divide type, what the range is being 
5656         // checked.  If there is an overflow on the low or high side, remember 
5657         // it, otherwise compute the range [low, hi) bounding the new value.
5658         // See: InsertRangeTest above for the kinds of replacements possible.
5659         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5660           // FIXME: If the operand types don't match the type of the divide 
5661           // then don't attempt this transform. The code below doesn't have the
5662           // logic to deal with a signed divide and an unsigned compare (and
5663           // vice versa). This is because (x /s C1) <s C2  produces different 
5664           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5665           // (x /u C1) <u C2.  Simply casting the operands and result won't 
5666           // work. :(  The if statement below tests that condition and bails 
5667           // if it finds it. 
5668           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5669           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
5670             break;
5671           if (DivRHS->isZero())
5672             break; // Don't hack on div by zero
5673
5674           // Initialize the variables that will indicate the nature of the
5675           // range check.
5676           bool LoOverflow = false, HiOverflow = false;
5677           ConstantInt *LoBound = 0, *HiBound = 0;
5678
5679           // Compute Prod = CI * DivRHS. We are essentially solving an equation
5680           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5681           // C2 (CI). By solving for X we can turn this into a range check 
5682           // instead of computing a divide. 
5683           ConstantInt *Prod = 
5684             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
5685
5686           // Determine if the product overflows by seeing if the product is
5687           // not equal to the divide. Make sure we do the same kind of divide
5688           // as in the LHS instruction that we're folding. 
5689           bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5690                                      ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5691
5692           // Get the ICmp opcode
5693           ICmpInst::Predicate predicate = I.getPredicate();
5694
5695           if (!DivIsSigned) {  // udiv
5696             LoBound = Prod;
5697             LoOverflow = ProdOV;
5698             HiOverflow = ProdOV || 
5699                          AddWithOverflow(HiBound, LoBound, DivRHS, false);
5700           } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5701             if (CI->isNullValue()) {       // (X / pos) op 0
5702               // Can't overflow.
5703               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5704               HiBound = DivRHS;
5705             } else if (CI->getValue().isPositive()) {   // (X / pos) op pos
5706               LoBound = Prod;
5707               LoOverflow = ProdOV;
5708               HiOverflow = ProdOV || 
5709                            AddWithOverflow(HiBound, Prod, DivRHS, true);
5710             } else {                       // (X / pos) op neg
5711               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5712               LoOverflow = AddWithOverflow(LoBound, Prod,
5713                                            cast<ConstantInt>(DivRHSH), true);
5714               HiBound = AddOne(Prod);
5715               HiOverflow = ProdOV;
5716             }
5717           } else {                         // Divisor is < 0.
5718             if (CI->isNullValue()) {       // (X / neg) op 0
5719               LoBound = AddOne(DivRHS);
5720               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5721               if (HiBound == DivRHS)
5722                 LoBound = 0;               // - INTMIN = INTMIN
5723             } else if (CI->getValue().isPositive()) {   // (X / neg) op pos
5724               HiOverflow = LoOverflow = ProdOV;
5725               if (!LoOverflow)
5726                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5727                                              true);
5728               HiBound = AddOne(Prod);
5729             } else {                       // (X / neg) op neg
5730               LoBound = Prod;
5731               LoOverflow = HiOverflow = ProdOV;
5732               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5733             }
5734
5735             // Dividing by a negate swaps the condition.
5736             predicate = ICmpInst::getSwappedPredicate(predicate);
5737           }
5738
5739           if (LoBound) {
5740             Value *X = LHSI->getOperand(0);
5741             switch (predicate) {
5742             default: assert(0 && "Unhandled icmp opcode!");
5743             case ICmpInst::ICMP_EQ:
5744               if (LoOverflow && HiOverflow)
5745                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5746               else if (HiOverflow)
5747                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
5748                                     ICmpInst::ICMP_UGE, X, LoBound);
5749               else if (LoOverflow)
5750                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5751                                     ICmpInst::ICMP_ULT, X, HiBound);
5752               else
5753                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5754                                        true, I);
5755             case ICmpInst::ICMP_NE:
5756               if (LoOverflow && HiOverflow)
5757                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5758               else if (HiOverflow)
5759                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
5760                                     ICmpInst::ICMP_ULT, X, LoBound);
5761               else if (LoOverflow)
5762                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5763                                     ICmpInst::ICMP_UGE, X, HiBound);
5764               else
5765                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5766                                        false, I);
5767             case ICmpInst::ICMP_ULT:
5768             case ICmpInst::ICMP_SLT:
5769               if (LoOverflow)
5770                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5771               return new ICmpInst(predicate, X, LoBound);
5772             case ICmpInst::ICMP_UGT:
5773             case ICmpInst::ICMP_SGT:
5774               if (HiOverflow)
5775                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5776               if (predicate == ICmpInst::ICMP_UGT)
5777                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5778               else
5779                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5780             }
5781           }
5782         }
5783         break;
5784       }
5785
5786     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5787     if (I.isEquality()) {
5788       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5789
5790       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5791       // the second operand is a constant, simplify a bit.
5792       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5793         switch (BO->getOpcode()) {
5794         case Instruction::SRem:
5795           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5796           if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
5797               BO->hasOneUse()) {
5798             APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5799             if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5800               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5801                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
5802               return new ICmpInst(I.getPredicate(), NewRem, 
5803                                   Constant::getNullValue(BO->getType()));
5804             }
5805           }
5806           break;
5807         case Instruction::Add:
5808           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5809           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5810             if (BO->hasOneUse())
5811               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5812                                   ConstantExpr::getSub(CI, BOp1C));
5813           } else if (CI->isNullValue()) {
5814             // Replace ((add A, B) != 0) with (A != -B) if A or B is
5815             // efficiently invertible, or if the add has just this one use.
5816             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5817
5818             if (Value *NegVal = dyn_castNegVal(BOp1))
5819               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
5820             else if (Value *NegVal = dyn_castNegVal(BOp0))
5821               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
5822             else if (BO->hasOneUse()) {
5823               Instruction *Neg = BinaryOperator::createNeg(BOp1);
5824               InsertNewInstBefore(Neg, I);
5825               Neg->takeName(BO);
5826               return new ICmpInst(I.getPredicate(), BOp0, Neg);
5827             }
5828           }
5829           break;
5830         case Instruction::Xor:
5831           // For the xor case, we can xor two constants together, eliminating
5832           // the explicit xor.
5833           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5834             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
5835                                 ConstantExpr::getXor(CI, BOC));
5836
5837           // FALLTHROUGH
5838         case Instruction::Sub:
5839           // Replace (([sub|xor] A, B) != 0) with (A != B)
5840           if (CI->isZero())
5841             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5842                                 BO->getOperand(1));
5843           break;
5844
5845         case Instruction::Or:
5846           // If bits are being or'd in that are not present in the constant we
5847           // are comparing against, then the comparison could never succeed!
5848           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5849             Constant *NotCI = ConstantExpr::getNot(CI);
5850             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5851               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5852                                                              isICMP_NE));
5853           }
5854           break;
5855
5856         case Instruction::And:
5857           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5858             // If bits are being compared against that are and'd out, then the
5859             // comparison can never succeed!
5860             if (!ConstantExpr::getAnd(CI,
5861                                       ConstantExpr::getNot(BOC))->isNullValue())
5862               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5863                                                              isICMP_NE));
5864
5865             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5866             if (CI == BOC && isOneBitSet(CI))
5867               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5868                                   ICmpInst::ICMP_NE, Op0,
5869                                   Constant::getNullValue(CI->getType()));
5870
5871             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5872             if (isSignBit(BOC)) {
5873               Value *X = BO->getOperand(0);
5874               Constant *Zero = Constant::getNullValue(X->getType());
5875               ICmpInst::Predicate pred = isICMP_NE ? 
5876                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5877               return new ICmpInst(pred, X, Zero);
5878             }
5879
5880             // ((X & ~7) == 0) --> X < 8
5881             if (CI->isNullValue() && isHighOnes(BOC)) {
5882               Value *X = BO->getOperand(0);
5883               Constant *NegX = ConstantExpr::getNeg(BOC);
5884               ICmpInst::Predicate pred = isICMP_NE ? 
5885                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5886               return new ICmpInst(pred, X, NegX);
5887             }
5888
5889           }
5890         default: break;
5891         }
5892       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5893         // Handle set{eq|ne} <intrinsic>, intcst.
5894         switch (II->getIntrinsicID()) {
5895         default: break;
5896         case Intrinsic::bswap_i16: 
5897           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5898           AddToWorkList(II);  // Dead?
5899           I.setOperand(0, II->getOperand(1));
5900           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5901                                            ByteSwap_16(CI->getZExtValue())));
5902           return &I;
5903         case Intrinsic::bswap_i32:   
5904           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5905           AddToWorkList(II);  // Dead?
5906           I.setOperand(0, II->getOperand(1));
5907           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5908                                            ByteSwap_32(CI->getZExtValue())));
5909           return &I;
5910         case Intrinsic::bswap_i64:   
5911           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5912           AddToWorkList(II);  // Dead?
5913           I.setOperand(0, II->getOperand(1));
5914           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5915                                            ByteSwap_64(CI->getZExtValue())));
5916           return &I;
5917         }
5918       }
5919     } else {  // Not a ICMP_EQ/ICMP_NE
5920       // If the LHS is a cast from an integral value of the same size, then 
5921       // since we know the RHS is a constant, try to simlify.
5922       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5923         Value *CastOp = Cast->getOperand(0);
5924         const Type *SrcTy = CastOp->getType();
5925         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5926         if (SrcTy->isInteger() && 
5927             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5928           // If this is an unsigned comparison, try to make the comparison use
5929           // smaller constant values.
5930           switch (I.getPredicate()) {
5931             default: break;
5932             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5933               ConstantInt *CUI = cast<ConstantInt>(CI);
5934               if (CUI->getValue() == APInt::getSignBit(SrcTySize))
5935                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5936                   ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5937               break;
5938             }
5939             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5940               ConstantInt *CUI = cast<ConstantInt>(CI);
5941               if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
5942                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5943                                     Constant::getNullValue(SrcTy));
5944               break;
5945             }
5946           }
5947
5948         }
5949       }
5950     }
5951   }
5952
5953   // Handle icmp with constant RHS
5954   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5955     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5956       switch (LHSI->getOpcode()) {
5957       case Instruction::GetElementPtr:
5958         if (RHSC->isNullValue()) {
5959           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5960           bool isAllZeros = true;
5961           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5962             if (!isa<Constant>(LHSI->getOperand(i)) ||
5963                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5964               isAllZeros = false;
5965               break;
5966             }
5967           if (isAllZeros)
5968             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5969                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5970         }
5971         break;
5972
5973       case Instruction::PHI:
5974         if (Instruction *NV = FoldOpIntoPhi(I))
5975           return NV;
5976         break;
5977       case Instruction::Select:
5978         // If either operand of the select is a constant, we can fold the
5979         // comparison into the select arms, which will cause one to be
5980         // constant folded and the select turned into a bitwise or.
5981         Value *Op1 = 0, *Op2 = 0;
5982         if (LHSI->hasOneUse()) {
5983           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5984             // Fold the known value into the constant operand.
5985             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5986             // Insert a new ICmp of the other select operand.
5987             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5988                                                    LHSI->getOperand(2), RHSC,
5989                                                    I.getName()), I);
5990           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5991             // Fold the known value into the constant operand.
5992             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5993             // Insert a new ICmp of the other select operand.
5994             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5995                                                    LHSI->getOperand(1), RHSC,
5996                                                    I.getName()), I);
5997           }
5998         }
5999
6000         if (Op1)
6001           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
6002         break;
6003       }
6004   }
6005
6006   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6007   if (User *GEP = dyn_castGetElementPtr(Op0))
6008     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6009       return NI;
6010   if (User *GEP = dyn_castGetElementPtr(Op1))
6011     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6012                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6013       return NI;
6014
6015   // Test to see if the operands of the icmp are casted versions of other
6016   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6017   // now.
6018   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6019     if (isa<PointerType>(Op0->getType()) && 
6020         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6021       // We keep moving the cast from the left operand over to the right
6022       // operand, where it can often be eliminated completely.
6023       Op0 = CI->getOperand(0);
6024
6025       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6026       // so eliminate it as well.
6027       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6028         Op1 = CI2->getOperand(0);
6029
6030       // If Op1 is a constant, we can fold the cast into the constant.
6031       if (Op0->getType() != Op1->getType())
6032         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6033           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6034         } else {
6035           // Otherwise, cast the RHS right before the icmp
6036           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
6037         }
6038       return new ICmpInst(I.getPredicate(), Op0, Op1);
6039     }
6040   }
6041   
6042   if (isa<CastInst>(Op0)) {
6043     // Handle the special case of: icmp (cast bool to X), <cst>
6044     // This comes up when you have code like
6045     //   int X = A < B;
6046     //   if (X) ...
6047     // For generality, we handle any zero-extension of any operand comparison
6048     // with a constant or another cast from the same type.
6049     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6050       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6051         return R;
6052   }
6053   
6054   if (I.isEquality()) {
6055     Value *A, *B, *C, *D;
6056     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6057       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6058         Value *OtherVal = A == Op1 ? B : A;
6059         return new ICmpInst(I.getPredicate(), OtherVal,
6060                             Constant::getNullValue(A->getType()));
6061       }
6062
6063       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6064         // A^c1 == C^c2 --> A == C^(c1^c2)
6065         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6066           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6067             if (Op1->hasOneUse()) {
6068               Constant *NC = ConstantExpr::getXor(C1, C2);
6069               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6070               return new ICmpInst(I.getPredicate(), A,
6071                                   InsertNewInstBefore(Xor, I));
6072             }
6073         
6074         // A^B == A^D -> B == D
6075         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6076         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6077         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6078         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6079       }
6080     }
6081     
6082     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6083         (A == Op0 || B == Op0)) {
6084       // A == (A^B)  ->  B == 0
6085       Value *OtherVal = A == Op0 ? B : A;
6086       return new ICmpInst(I.getPredicate(), OtherVal,
6087                           Constant::getNullValue(A->getType()));
6088     }
6089     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6090       // (A-B) == A  ->  B == 0
6091       return new ICmpInst(I.getPredicate(), B,
6092                           Constant::getNullValue(B->getType()));
6093     }
6094     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6095       // A == (A-B)  ->  B == 0
6096       return new ICmpInst(I.getPredicate(), B,
6097                           Constant::getNullValue(B->getType()));
6098     }
6099     
6100     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6101     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6102         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6103         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6104       Value *X = 0, *Y = 0, *Z = 0;
6105       
6106       if (A == C) {
6107         X = B; Y = D; Z = A;
6108       } else if (A == D) {
6109         X = B; Y = C; Z = A;
6110       } else if (B == C) {
6111         X = A; Y = D; Z = B;
6112       } else if (B == D) {
6113         X = A; Y = C; Z = B;
6114       }
6115       
6116       if (X) {   // Build (X^Y) & Z
6117         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6118         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6119         I.setOperand(0, Op1);
6120         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6121         return &I;
6122       }
6123     }
6124   }
6125   return Changed ? &I : 0;
6126 }
6127
6128 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6129 // We only handle extending casts so far.
6130 //
6131 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6132   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6133   Value *LHSCIOp        = LHSCI->getOperand(0);
6134   const Type *SrcTy     = LHSCIOp->getType();
6135   const Type *DestTy    = LHSCI->getType();
6136   Value *RHSCIOp;
6137
6138   // We only handle extension cast instructions, so far. Enforce this.
6139   if (LHSCI->getOpcode() != Instruction::ZExt &&
6140       LHSCI->getOpcode() != Instruction::SExt)
6141     return 0;
6142
6143   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6144   bool isSignedCmp = ICI.isSignedPredicate();
6145
6146   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6147     // Not an extension from the same type?
6148     RHSCIOp = CI->getOperand(0);
6149     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6150       return 0;
6151     
6152     // If the signedness of the two compares doesn't agree (i.e. one is a sext
6153     // and the other is a zext), then we can't handle this.
6154     if (CI->getOpcode() != LHSCI->getOpcode())
6155       return 0;
6156
6157     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
6158     // then we can't handle this.
6159     if (isSignedExt != isSignedCmp && !ICI.isEquality())
6160       return 0;
6161     
6162     // Okay, just insert a compare of the reduced operands now!
6163     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6164   }
6165
6166   // If we aren't dealing with a constant on the RHS, exit early
6167   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6168   if (!CI)
6169     return 0;
6170
6171   // Compute the constant that would happen if we truncated to SrcTy then
6172   // reextended to DestTy.
6173   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6174   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6175
6176   // If the re-extended constant didn't change...
6177   if (Res2 == CI) {
6178     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6179     // For example, we might have:
6180     //    %A = sext short %X to uint
6181     //    %B = icmp ugt uint %A, 1330
6182     // It is incorrect to transform this into 
6183     //    %B = icmp ugt short %X, 1330 
6184     // because %A may have negative value. 
6185     //
6186     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6187     // OR operation is EQ/NE.
6188     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6189       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6190     else
6191       return 0;
6192   }
6193
6194   // The re-extended constant changed so the constant cannot be represented 
6195   // in the shorter type. Consequently, we cannot emit a simple comparison.
6196
6197   // First, handle some easy cases. We know the result cannot be equal at this
6198   // point so handle the ICI.isEquality() cases
6199   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6200     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6201   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6202     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6203
6204   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6205   // should have been folded away previously and not enter in here.
6206   Value *Result;
6207   if (isSignedCmp) {
6208     // We're performing a signed comparison.
6209     if (cast<ConstantInt>(CI)->getValue().isNegative())
6210       Result = ConstantInt::getFalse();          // X < (small) --> false
6211     else
6212       Result = ConstantInt::getTrue();           // X < (large) --> true
6213   } else {
6214     // We're performing an unsigned comparison.
6215     if (isSignedExt) {
6216       // We're performing an unsigned comp with a sign extended value.
6217       // This is true if the input is >= 0. [aka >s -1]
6218       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6219       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6220                                    NegOne, ICI.getName()), ICI);
6221     } else {
6222       // Unsigned extend & unsigned compare -> always true.
6223       Result = ConstantInt::getTrue();
6224     }
6225   }
6226
6227   // Finally, return the value computed.
6228   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6229       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6230     return ReplaceInstUsesWith(ICI, Result);
6231   } else {
6232     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6233             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6234            "ICmp should be folded!");
6235     if (Constant *CI = dyn_cast<Constant>(Result))
6236       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6237     else
6238       return BinaryOperator::createNot(Result);
6239   }
6240 }
6241
6242 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6243   return commonShiftTransforms(I);
6244 }
6245
6246 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6247   return commonShiftTransforms(I);
6248 }
6249
6250 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6251   return commonShiftTransforms(I);
6252 }
6253
6254 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6255   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6256   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6257
6258   // shl X, 0 == X and shr X, 0 == X
6259   // shl 0, X == 0 and shr 0, X == 0
6260   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6261       Op0 == Constant::getNullValue(Op0->getType()))
6262     return ReplaceInstUsesWith(I, Op0);
6263   
6264   if (isa<UndefValue>(Op0)) {            
6265     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6266       return ReplaceInstUsesWith(I, Op0);
6267     else                                    // undef << X -> 0, undef >>u X -> 0
6268       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6269   }
6270   if (isa<UndefValue>(Op1)) {
6271     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6272       return ReplaceInstUsesWith(I, Op0);          
6273     else                                     // X << undef, X >>u undef -> 0
6274       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6275   }
6276
6277   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6278   if (I.getOpcode() == Instruction::AShr)
6279     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6280       if (CSI->isAllOnesValue())
6281         return ReplaceInstUsesWith(I, CSI);
6282
6283   // Try to fold constant and into select arguments.
6284   if (isa<Constant>(Op0))
6285     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6286       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6287         return R;
6288
6289   // See if we can turn a signed shr into an unsigned shr.
6290   if (I.isArithmeticShift()) {
6291     if (MaskedValueIsZero(Op0,
6292                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
6293       return BinaryOperator::createLShr(Op0, Op1, I.getName());
6294     }
6295   }
6296
6297   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6298     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6299       return Res;
6300   return 0;
6301 }
6302
6303 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6304                                                BinaryOperator &I) {
6305   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6306
6307   // See if we can simplify any instructions used by the instruction whose sole 
6308   // purpose is to compute bits we don't care about.
6309   uint64_t KnownZero, KnownOne;
6310   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
6311                            KnownZero, KnownOne))
6312     return &I;
6313   
6314   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6315   // of a signed value.
6316   //
6317   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6318   if (Op1->getZExtValue() >= TypeBits) {
6319     if (I.getOpcode() != Instruction::AShr)
6320       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6321     else {
6322       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6323       return &I;
6324     }
6325   }
6326   
6327   // ((X*C1) << C2) == (X * (C1 << C2))
6328   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6329     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6330       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6331         return BinaryOperator::createMul(BO->getOperand(0),
6332                                          ConstantExpr::getShl(BOOp, Op1));
6333   
6334   // Try to fold constant and into select arguments.
6335   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6336     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6337       return R;
6338   if (isa<PHINode>(Op0))
6339     if (Instruction *NV = FoldOpIntoPhi(I))
6340       return NV;
6341   
6342   if (Op0->hasOneUse()) {
6343     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6344       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6345       Value *V1, *V2;
6346       ConstantInt *CC;
6347       switch (Op0BO->getOpcode()) {
6348         default: break;
6349         case Instruction::Add:
6350         case Instruction::And:
6351         case Instruction::Or:
6352         case Instruction::Xor: {
6353           // These operators commute.
6354           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6355           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6356               match(Op0BO->getOperand(1),
6357                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6358             Instruction *YS = BinaryOperator::createShl(
6359                                             Op0BO->getOperand(0), Op1,
6360                                             Op0BO->getName());
6361             InsertNewInstBefore(YS, I); // (Y << C)
6362             Instruction *X = 
6363               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6364                                      Op0BO->getOperand(1)->getName());
6365             InsertNewInstBefore(X, I);  // (X + (Y << C))
6366             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
6367             C2 = ConstantExpr::getShl(C2, Op1);
6368             return BinaryOperator::createAnd(X, C2);
6369           }
6370           
6371           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6372           Value *Op0BOOp1 = Op0BO->getOperand(1);
6373           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6374               match(Op0BOOp1, 
6375                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6376               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6377               V2 == Op1) {
6378             Instruction *YS = BinaryOperator::createShl(
6379                                                      Op0BO->getOperand(0), Op1,
6380                                                      Op0BO->getName());
6381             InsertNewInstBefore(YS, I); // (Y << C)
6382             Instruction *XM =
6383               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6384                                         V1->getName()+".mask");
6385             InsertNewInstBefore(XM, I); // X & (CC << C)
6386             
6387             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6388           }
6389         }
6390           
6391         // FALL THROUGH.
6392         case Instruction::Sub: {
6393           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6394           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6395               match(Op0BO->getOperand(0),
6396                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6397             Instruction *YS = BinaryOperator::createShl(
6398                                                      Op0BO->getOperand(1), Op1,
6399                                                      Op0BO->getName());
6400             InsertNewInstBefore(YS, I); // (Y << C)
6401             Instruction *X =
6402               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6403                                      Op0BO->getOperand(0)->getName());
6404             InsertNewInstBefore(X, I);  // (X + (Y << C))
6405             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
6406             C2 = ConstantExpr::getShl(C2, Op1);
6407             return BinaryOperator::createAnd(X, C2);
6408           }
6409           
6410           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6411           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6412               match(Op0BO->getOperand(0),
6413                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6414                           m_ConstantInt(CC))) && V2 == Op1 &&
6415               cast<BinaryOperator>(Op0BO->getOperand(0))
6416                   ->getOperand(0)->hasOneUse()) {
6417             Instruction *YS = BinaryOperator::createShl(
6418                                                      Op0BO->getOperand(1), Op1,
6419                                                      Op0BO->getName());
6420             InsertNewInstBefore(YS, I); // (Y << C)
6421             Instruction *XM =
6422               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6423                                         V1->getName()+".mask");
6424             InsertNewInstBefore(XM, I); // X & (CC << C)
6425             
6426             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6427           }
6428           
6429           break;
6430         }
6431       }
6432       
6433       
6434       // If the operand is an bitwise operator with a constant RHS, and the
6435       // shift is the only use, we can pull it out of the shift.
6436       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6437         bool isValid = true;     // Valid only for And, Or, Xor
6438         bool highBitSet = false; // Transform if high bit of constant set?
6439         
6440         switch (Op0BO->getOpcode()) {
6441           default: isValid = false; break;   // Do not perform transform!
6442           case Instruction::Add:
6443             isValid = isLeftShift;
6444             break;
6445           case Instruction::Or:
6446           case Instruction::Xor:
6447             highBitSet = false;
6448             break;
6449           case Instruction::And:
6450             highBitSet = true;
6451             break;
6452         }
6453         
6454         // If this is a signed shift right, and the high bit is modified
6455         // by the logical operation, do not perform the transformation.
6456         // The highBitSet boolean indicates the value of the high bit of
6457         // the constant which would cause it to be modified for this
6458         // operation.
6459         //
6460         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
6461           uint64_t Val = Op0C->getZExtValue();
6462           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
6463         }
6464         
6465         if (isValid) {
6466           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6467           
6468           Instruction *NewShift =
6469             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6470           InsertNewInstBefore(NewShift, I);
6471           NewShift->takeName(Op0BO);
6472           
6473           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6474                                         NewRHS);
6475         }
6476       }
6477     }
6478   }
6479   
6480   // Find out if this is a shift of a shift by a constant.
6481   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6482   if (ShiftOp && !ShiftOp->isShift())
6483     ShiftOp = 0;
6484   
6485   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6486     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6487     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6488     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
6489     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6490     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6491     Value *X = ShiftOp->getOperand(0);
6492     
6493     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6494     if (AmtSum > I.getType()->getPrimitiveSizeInBits())
6495       AmtSum = I.getType()->getPrimitiveSizeInBits();
6496     
6497     const IntegerType *Ty = cast<IntegerType>(I.getType());
6498     
6499     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6500     if (I.getOpcode() == ShiftOp->getOpcode()) {
6501       return BinaryOperator::create(I.getOpcode(), X,
6502                                     ConstantInt::get(Ty, AmtSum));
6503     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6504                I.getOpcode() == Instruction::AShr) {
6505       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6506       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6507     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6508                I.getOpcode() == Instruction::LShr) {
6509       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6510       Instruction *Shift =
6511         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6512       InsertNewInstBefore(Shift, I);
6513
6514       uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6515       return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6516     }
6517     
6518     // Okay, if we get here, one shift must be left, and the other shift must be
6519     // right.  See if the amounts are equal.
6520     if (ShiftAmt1 == ShiftAmt2) {
6521       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6522       if (I.getOpcode() == Instruction::Shl) {
6523         uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
6524         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6525       }
6526       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6527       if (I.getOpcode() == Instruction::LShr) {
6528         uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
6529         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6530       }
6531       // We can simplify ((X << C) >>s C) into a trunc + sext.
6532       // NOTE: we could do this for any C, but that would make 'unusual' integer
6533       // types.  For now, just stick to ones well-supported by the code
6534       // generators.
6535       const Type *SExtType = 0;
6536       switch (Ty->getBitWidth() - ShiftAmt1) {
6537       case 8 : SExtType = Type::Int8Ty; break;
6538       case 16: SExtType = Type::Int16Ty; break;
6539       case 32: SExtType = Type::Int32Ty; break;
6540       default: break;
6541       }
6542       if (SExtType) {
6543         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6544         InsertNewInstBefore(NewTrunc, I);
6545         return new SExtInst(NewTrunc, Ty);
6546       }
6547       // Otherwise, we can't handle it yet.
6548     } else if (ShiftAmt1 < ShiftAmt2) {
6549       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
6550       
6551       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6552       if (I.getOpcode() == Instruction::Shl) {
6553         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6554                ShiftOp->getOpcode() == Instruction::AShr);
6555         Instruction *Shift =
6556           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6557         InsertNewInstBefore(Shift, I);
6558         
6559         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6560         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6561       }
6562       
6563       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6564       if (I.getOpcode() == Instruction::LShr) {
6565         assert(ShiftOp->getOpcode() == Instruction::Shl);
6566         Instruction *Shift =
6567           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6568         InsertNewInstBefore(Shift, I);
6569         
6570         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6571         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6572       }
6573       
6574       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6575     } else {
6576       assert(ShiftAmt2 < ShiftAmt1);
6577       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6578
6579       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6580       if (I.getOpcode() == Instruction::Shl) {
6581         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6582                ShiftOp->getOpcode() == Instruction::AShr);
6583         Instruction *Shift =
6584           BinaryOperator::create(ShiftOp->getOpcode(), X,
6585                                  ConstantInt::get(Ty, ShiftDiff));
6586         InsertNewInstBefore(Shift, I);
6587         
6588         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6589         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6590       }
6591       
6592       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6593       if (I.getOpcode() == Instruction::LShr) {
6594         assert(ShiftOp->getOpcode() == Instruction::Shl);
6595         Instruction *Shift =
6596           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6597         InsertNewInstBefore(Shift, I);
6598         
6599         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6600         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6601       }
6602       
6603       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6604     }
6605   }
6606   return 0;
6607 }
6608
6609
6610 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6611 /// expression.  If so, decompose it, returning some value X, such that Val is
6612 /// X*Scale+Offset.
6613 ///
6614 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6615                                         unsigned &Offset) {
6616   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6617   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6618     Offset = CI->getZExtValue();
6619     Scale  = 1;
6620     return ConstantInt::get(Type::Int32Ty, 0);
6621   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6622     if (I->getNumOperands() == 2) {
6623       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6624         if (I->getOpcode() == Instruction::Shl) {
6625           // This is a value scaled by '1 << the shift amt'.
6626           Scale = 1U << CUI->getZExtValue();
6627           Offset = 0;
6628           return I->getOperand(0);
6629         } else if (I->getOpcode() == Instruction::Mul) {
6630           // This value is scaled by 'CUI'.
6631           Scale = CUI->getZExtValue();
6632           Offset = 0;
6633           return I->getOperand(0);
6634         } else if (I->getOpcode() == Instruction::Add) {
6635           // We have X+C.  Check to see if we really have (X*C2)+C1, 
6636           // where C1 is divisible by C2.
6637           unsigned SubScale;
6638           Value *SubVal = 
6639             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6640           Offset += CUI->getZExtValue();
6641           if (SubScale > 1 && (Offset % SubScale == 0)) {
6642             Scale = SubScale;
6643             return SubVal;
6644           }
6645         }
6646       }
6647     }
6648   }
6649
6650   // Otherwise, we can't look past this.
6651   Scale = 1;
6652   Offset = 0;
6653   return Val;
6654 }
6655
6656
6657 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6658 /// try to eliminate the cast by moving the type information into the alloc.
6659 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6660                                                    AllocationInst &AI) {
6661   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
6662   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
6663   
6664   // Remove any uses of AI that are dead.
6665   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6666   
6667   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6668     Instruction *User = cast<Instruction>(*UI++);
6669     if (isInstructionTriviallyDead(User)) {
6670       while (UI != E && *UI == User)
6671         ++UI; // If this instruction uses AI more than once, don't break UI.
6672       
6673       ++NumDeadInst;
6674       DOUT << "IC: DCE: " << *User;
6675       EraseInstFromFunction(*User);
6676     }
6677   }
6678   
6679   // Get the type really allocated and the type casted to.
6680   const Type *AllocElTy = AI.getAllocatedType();
6681   const Type *CastElTy = PTy->getElementType();
6682   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6683
6684   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6685   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6686   if (CastElTyAlign < AllocElTyAlign) return 0;
6687
6688   // If the allocation has multiple uses, only promote it if we are strictly
6689   // increasing the alignment of the resultant allocation.  If we keep it the
6690   // same, we open the door to infinite loops of various kinds.
6691   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6692
6693   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6694   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6695   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6696
6697   // See if we can satisfy the modulus by pulling a scale out of the array
6698   // size argument.
6699   unsigned ArraySizeScale, ArrayOffset;
6700   Value *NumElements = // See if the array size is a decomposable linear expr.
6701     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6702  
6703   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6704   // do the xform.
6705   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6706       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6707
6708   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6709   Value *Amt = 0;
6710   if (Scale == 1) {
6711     Amt = NumElements;
6712   } else {
6713     // If the allocation size is constant, form a constant mul expression
6714     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6715     if (isa<ConstantInt>(NumElements))
6716       Amt = ConstantExpr::getMul(
6717               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6718     // otherwise multiply the amount and the number of elements
6719     else if (Scale != 1) {
6720       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6721       Amt = InsertNewInstBefore(Tmp, AI);
6722     }
6723   }
6724   
6725   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6726     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
6727     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6728     Amt = InsertNewInstBefore(Tmp, AI);
6729   }
6730   
6731   AllocationInst *New;
6732   if (isa<MallocInst>(AI))
6733     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6734   else
6735     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6736   InsertNewInstBefore(New, AI);
6737   New->takeName(&AI);
6738   
6739   // If the allocation has multiple uses, insert a cast and change all things
6740   // that used it to use the new cast.  This will also hack on CI, but it will
6741   // die soon.
6742   if (!AI.hasOneUse()) {
6743     AddUsesToWorkList(AI);
6744     // New is the allocation instruction, pointer typed. AI is the original
6745     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6746     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6747     InsertNewInstBefore(NewCast, AI);
6748     AI.replaceAllUsesWith(NewCast);
6749   }
6750   return ReplaceInstUsesWith(CI, New);
6751 }
6752
6753 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6754 /// and return it as type Ty without inserting any new casts and without
6755 /// changing the computed value.  This is used by code that tries to decide
6756 /// whether promoting or shrinking integer operations to wider or smaller types
6757 /// will allow us to eliminate a truncate or extend.
6758 ///
6759 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6760 /// extension operation if Ty is larger.
6761 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6762                                        int &NumCastsRemoved) {
6763   // We can always evaluate constants in another type.
6764   if (isa<ConstantInt>(V))
6765     return true;
6766   
6767   Instruction *I = dyn_cast<Instruction>(V);
6768   if (!I) return false;
6769   
6770   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6771   
6772   switch (I->getOpcode()) {
6773   case Instruction::Add:
6774   case Instruction::Sub:
6775   case Instruction::And:
6776   case Instruction::Or:
6777   case Instruction::Xor:
6778     if (!I->hasOneUse()) return false;
6779     // These operators can all arbitrarily be extended or truncated.
6780     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6781            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6782
6783   case Instruction::Shl:
6784     if (!I->hasOneUse()) return false;
6785     // If we are truncating the result of this SHL, and if it's a shift of a
6786     // constant amount, we can always perform a SHL in a smaller type.
6787     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6788       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6789           CI->getZExtValue() < Ty->getBitWidth())
6790         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6791     }
6792     break;
6793   case Instruction::LShr:
6794     if (!I->hasOneUse()) return false;
6795     // If this is a truncate of a logical shr, we can truncate it to a smaller
6796     // lshr iff we know that the bits we would otherwise be shifting in are
6797     // already zeros.
6798     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6799       uint32_t BitWidth = OrigTy->getBitWidth();
6800       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6801           MaskedValueIsZero(I->getOperand(0),
6802             APInt::getAllOnesValue(BitWidth) & 
6803          APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6804          && CI->getZExtValue() < Ty->getBitWidth()) {
6805         return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6806       }
6807     }
6808     break;
6809   case Instruction::Trunc:
6810   case Instruction::ZExt:
6811   case Instruction::SExt:
6812     // If this is a cast from the destination type, we can trivially eliminate
6813     // it, and this will remove a cast overall.
6814     if (I->getOperand(0)->getType() == Ty) {
6815       // If the first operand is itself a cast, and is eliminable, do not count
6816       // this as an eliminable cast.  We would prefer to eliminate those two
6817       // casts first.
6818       if (isa<CastInst>(I->getOperand(0)))
6819         return true;
6820       
6821       ++NumCastsRemoved;
6822       return true;
6823     }
6824     break;
6825   default:
6826     // TODO: Can handle more cases here.
6827     break;
6828   }
6829   
6830   return false;
6831 }
6832
6833 /// EvaluateInDifferentType - Given an expression that 
6834 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6835 /// evaluate the expression.
6836 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6837                                              bool isSigned) {
6838   if (Constant *C = dyn_cast<Constant>(V))
6839     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6840
6841   // Otherwise, it must be an instruction.
6842   Instruction *I = cast<Instruction>(V);
6843   Instruction *Res = 0;
6844   switch (I->getOpcode()) {
6845   case Instruction::Add:
6846   case Instruction::Sub:
6847   case Instruction::And:
6848   case Instruction::Or:
6849   case Instruction::Xor:
6850   case Instruction::AShr:
6851   case Instruction::LShr:
6852   case Instruction::Shl: {
6853     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6854     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6855     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6856                                  LHS, RHS, I->getName());
6857     break;
6858   }    
6859   case Instruction::Trunc:
6860   case Instruction::ZExt:
6861   case Instruction::SExt:
6862   case Instruction::BitCast:
6863     // If the source type of the cast is the type we're trying for then we can
6864     // just return the source. There's no need to insert it because its not new.
6865     if (I->getOperand(0)->getType() == Ty)
6866       return I->getOperand(0);
6867     
6868     // Some other kind of cast, which shouldn't happen, so just ..
6869     // FALL THROUGH
6870   default: 
6871     // TODO: Can handle more cases here.
6872     assert(0 && "Unreachable!");
6873     break;
6874   }
6875   
6876   return InsertNewInstBefore(Res, *I);
6877 }
6878
6879 /// @brief Implement the transforms common to all CastInst visitors.
6880 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6881   Value *Src = CI.getOperand(0);
6882
6883   // Casting undef to anything results in undef so might as just replace it and
6884   // get rid of the cast.
6885   if (isa<UndefValue>(Src))   // cast undef -> undef
6886     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6887
6888   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6889   // eliminate it now.
6890   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6891     if (Instruction::CastOps opc = 
6892         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6893       // The first cast (CSrc) is eliminable so we need to fix up or replace
6894       // the second cast (CI). CSrc will then have a good chance of being dead.
6895       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6896     }
6897   }
6898
6899   // If casting the result of a getelementptr instruction with no offset, turn
6900   // this into a cast of the original pointer!
6901   //
6902   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6903     bool AllZeroOperands = true;
6904     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6905       if (!isa<Constant>(GEP->getOperand(i)) ||
6906           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6907         AllZeroOperands = false;
6908         break;
6909       }
6910     if (AllZeroOperands) {
6911       // Changing the cast operand is usually not a good idea but it is safe
6912       // here because the pointer operand is being replaced with another 
6913       // pointer operand so the opcode doesn't need to change.
6914       CI.setOperand(0, GEP->getOperand(0));
6915       return &CI;
6916     }
6917   }
6918     
6919   // If we are casting a malloc or alloca to a pointer to a type of the same
6920   // size, rewrite the allocation instruction to allocate the "right" type.
6921   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6922     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6923       return V;
6924
6925   // If we are casting a select then fold the cast into the select
6926   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6927     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6928       return NV;
6929
6930   // If we are casting a PHI then fold the cast into the PHI
6931   if (isa<PHINode>(Src))
6932     if (Instruction *NV = FoldOpIntoPhi(CI))
6933       return NV;
6934   
6935   return 0;
6936 }
6937
6938 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6939 /// integer types. This function implements the common transforms for all those
6940 /// cases.
6941 /// @brief Implement the transforms common to CastInst with integer operands
6942 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6943   if (Instruction *Result = commonCastTransforms(CI))
6944     return Result;
6945
6946   Value *Src = CI.getOperand(0);
6947   const Type *SrcTy = Src->getType();
6948   const Type *DestTy = CI.getType();
6949   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6950   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6951
6952   // See if we can simplify any instructions used by the LHS whose sole 
6953   // purpose is to compute bits we don't care about.
6954   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6955   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6956                            KnownZero, KnownOne))
6957     return &CI;
6958
6959   // If the source isn't an instruction or has more than one use then we
6960   // can't do anything more. 
6961   Instruction *SrcI = dyn_cast<Instruction>(Src);
6962   if (!SrcI || !Src->hasOneUse())
6963     return 0;
6964
6965   // Attempt to propagate the cast into the instruction for int->int casts.
6966   int NumCastsRemoved = 0;
6967   if (!isa<BitCastInst>(CI) &&
6968       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6969                                  NumCastsRemoved)) {
6970     // If this cast is a truncate, evaluting in a different type always
6971     // eliminates the cast, so it is always a win.  If this is a noop-cast
6972     // this just removes a noop cast which isn't pointful, but simplifies
6973     // the code.  If this is a zero-extension, we need to do an AND to
6974     // maintain the clear top-part of the computation, so we require that
6975     // the input have eliminated at least one cast.  If this is a sign
6976     // extension, we insert two new casts (to do the extension) so we
6977     // require that two casts have been eliminated.
6978     bool DoXForm;
6979     switch (CI.getOpcode()) {
6980     default:
6981       // All the others use floating point so we shouldn't actually 
6982       // get here because of the check above.
6983       assert(0 && "Unknown cast type");
6984     case Instruction::Trunc:
6985       DoXForm = true;
6986       break;
6987     case Instruction::ZExt:
6988       DoXForm = NumCastsRemoved >= 1;
6989       break;
6990     case Instruction::SExt:
6991       DoXForm = NumCastsRemoved >= 2;
6992       break;
6993     case Instruction::BitCast:
6994       DoXForm = false;
6995       break;
6996     }
6997     
6998     if (DoXForm) {
6999       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7000                                            CI.getOpcode() == Instruction::SExt);
7001       assert(Res->getType() == DestTy);
7002       switch (CI.getOpcode()) {
7003       default: assert(0 && "Unknown cast type!");
7004       case Instruction::Trunc:
7005       case Instruction::BitCast:
7006         // Just replace this cast with the result.
7007         return ReplaceInstUsesWith(CI, Res);
7008       case Instruction::ZExt: {
7009         // We need to emit an AND to clear the high bits.
7010         assert(SrcBitSize < DestBitSize && "Not a zext?");
7011         Constant *C = ConstantInt::get(APInt::getAllOnesValue(SrcBitSize));
7012         C = ConstantExpr::getZExt(C, DestTy);
7013         return BinaryOperator::createAnd(Res, C);
7014       }
7015       case Instruction::SExt:
7016         // We need to emit a cast to truncate, then a cast to sext.
7017         return CastInst::create(Instruction::SExt,
7018             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7019                              CI), DestTy);
7020       }
7021     }
7022   }
7023   
7024   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7025   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7026
7027   switch (SrcI->getOpcode()) {
7028   case Instruction::Add:
7029   case Instruction::Mul:
7030   case Instruction::And:
7031   case Instruction::Or:
7032   case Instruction::Xor:
7033     // If we are discarding information, or just changing the sign, 
7034     // rewrite.
7035     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7036       // Don't insert two casts if they cannot be eliminated.  We allow 
7037       // two casts to be inserted if the sizes are the same.  This could 
7038       // only be converting signedness, which is a noop.
7039       if (DestBitSize == SrcBitSize || 
7040           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7041           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7042         Instruction::CastOps opcode = CI.getOpcode();
7043         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7044         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7045         return BinaryOperator::create(
7046             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7047       }
7048     }
7049
7050     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7051     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7052         SrcI->getOpcode() == Instruction::Xor &&
7053         Op1 == ConstantInt::getTrue() &&
7054         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7055       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7056       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7057     }
7058     break;
7059   case Instruction::SDiv:
7060   case Instruction::UDiv:
7061   case Instruction::SRem:
7062   case Instruction::URem:
7063     // If we are just changing the sign, rewrite.
7064     if (DestBitSize == SrcBitSize) {
7065       // Don't insert two casts if they cannot be eliminated.  We allow 
7066       // two casts to be inserted if the sizes are the same.  This could 
7067       // only be converting signedness, which is a noop.
7068       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7069           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7070         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7071                                               Op0, DestTy, SrcI);
7072         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7073                                               Op1, DestTy, SrcI);
7074         return BinaryOperator::create(
7075           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7076       }
7077     }
7078     break;
7079
7080   case Instruction::Shl:
7081     // Allow changing the sign of the source operand.  Do not allow 
7082     // changing the size of the shift, UNLESS the shift amount is a 
7083     // constant.  We must not change variable sized shifts to a smaller 
7084     // size, because it is undefined to shift more bits out than exist 
7085     // in the value.
7086     if (DestBitSize == SrcBitSize ||
7087         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7088       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7089           Instruction::BitCast : Instruction::Trunc);
7090       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7091       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7092       return BinaryOperator::createShl(Op0c, Op1c);
7093     }
7094     break;
7095   case Instruction::AShr:
7096     // If this is a signed shr, and if all bits shifted in are about to be
7097     // truncated off, turn it into an unsigned shr to allow greater
7098     // simplifications.
7099     if (DestBitSize < SrcBitSize &&
7100         isa<ConstantInt>(Op1)) {
7101       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7102       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7103         // Insert the new logical shift right.
7104         return BinaryOperator::createLShr(Op0, Op1);
7105       }
7106     }
7107     break;
7108
7109   case Instruction::ICmp:
7110     // If we are just checking for a icmp eq of a single bit and casting it
7111     // to an integer, then shift the bit to the appropriate place and then
7112     // cast to integer to avoid the comparison.
7113     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
7114       APInt Op1CV(Op1C->getValue());
7115       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
7116       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7117       // cast (X == 1) to int --> X        iff X has only the low bit set.
7118       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
7119       // cast (X != 0) to int --> X        iff X has only the low bit set.
7120       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
7121       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
7122       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7123       if (Op1CV == 0 || Op1CV.isPowerOf2()) {
7124         // If Op1C some other power of two, convert:
7125         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7126         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7127         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7128         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
7129
7130         // This only works for EQ and NE
7131         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7132         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7133           break;
7134         
7135         if ((KnownZero^TypeMask).isPowerOf2()) { // Exactly 1 possible 1?
7136           bool isNE = pred == ICmpInst::ICMP_NE;
7137           if (Op1CV != 0 && (Op1CV != (KnownZero^TypeMask))) {
7138             // (X&4) == 2 --> false
7139             // (X&4) != 2 --> true
7140             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7141             Res = ConstantExpr::getZExt(Res, CI.getType());
7142             return ReplaceInstUsesWith(CI, Res);
7143           }
7144           
7145           unsigned ShiftAmt = (KnownZero^TypeMask).logBase2();
7146           Value *In = Op0;
7147           if (ShiftAmt) {
7148             // Perform a logical shr by shiftamt.
7149             // Insert the shift to put the result in the low bit.
7150             In = InsertNewInstBefore(
7151               BinaryOperator::createLShr(In,
7152                                      ConstantInt::get(In->getType(), ShiftAmt),
7153                                      In->getName()+".lobit"), CI);
7154           }
7155           
7156           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7157             Constant *One = ConstantInt::get(In->getType(), 1);
7158             In = BinaryOperator::createXor(In, One, "tmp");
7159             InsertNewInstBefore(cast<Instruction>(In), CI);
7160           }
7161           
7162           if (CI.getType() == In->getType())
7163             return ReplaceInstUsesWith(CI, In);
7164           else
7165             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7166         }
7167       }
7168     }
7169     break;
7170   }
7171   return 0;
7172 }
7173
7174 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
7175   if (Instruction *Result = commonIntCastTransforms(CI))
7176     return Result;
7177   
7178   Value *Src = CI.getOperand(0);
7179   const Type *Ty = CI.getType();
7180   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
7181   unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7182   
7183   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7184     switch (SrcI->getOpcode()) {
7185     default: break;
7186     case Instruction::LShr:
7187       // We can shrink lshr to something smaller if we know the bits shifted in
7188       // are already zeros.
7189       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7190         unsigned ShAmt = ShAmtV->getZExtValue();
7191         
7192         // Get a mask for the bits shifting in.
7193         APInt Mask(APInt::getAllOnesValue(SrcBitWidth).lshr(
7194                      SrcBitWidth-ShAmt).shl(DestBitWidth));
7195         Value* SrcIOp0 = SrcI->getOperand(0);
7196         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7197           if (ShAmt >= DestBitWidth)        // All zeros.
7198             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7199
7200           // Okay, we can shrink this.  Truncate the input, then return a new
7201           // shift.
7202           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7203           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7204                                        Ty, CI);
7205           return BinaryOperator::createLShr(V1, V2);
7206         }
7207       } else {     // This is a variable shr.
7208         
7209         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7210         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7211         // loop-invariant and CSE'd.
7212         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7213           Value *One = ConstantInt::get(SrcI->getType(), 1);
7214
7215           Value *V = InsertNewInstBefore(
7216               BinaryOperator::createShl(One, SrcI->getOperand(1),
7217                                      "tmp"), CI);
7218           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7219                                                             SrcI->getOperand(0),
7220                                                             "tmp"), CI);
7221           Value *Zero = Constant::getNullValue(V->getType());
7222           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7223         }
7224       }
7225       break;
7226     }
7227   }
7228   
7229   return 0;
7230 }
7231
7232 Instruction *InstCombiner::visitZExt(CastInst &CI) {
7233   // If one of the common conversion will work ..
7234   if (Instruction *Result = commonIntCastTransforms(CI))
7235     return Result;
7236
7237   Value *Src = CI.getOperand(0);
7238
7239   // If this is a cast of a cast
7240   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7241     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7242     // types and if the sizes are just right we can convert this into a logical
7243     // 'and' which will be much cheaper than the pair of casts.
7244     if (isa<TruncInst>(CSrc)) {
7245       // Get the sizes of the types involved
7246       Value *A = CSrc->getOperand(0);
7247       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7248       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7249       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7250       // If we're actually extending zero bits and the trunc is a no-op
7251       if (MidSize < DstSize && SrcSize == DstSize) {
7252         // Replace both of the casts with an And of the type mask.
7253         APInt AndValue(APInt::getAllOnesValue(MidSize).zext(SrcSize));
7254         Constant *AndConst = ConstantInt::get(AndValue);
7255         Instruction *And = 
7256           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7257         // Unfortunately, if the type changed, we need to cast it back.
7258         if (And->getType() != CI.getType()) {
7259           And->setName(CSrc->getName()+".mask");
7260           InsertNewInstBefore(And, CI);
7261           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7262         }
7263         return And;
7264       }
7265     }
7266   }
7267
7268   return 0;
7269 }
7270
7271 Instruction *InstCombiner::visitSExt(CastInst &CI) {
7272   return commonIntCastTransforms(CI);
7273 }
7274
7275 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7276   return commonCastTransforms(CI);
7277 }
7278
7279 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7280   return commonCastTransforms(CI);
7281 }
7282
7283 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7284   return commonCastTransforms(CI);
7285 }
7286
7287 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7288   return commonCastTransforms(CI);
7289 }
7290
7291 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7292   return commonCastTransforms(CI);
7293 }
7294
7295 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7296   return commonCastTransforms(CI);
7297 }
7298
7299 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7300   return commonCastTransforms(CI);
7301 }
7302
7303 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7304   return commonCastTransforms(CI);
7305 }
7306
7307 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7308
7309   // If the operands are integer typed then apply the integer transforms,
7310   // otherwise just apply the common ones.
7311   Value *Src = CI.getOperand(0);
7312   const Type *SrcTy = Src->getType();
7313   const Type *DestTy = CI.getType();
7314
7315   if (SrcTy->isInteger() && DestTy->isInteger()) {
7316     if (Instruction *Result = commonIntCastTransforms(CI))
7317       return Result;
7318   } else {
7319     if (Instruction *Result = commonCastTransforms(CI))
7320       return Result;
7321   }
7322
7323
7324   // Get rid of casts from one type to the same type. These are useless and can
7325   // be replaced by the operand.
7326   if (DestTy == Src->getType())
7327     return ReplaceInstUsesWith(CI, Src);
7328
7329   // If the source and destination are pointers, and this cast is equivalent to
7330   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
7331   // This can enhance SROA and other transforms that want type-safe pointers.
7332   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7333     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7334       const Type *DstElTy = DstPTy->getElementType();
7335       const Type *SrcElTy = SrcPTy->getElementType();
7336       
7337       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7338       unsigned NumZeros = 0;
7339       while (SrcElTy != DstElTy && 
7340              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7341              SrcElTy->getNumContainedTypes() /* not "{}" */) {
7342         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7343         ++NumZeros;
7344       }
7345
7346       // If we found a path from the src to dest, create the getelementptr now.
7347       if (SrcElTy == DstElTy) {
7348         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7349         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
7350       }
7351     }
7352   }
7353
7354   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7355     if (SVI->hasOneUse()) {
7356       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7357       // a bitconvert to a vector with the same # elts.
7358       if (isa<VectorType>(DestTy) && 
7359           cast<VectorType>(DestTy)->getNumElements() == 
7360                 SVI->getType()->getNumElements()) {
7361         CastInst *Tmp;
7362         // If either of the operands is a cast from CI.getType(), then
7363         // evaluating the shuffle in the casted destination's type will allow
7364         // us to eliminate at least one cast.
7365         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7366              Tmp->getOperand(0)->getType() == DestTy) ||
7367             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7368              Tmp->getOperand(0)->getType() == DestTy)) {
7369           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7370                                                SVI->getOperand(0), DestTy, &CI);
7371           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7372                                                SVI->getOperand(1), DestTy, &CI);
7373           // Return a new shuffle vector.  Use the same element ID's, as we
7374           // know the vector types match #elts.
7375           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7376         }
7377       }
7378     }
7379   }
7380   return 0;
7381 }
7382
7383 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7384 ///   %C = or %A, %B
7385 ///   %D = select %cond, %C, %A
7386 /// into:
7387 ///   %C = select %cond, %B, 0
7388 ///   %D = or %A, %C
7389 ///
7390 /// Assuming that the specified instruction is an operand to the select, return
7391 /// a bitmask indicating which operands of this instruction are foldable if they
7392 /// equal the other incoming value of the select.
7393 ///
7394 static unsigned GetSelectFoldableOperands(Instruction *I) {
7395   switch (I->getOpcode()) {
7396   case Instruction::Add:
7397   case Instruction::Mul:
7398   case Instruction::And:
7399   case Instruction::Or:
7400   case Instruction::Xor:
7401     return 3;              // Can fold through either operand.
7402   case Instruction::Sub:   // Can only fold on the amount subtracted.
7403   case Instruction::Shl:   // Can only fold on the shift amount.
7404   case Instruction::LShr:
7405   case Instruction::AShr:
7406     return 1;
7407   default:
7408     return 0;              // Cannot fold
7409   }
7410 }
7411
7412 /// GetSelectFoldableConstant - For the same transformation as the previous
7413 /// function, return the identity constant that goes into the select.
7414 static Constant *GetSelectFoldableConstant(Instruction *I) {
7415   switch (I->getOpcode()) {
7416   default: assert(0 && "This cannot happen!"); abort();
7417   case Instruction::Add:
7418   case Instruction::Sub:
7419   case Instruction::Or:
7420   case Instruction::Xor:
7421   case Instruction::Shl:
7422   case Instruction::LShr:
7423   case Instruction::AShr:
7424     return Constant::getNullValue(I->getType());
7425   case Instruction::And:
7426     return ConstantInt::getAllOnesValue(I->getType());
7427   case Instruction::Mul:
7428     return ConstantInt::get(I->getType(), 1);
7429   }
7430 }
7431
7432 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7433 /// have the same opcode and only one use each.  Try to simplify this.
7434 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7435                                           Instruction *FI) {
7436   if (TI->getNumOperands() == 1) {
7437     // If this is a non-volatile load or a cast from the same type,
7438     // merge.
7439     if (TI->isCast()) {
7440       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7441         return 0;
7442     } else {
7443       return 0;  // unknown unary op.
7444     }
7445
7446     // Fold this by inserting a select from the input values.
7447     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7448                                        FI->getOperand(0), SI.getName()+".v");
7449     InsertNewInstBefore(NewSI, SI);
7450     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7451                             TI->getType());
7452   }
7453
7454   // Only handle binary operators here.
7455   if (!isa<BinaryOperator>(TI))
7456     return 0;
7457
7458   // Figure out if the operations have any operands in common.
7459   Value *MatchOp, *OtherOpT, *OtherOpF;
7460   bool MatchIsOpZero;
7461   if (TI->getOperand(0) == FI->getOperand(0)) {
7462     MatchOp  = TI->getOperand(0);
7463     OtherOpT = TI->getOperand(1);
7464     OtherOpF = FI->getOperand(1);
7465     MatchIsOpZero = true;
7466   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7467     MatchOp  = TI->getOperand(1);
7468     OtherOpT = TI->getOperand(0);
7469     OtherOpF = FI->getOperand(0);
7470     MatchIsOpZero = false;
7471   } else if (!TI->isCommutative()) {
7472     return 0;
7473   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7474     MatchOp  = TI->getOperand(0);
7475     OtherOpT = TI->getOperand(1);
7476     OtherOpF = FI->getOperand(0);
7477     MatchIsOpZero = true;
7478   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7479     MatchOp  = TI->getOperand(1);
7480     OtherOpT = TI->getOperand(0);
7481     OtherOpF = FI->getOperand(1);
7482     MatchIsOpZero = true;
7483   } else {
7484     return 0;
7485   }
7486
7487   // If we reach here, they do have operations in common.
7488   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7489                                      OtherOpF, SI.getName()+".v");
7490   InsertNewInstBefore(NewSI, SI);
7491
7492   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7493     if (MatchIsOpZero)
7494       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7495     else
7496       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7497   }
7498   assert(0 && "Shouldn't get here");
7499   return 0;
7500 }
7501
7502 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7503   Value *CondVal = SI.getCondition();
7504   Value *TrueVal = SI.getTrueValue();
7505   Value *FalseVal = SI.getFalseValue();
7506
7507   // select true, X, Y  -> X
7508   // select false, X, Y -> Y
7509   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7510     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7511
7512   // select C, X, X -> X
7513   if (TrueVal == FalseVal)
7514     return ReplaceInstUsesWith(SI, TrueVal);
7515
7516   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7517     return ReplaceInstUsesWith(SI, FalseVal);
7518   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7519     return ReplaceInstUsesWith(SI, TrueVal);
7520   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7521     if (isa<Constant>(TrueVal))
7522       return ReplaceInstUsesWith(SI, TrueVal);
7523     else
7524       return ReplaceInstUsesWith(SI, FalseVal);
7525   }
7526
7527   if (SI.getType() == Type::Int1Ty) {
7528     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7529       if (C->getZExtValue()) {
7530         // Change: A = select B, true, C --> A = or B, C
7531         return BinaryOperator::createOr(CondVal, FalseVal);
7532       } else {
7533         // Change: A = select B, false, C --> A = and !B, C
7534         Value *NotCond =
7535           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7536                                              "not."+CondVal->getName()), SI);
7537         return BinaryOperator::createAnd(NotCond, FalseVal);
7538       }
7539     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7540       if (C->getZExtValue() == false) {
7541         // Change: A = select B, C, false --> A = and B, C
7542         return BinaryOperator::createAnd(CondVal, TrueVal);
7543       } else {
7544         // Change: A = select B, C, true --> A = or !B, C
7545         Value *NotCond =
7546           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7547                                              "not."+CondVal->getName()), SI);
7548         return BinaryOperator::createOr(NotCond, TrueVal);
7549       }
7550     }
7551   }
7552
7553   // Selecting between two integer constants?
7554   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7555     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7556       // select C, 1, 0 -> cast C to int
7557       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
7558         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7559       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
7560         // select C, 0, 1 -> cast !C to int
7561         Value *NotCond =
7562           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7563                                                "not."+CondVal->getName()), SI);
7564         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7565       }
7566
7567       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7568
7569         // (x <s 0) ? -1 : 0 -> ashr x, 31
7570         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
7571         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7572           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7573             bool CanXForm = false;
7574             if (IC->isSignedPredicate())
7575               CanXForm = CmpCst->isNullValue() && 
7576                          IC->getPredicate() == ICmpInst::ICMP_SLT;
7577             else {
7578               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
7579               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
7580                          IC->getPredicate() == ICmpInst::ICMP_UGT;
7581             }
7582             
7583             if (CanXForm) {
7584               // The comparison constant and the result are not neccessarily the
7585               // same width. Make an all-ones value by inserting a AShr.
7586               Value *X = IC->getOperand(0);
7587               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
7588               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7589               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7590                                                         ShAmt, "ones");
7591               InsertNewInstBefore(SRA, SI);
7592               
7593               // Finally, convert to the type of the select RHS.  We figure out
7594               // if this requires a SExt, Trunc or BitCast based on the sizes.
7595               Instruction::CastOps opc = Instruction::BitCast;
7596               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7597               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
7598               if (SRASize < SISize)
7599                 opc = Instruction::SExt;
7600               else if (SRASize > SISize)
7601                 opc = Instruction::Trunc;
7602               return CastInst::create(opc, SRA, SI.getType());
7603             }
7604           }
7605
7606
7607         // If one of the constants is zero (we know they can't both be) and we
7608         // have a fcmp instruction with zero, and we have an 'and' with the
7609         // non-constant value, eliminate this whole mess.  This corresponds to
7610         // cases like this: ((X & 27) ? 27 : 0)
7611         if (TrueValC->isNullValue() || FalseValC->isNullValue())
7612           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7613               cast<Constant>(IC->getOperand(1))->isNullValue())
7614             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7615               if (ICA->getOpcode() == Instruction::And &&
7616                   isa<ConstantInt>(ICA->getOperand(1)) &&
7617                   (ICA->getOperand(1) == TrueValC ||
7618                    ICA->getOperand(1) == FalseValC) &&
7619                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7620                 // Okay, now we know that everything is set up, we just don't
7621                 // know whether we have a icmp_ne or icmp_eq and whether the 
7622                 // true or false val is the zero.
7623                 bool ShouldNotVal = !TrueValC->isNullValue();
7624                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7625                 Value *V = ICA;
7626                 if (ShouldNotVal)
7627                   V = InsertNewInstBefore(BinaryOperator::create(
7628                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7629                 return ReplaceInstUsesWith(SI, V);
7630               }
7631       }
7632     }
7633
7634   // See if we are selecting two values based on a comparison of the two values.
7635   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7636     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7637       // Transform (X == Y) ? X : Y  -> Y
7638       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7639         return ReplaceInstUsesWith(SI, FalseVal);
7640       // Transform (X != Y) ? X : Y  -> X
7641       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7642         return ReplaceInstUsesWith(SI, TrueVal);
7643       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7644
7645     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7646       // Transform (X == Y) ? Y : X  -> X
7647       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7648         return ReplaceInstUsesWith(SI, FalseVal);
7649       // Transform (X != Y) ? Y : X  -> Y
7650       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7651         return ReplaceInstUsesWith(SI, TrueVal);
7652       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7653     }
7654   }
7655
7656   // See if we are selecting two values based on a comparison of the two values.
7657   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7658     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7659       // Transform (X == Y) ? X : Y  -> Y
7660       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7661         return ReplaceInstUsesWith(SI, FalseVal);
7662       // Transform (X != Y) ? X : Y  -> X
7663       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7664         return ReplaceInstUsesWith(SI, TrueVal);
7665       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7666
7667     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7668       // Transform (X == Y) ? Y : X  -> X
7669       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7670         return ReplaceInstUsesWith(SI, FalseVal);
7671       // Transform (X != Y) ? Y : X  -> Y
7672       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7673         return ReplaceInstUsesWith(SI, TrueVal);
7674       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7675     }
7676   }
7677
7678   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7679     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7680       if (TI->hasOneUse() && FI->hasOneUse()) {
7681         Instruction *AddOp = 0, *SubOp = 0;
7682
7683         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7684         if (TI->getOpcode() == FI->getOpcode())
7685           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7686             return IV;
7687
7688         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7689         // even legal for FP.
7690         if (TI->getOpcode() == Instruction::Sub &&
7691             FI->getOpcode() == Instruction::Add) {
7692           AddOp = FI; SubOp = TI;
7693         } else if (FI->getOpcode() == Instruction::Sub &&
7694                    TI->getOpcode() == Instruction::Add) {
7695           AddOp = TI; SubOp = FI;
7696         }
7697
7698         if (AddOp) {
7699           Value *OtherAddOp = 0;
7700           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7701             OtherAddOp = AddOp->getOperand(1);
7702           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7703             OtherAddOp = AddOp->getOperand(0);
7704           }
7705
7706           if (OtherAddOp) {
7707             // So at this point we know we have (Y -> OtherAddOp):
7708             //        select C, (add X, Y), (sub X, Z)
7709             Value *NegVal;  // Compute -Z
7710             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7711               NegVal = ConstantExpr::getNeg(C);
7712             } else {
7713               NegVal = InsertNewInstBefore(
7714                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7715             }
7716
7717             Value *NewTrueOp = OtherAddOp;
7718             Value *NewFalseOp = NegVal;
7719             if (AddOp != TI)
7720               std::swap(NewTrueOp, NewFalseOp);
7721             Instruction *NewSel =
7722               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7723
7724             NewSel = InsertNewInstBefore(NewSel, SI);
7725             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7726           }
7727         }
7728       }
7729
7730   // See if we can fold the select into one of our operands.
7731   if (SI.getType()->isInteger()) {
7732     // See the comment above GetSelectFoldableOperands for a description of the
7733     // transformation we are doing here.
7734     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7735       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7736           !isa<Constant>(FalseVal))
7737         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7738           unsigned OpToFold = 0;
7739           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7740             OpToFold = 1;
7741           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7742             OpToFold = 2;
7743           }
7744
7745           if (OpToFold) {
7746             Constant *C = GetSelectFoldableConstant(TVI);
7747             Instruction *NewSel =
7748               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7749             InsertNewInstBefore(NewSel, SI);
7750             NewSel->takeName(TVI);
7751             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7752               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7753             else {
7754               assert(0 && "Unknown instruction!!");
7755             }
7756           }
7757         }
7758
7759     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7760       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7761           !isa<Constant>(TrueVal))
7762         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7763           unsigned OpToFold = 0;
7764           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7765             OpToFold = 1;
7766           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7767             OpToFold = 2;
7768           }
7769
7770           if (OpToFold) {
7771             Constant *C = GetSelectFoldableConstant(FVI);
7772             Instruction *NewSel =
7773               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7774             InsertNewInstBefore(NewSel, SI);
7775             NewSel->takeName(FVI);
7776             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7777               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7778             else
7779               assert(0 && "Unknown instruction!!");
7780           }
7781         }
7782   }
7783
7784   if (BinaryOperator::isNot(CondVal)) {
7785     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7786     SI.setOperand(1, FalseVal);
7787     SI.setOperand(2, TrueVal);
7788     return &SI;
7789   }
7790
7791   return 0;
7792 }
7793
7794 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7795 /// determine, return it, otherwise return 0.
7796 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7797   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7798     unsigned Align = GV->getAlignment();
7799     if (Align == 0 && TD) 
7800       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7801     return Align;
7802   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7803     unsigned Align = AI->getAlignment();
7804     if (Align == 0 && TD) {
7805       if (isa<AllocaInst>(AI))
7806         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7807       else if (isa<MallocInst>(AI)) {
7808         // Malloc returns maximally aligned memory.
7809         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7810         Align =
7811           std::max(Align,
7812                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7813         Align =
7814           std::max(Align,
7815                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7816       }
7817     }
7818     return Align;
7819   } else if (isa<BitCastInst>(V) ||
7820              (isa<ConstantExpr>(V) && 
7821               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7822     User *CI = cast<User>(V);
7823     if (isa<PointerType>(CI->getOperand(0)->getType()))
7824       return GetKnownAlignment(CI->getOperand(0), TD);
7825     return 0;
7826   } else if (isa<GetElementPtrInst>(V) ||
7827              (isa<ConstantExpr>(V) && 
7828               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7829     User *GEPI = cast<User>(V);
7830     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7831     if (BaseAlignment == 0) return 0;
7832     
7833     // If all indexes are zero, it is just the alignment of the base pointer.
7834     bool AllZeroOperands = true;
7835     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7836       if (!isa<Constant>(GEPI->getOperand(i)) ||
7837           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7838         AllZeroOperands = false;
7839         break;
7840       }
7841     if (AllZeroOperands)
7842       return BaseAlignment;
7843     
7844     // Otherwise, if the base alignment is >= the alignment we expect for the
7845     // base pointer type, then we know that the resultant pointer is aligned at
7846     // least as much as its type requires.
7847     if (!TD) return 0;
7848
7849     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7850     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7851     if (TD->getABITypeAlignment(PtrTy->getElementType())
7852         <= BaseAlignment) {
7853       const Type *GEPTy = GEPI->getType();
7854       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7855       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7856     }
7857     return 0;
7858   }
7859   return 0;
7860 }
7861
7862
7863 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7864 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7865 /// the heavy lifting.
7866 ///
7867 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7868   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7869   if (!II) return visitCallSite(&CI);
7870   
7871   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7872   // visitCallSite.
7873   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7874     bool Changed = false;
7875
7876     // memmove/cpy/set of zero bytes is a noop.
7877     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7878       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7879
7880       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7881         if (CI->getZExtValue() == 1) {
7882           // Replace the instruction with just byte operations.  We would
7883           // transform other cases to loads/stores, but we don't know if
7884           // alignment is sufficient.
7885         }
7886     }
7887
7888     // If we have a memmove and the source operation is a constant global,
7889     // then the source and dest pointers can't alias, so we can change this
7890     // into a call to memcpy.
7891     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7892       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7893         if (GVSrc->isConstant()) {
7894           Module *M = CI.getParent()->getParent()->getParent();
7895           const char *Name;
7896           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7897               Type::Int32Ty)
7898             Name = "llvm.memcpy.i32";
7899           else
7900             Name = "llvm.memcpy.i64";
7901           Constant *MemCpy = M->getOrInsertFunction(Name,
7902                                      CI.getCalledFunction()->getFunctionType());
7903           CI.setOperand(0, MemCpy);
7904           Changed = true;
7905         }
7906     }
7907
7908     // If we can determine a pointer alignment that is bigger than currently
7909     // set, update the alignment.
7910     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7911       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7912       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7913       unsigned Align = std::min(Alignment1, Alignment2);
7914       if (MI->getAlignment()->getZExtValue() < Align) {
7915         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7916         Changed = true;
7917       }
7918     } else if (isa<MemSetInst>(MI)) {
7919       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7920       if (MI->getAlignment()->getZExtValue() < Alignment) {
7921         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7922         Changed = true;
7923       }
7924     }
7925           
7926     if (Changed) return II;
7927   } else {
7928     switch (II->getIntrinsicID()) {
7929     default: break;
7930     case Intrinsic::ppc_altivec_lvx:
7931     case Intrinsic::ppc_altivec_lvxl:
7932     case Intrinsic::x86_sse_loadu_ps:
7933     case Intrinsic::x86_sse2_loadu_pd:
7934     case Intrinsic::x86_sse2_loadu_dq:
7935       // Turn PPC lvx     -> load if the pointer is known aligned.
7936       // Turn X86 loadups -> load if the pointer is known aligned.
7937       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7938         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7939                                       PointerType::get(II->getType()), CI);
7940         return new LoadInst(Ptr);
7941       }
7942       break;
7943     case Intrinsic::ppc_altivec_stvx:
7944     case Intrinsic::ppc_altivec_stvxl:
7945       // Turn stvx -> store if the pointer is known aligned.
7946       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7947         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7948         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7949                                       OpPtrTy, CI);
7950         return new StoreInst(II->getOperand(1), Ptr);
7951       }
7952       break;
7953     case Intrinsic::x86_sse_storeu_ps:
7954     case Intrinsic::x86_sse2_storeu_pd:
7955     case Intrinsic::x86_sse2_storeu_dq:
7956     case Intrinsic::x86_sse2_storel_dq:
7957       // Turn X86 storeu -> store if the pointer is known aligned.
7958       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7959         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7960         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7961                                       OpPtrTy, CI);
7962         return new StoreInst(II->getOperand(2), Ptr);
7963       }
7964       break;
7965       
7966     case Intrinsic::x86_sse_cvttss2si: {
7967       // These intrinsics only demands the 0th element of its input vector.  If
7968       // we can simplify the input based on that, do so now.
7969       uint64_t UndefElts;
7970       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7971                                                 UndefElts)) {
7972         II->setOperand(1, V);
7973         return II;
7974       }
7975       break;
7976     }
7977       
7978     case Intrinsic::ppc_altivec_vperm:
7979       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7980       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7981         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7982         
7983         // Check that all of the elements are integer constants or undefs.
7984         bool AllEltsOk = true;
7985         for (unsigned i = 0; i != 16; ++i) {
7986           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7987               !isa<UndefValue>(Mask->getOperand(i))) {
7988             AllEltsOk = false;
7989             break;
7990           }
7991         }
7992         
7993         if (AllEltsOk) {
7994           // Cast the input vectors to byte vectors.
7995           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7996                                         II->getOperand(1), Mask->getType(), CI);
7997           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7998                                         II->getOperand(2), Mask->getType(), CI);
7999           Value *Result = UndefValue::get(Op0->getType());
8000           
8001           // Only extract each element once.
8002           Value *ExtractedElts[32];
8003           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8004           
8005           for (unsigned i = 0; i != 16; ++i) {
8006             if (isa<UndefValue>(Mask->getOperand(i)))
8007               continue;
8008             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8009             Idx &= 31;  // Match the hardware behavior.
8010             
8011             if (ExtractedElts[Idx] == 0) {
8012               Instruction *Elt = 
8013                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8014               InsertNewInstBefore(Elt, CI);
8015               ExtractedElts[Idx] = Elt;
8016             }
8017           
8018             // Insert this value into the result vector.
8019             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8020             InsertNewInstBefore(cast<Instruction>(Result), CI);
8021           }
8022           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8023         }
8024       }
8025       break;
8026
8027     case Intrinsic::stackrestore: {
8028       // If the save is right next to the restore, remove the restore.  This can
8029       // happen when variable allocas are DCE'd.
8030       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8031         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8032           BasicBlock::iterator BI = SS;
8033           if (&*++BI == II)
8034             return EraseInstFromFunction(CI);
8035         }
8036       }
8037       
8038       // If the stack restore is in a return/unwind block and if there are no
8039       // allocas or calls between the restore and the return, nuke the restore.
8040       TerminatorInst *TI = II->getParent()->getTerminator();
8041       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8042         BasicBlock::iterator BI = II;
8043         bool CannotRemove = false;
8044         for (++BI; &*BI != TI; ++BI) {
8045           if (isa<AllocaInst>(BI) ||
8046               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8047             CannotRemove = true;
8048             break;
8049           }
8050         }
8051         if (!CannotRemove)
8052           return EraseInstFromFunction(CI);
8053       }
8054       break;
8055     }
8056     }
8057   }
8058
8059   return visitCallSite(II);
8060 }
8061
8062 // InvokeInst simplification
8063 //
8064 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8065   return visitCallSite(&II);
8066 }
8067
8068 // visitCallSite - Improvements for call and invoke instructions.
8069 //
8070 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8071   bool Changed = false;
8072
8073   // If the callee is a constexpr cast of a function, attempt to move the cast
8074   // to the arguments of the call/invoke.
8075   if (transformConstExprCastCall(CS)) return 0;
8076
8077   Value *Callee = CS.getCalledValue();
8078
8079   if (Function *CalleeF = dyn_cast<Function>(Callee))
8080     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8081       Instruction *OldCall = CS.getInstruction();
8082       // If the call and callee calling conventions don't match, this call must
8083       // be unreachable, as the call is undefined.
8084       new StoreInst(ConstantInt::getTrue(),
8085                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
8086       if (!OldCall->use_empty())
8087         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8088       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8089         return EraseInstFromFunction(*OldCall);
8090       return 0;
8091     }
8092
8093   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8094     // This instruction is not reachable, just remove it.  We insert a store to
8095     // undef so that we know that this code is not reachable, despite the fact
8096     // that we can't modify the CFG here.
8097     new StoreInst(ConstantInt::getTrue(),
8098                   UndefValue::get(PointerType::get(Type::Int1Ty)),
8099                   CS.getInstruction());
8100
8101     if (!CS.getInstruction()->use_empty())
8102       CS.getInstruction()->
8103         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8104
8105     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8106       // Don't break the CFG, insert a dummy cond branch.
8107       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8108                      ConstantInt::getTrue(), II);
8109     }
8110     return EraseInstFromFunction(*CS.getInstruction());
8111   }
8112
8113   const PointerType *PTy = cast<PointerType>(Callee->getType());
8114   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8115   if (FTy->isVarArg()) {
8116     // See if we can optimize any arguments passed through the varargs area of
8117     // the call.
8118     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8119            E = CS.arg_end(); I != E; ++I)
8120       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8121         // If this cast does not effect the value passed through the varargs
8122         // area, we can eliminate the use of the cast.
8123         Value *Op = CI->getOperand(0);
8124         if (CI->isLosslessCast()) {
8125           *I = Op;
8126           Changed = true;
8127         }
8128       }
8129   }
8130
8131   return Changed ? CS.getInstruction() : 0;
8132 }
8133
8134 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8135 // attempt to move the cast to the arguments of the call/invoke.
8136 //
8137 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8138   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8139   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8140   if (CE->getOpcode() != Instruction::BitCast || 
8141       !isa<Function>(CE->getOperand(0)))
8142     return false;
8143   Function *Callee = cast<Function>(CE->getOperand(0));
8144   Instruction *Caller = CS.getInstruction();
8145
8146   // Okay, this is a cast from a function to a different type.  Unless doing so
8147   // would cause a type conversion of one of our arguments, change this call to
8148   // be a direct call with arguments casted to the appropriate types.
8149   //
8150   const FunctionType *FT = Callee->getFunctionType();
8151   const Type *OldRetTy = Caller->getType();
8152
8153   // Check to see if we are changing the return type...
8154   if (OldRetTy != FT->getReturnType()) {
8155     if (Callee->isDeclaration() && !Caller->use_empty() && 
8156         // Conversion is ok if changing from pointer to int of same size.
8157         !(isa<PointerType>(FT->getReturnType()) &&
8158           TD->getIntPtrType() == OldRetTy))
8159       return false;   // Cannot transform this return value.
8160
8161     // If the callsite is an invoke instruction, and the return value is used by
8162     // a PHI node in a successor, we cannot change the return type of the call
8163     // because there is no place to put the cast instruction (without breaking
8164     // the critical edge).  Bail out in this case.
8165     if (!Caller->use_empty())
8166       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8167         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8168              UI != E; ++UI)
8169           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8170             if (PN->getParent() == II->getNormalDest() ||
8171                 PN->getParent() == II->getUnwindDest())
8172               return false;
8173   }
8174
8175   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8176   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8177
8178   CallSite::arg_iterator AI = CS.arg_begin();
8179   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8180     const Type *ParamTy = FT->getParamType(i);
8181     const Type *ActTy = (*AI)->getType();
8182     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8183     //Either we can cast directly, or we can upconvert the argument
8184     bool isConvertible = ActTy == ParamTy ||
8185       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8186       (ParamTy->isInteger() && ActTy->isInteger() &&
8187        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8188       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8189        && c->getSExtValue() > 0);
8190     if (Callee->isDeclaration() && !isConvertible) return false;
8191   }
8192
8193   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8194       Callee->isDeclaration())
8195     return false;   // Do not delete arguments unless we have a function body...
8196
8197   // Okay, we decided that this is a safe thing to do: go ahead and start
8198   // inserting cast instructions as necessary...
8199   std::vector<Value*> Args;
8200   Args.reserve(NumActualArgs);
8201
8202   AI = CS.arg_begin();
8203   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8204     const Type *ParamTy = FT->getParamType(i);
8205     if ((*AI)->getType() == ParamTy) {
8206       Args.push_back(*AI);
8207     } else {
8208       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8209           false, ParamTy, false);
8210       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8211       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8212     }
8213   }
8214
8215   // If the function takes more arguments than the call was taking, add them
8216   // now...
8217   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8218     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8219
8220   // If we are removing arguments to the function, emit an obnoxious warning...
8221   if (FT->getNumParams() < NumActualArgs)
8222     if (!FT->isVarArg()) {
8223       cerr << "WARNING: While resolving call to function '"
8224            << Callee->getName() << "' arguments were dropped!\n";
8225     } else {
8226       // Add all of the arguments in their promoted form to the arg list...
8227       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8228         const Type *PTy = getPromotedType((*AI)->getType());
8229         if (PTy != (*AI)->getType()) {
8230           // Must promote to pass through va_arg area!
8231           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8232                                                                 PTy, false);
8233           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8234           InsertNewInstBefore(Cast, *Caller);
8235           Args.push_back(Cast);
8236         } else {
8237           Args.push_back(*AI);
8238         }
8239       }
8240     }
8241
8242   if (FT->getReturnType() == Type::VoidTy)
8243     Caller->setName("");   // Void type should not have a name.
8244
8245   Instruction *NC;
8246   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8247     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8248                         &Args[0], Args.size(), Caller->getName(), Caller);
8249     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
8250   } else {
8251     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
8252     if (cast<CallInst>(Caller)->isTailCall())
8253       cast<CallInst>(NC)->setTailCall();
8254    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8255   }
8256
8257   // Insert a cast of the return type as necessary.
8258   Value *NV = NC;
8259   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8260     if (NV->getType() != Type::VoidTy) {
8261       const Type *CallerTy = Caller->getType();
8262       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8263                                                             CallerTy, false);
8264       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8265
8266       // If this is an invoke instruction, we should insert it after the first
8267       // non-phi, instruction in the normal successor block.
8268       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8269         BasicBlock::iterator I = II->getNormalDest()->begin();
8270         while (isa<PHINode>(I)) ++I;
8271         InsertNewInstBefore(NC, *I);
8272       } else {
8273         // Otherwise, it's a call, just insert cast right after the call instr
8274         InsertNewInstBefore(NC, *Caller);
8275       }
8276       AddUsersToWorkList(*Caller);
8277     } else {
8278       NV = UndefValue::get(Caller->getType());
8279     }
8280   }
8281
8282   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8283     Caller->replaceAllUsesWith(NV);
8284   Caller->eraseFromParent();
8285   RemoveFromWorkList(Caller);
8286   return true;
8287 }
8288
8289 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8290 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8291 /// and a single binop.
8292 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8293   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8294   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8295          isa<CmpInst>(FirstInst));
8296   unsigned Opc = FirstInst->getOpcode();
8297   Value *LHSVal = FirstInst->getOperand(0);
8298   Value *RHSVal = FirstInst->getOperand(1);
8299     
8300   const Type *LHSType = LHSVal->getType();
8301   const Type *RHSType = RHSVal->getType();
8302   
8303   // Scan to see if all operands are the same opcode, all have one use, and all
8304   // kill their operands (i.e. the operands have one use).
8305   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8306     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8307     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8308         // Verify type of the LHS matches so we don't fold cmp's of different
8309         // types or GEP's with different index types.
8310         I->getOperand(0)->getType() != LHSType ||
8311         I->getOperand(1)->getType() != RHSType)
8312       return 0;
8313
8314     // If they are CmpInst instructions, check their predicates
8315     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8316       if (cast<CmpInst>(I)->getPredicate() !=
8317           cast<CmpInst>(FirstInst)->getPredicate())
8318         return 0;
8319     
8320     // Keep track of which operand needs a phi node.
8321     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8322     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8323   }
8324   
8325   // Otherwise, this is safe to transform, determine if it is profitable.
8326
8327   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8328   // Indexes are often folded into load/store instructions, so we don't want to
8329   // hide them behind a phi.
8330   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8331     return 0;
8332   
8333   Value *InLHS = FirstInst->getOperand(0);
8334   Value *InRHS = FirstInst->getOperand(1);
8335   PHINode *NewLHS = 0, *NewRHS = 0;
8336   if (LHSVal == 0) {
8337     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8338     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8339     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8340     InsertNewInstBefore(NewLHS, PN);
8341     LHSVal = NewLHS;
8342   }
8343   
8344   if (RHSVal == 0) {
8345     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8346     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8347     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8348     InsertNewInstBefore(NewRHS, PN);
8349     RHSVal = NewRHS;
8350   }
8351   
8352   // Add all operands to the new PHIs.
8353   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8354     if (NewLHS) {
8355       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8356       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8357     }
8358     if (NewRHS) {
8359       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8360       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8361     }
8362   }
8363     
8364   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8365     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8366   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8367     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8368                            RHSVal);
8369   else {
8370     assert(isa<GetElementPtrInst>(FirstInst));
8371     return new GetElementPtrInst(LHSVal, RHSVal);
8372   }
8373 }
8374
8375 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8376 /// of the block that defines it.  This means that it must be obvious the value
8377 /// of the load is not changed from the point of the load to the end of the
8378 /// block it is in.
8379 ///
8380 /// Finally, it is safe, but not profitable, to sink a load targetting a
8381 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8382 /// to a register.
8383 static bool isSafeToSinkLoad(LoadInst *L) {
8384   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8385   
8386   for (++BBI; BBI != E; ++BBI)
8387     if (BBI->mayWriteToMemory())
8388       return false;
8389   
8390   // Check for non-address taken alloca.  If not address-taken already, it isn't
8391   // profitable to do this xform.
8392   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8393     bool isAddressTaken = false;
8394     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8395          UI != E; ++UI) {
8396       if (isa<LoadInst>(UI)) continue;
8397       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8398         // If storing TO the alloca, then the address isn't taken.
8399         if (SI->getOperand(1) == AI) continue;
8400       }
8401       isAddressTaken = true;
8402       break;
8403     }
8404     
8405     if (!isAddressTaken)
8406       return false;
8407   }
8408   
8409   return true;
8410 }
8411
8412
8413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8414 // operator and they all are only used by the PHI, PHI together their
8415 // inputs, and do the operation once, to the result of the PHI.
8416 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8417   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8418
8419   // Scan the instruction, looking for input operations that can be folded away.
8420   // If all input operands to the phi are the same instruction (e.g. a cast from
8421   // the same type or "+42") we can pull the operation through the PHI, reducing
8422   // code size and simplifying code.
8423   Constant *ConstantOp = 0;
8424   const Type *CastSrcTy = 0;
8425   bool isVolatile = false;
8426   if (isa<CastInst>(FirstInst)) {
8427     CastSrcTy = FirstInst->getOperand(0)->getType();
8428   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8429     // Can fold binop, compare or shift here if the RHS is a constant, 
8430     // otherwise call FoldPHIArgBinOpIntoPHI.
8431     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8432     if (ConstantOp == 0)
8433       return FoldPHIArgBinOpIntoPHI(PN);
8434   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8435     isVolatile = LI->isVolatile();
8436     // We can't sink the load if the loaded value could be modified between the
8437     // load and the PHI.
8438     if (LI->getParent() != PN.getIncomingBlock(0) ||
8439         !isSafeToSinkLoad(LI))
8440       return 0;
8441   } else if (isa<GetElementPtrInst>(FirstInst)) {
8442     if (FirstInst->getNumOperands() == 2)
8443       return FoldPHIArgBinOpIntoPHI(PN);
8444     // Can't handle general GEPs yet.
8445     return 0;
8446   } else {
8447     return 0;  // Cannot fold this operation.
8448   }
8449
8450   // Check to see if all arguments are the same operation.
8451   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8452     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8453     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8454     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8455       return 0;
8456     if (CastSrcTy) {
8457       if (I->getOperand(0)->getType() != CastSrcTy)
8458         return 0;  // Cast operation must match.
8459     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8460       // We can't sink the load if the loaded value could be modified between 
8461       // the load and the PHI.
8462       if (LI->isVolatile() != isVolatile ||
8463           LI->getParent() != PN.getIncomingBlock(i) ||
8464           !isSafeToSinkLoad(LI))
8465         return 0;
8466     } else if (I->getOperand(1) != ConstantOp) {
8467       return 0;
8468     }
8469   }
8470
8471   // Okay, they are all the same operation.  Create a new PHI node of the
8472   // correct type, and PHI together all of the LHS's of the instructions.
8473   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8474                                PN.getName()+".in");
8475   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8476
8477   Value *InVal = FirstInst->getOperand(0);
8478   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8479
8480   // Add all operands to the new PHI.
8481   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8482     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8483     if (NewInVal != InVal)
8484       InVal = 0;
8485     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8486   }
8487
8488   Value *PhiVal;
8489   if (InVal) {
8490     // The new PHI unions all of the same values together.  This is really
8491     // common, so we handle it intelligently here for compile-time speed.
8492     PhiVal = InVal;
8493     delete NewPN;
8494   } else {
8495     InsertNewInstBefore(NewPN, PN);
8496     PhiVal = NewPN;
8497   }
8498
8499   // Insert and return the new operation.
8500   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8501     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8502   else if (isa<LoadInst>(FirstInst))
8503     return new LoadInst(PhiVal, "", isVolatile);
8504   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8505     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8506   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8507     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8508                            PhiVal, ConstantOp);
8509   else
8510     assert(0 && "Unknown operation");
8511   return 0;
8512 }
8513
8514 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8515 /// that is dead.
8516 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8517   if (PN->use_empty()) return true;
8518   if (!PN->hasOneUse()) return false;
8519
8520   // Remember this node, and if we find the cycle, return.
8521   if (!PotentiallyDeadPHIs.insert(PN).second)
8522     return true;
8523
8524   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8525     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8526
8527   return false;
8528 }
8529
8530 // PHINode simplification
8531 //
8532 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8533   // If LCSSA is around, don't mess with Phi nodes
8534   if (MustPreserveLCSSA) return 0;
8535   
8536   if (Value *V = PN.hasConstantValue())
8537     return ReplaceInstUsesWith(PN, V);
8538
8539   // If all PHI operands are the same operation, pull them through the PHI,
8540   // reducing code size.
8541   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8542       PN.getIncomingValue(0)->hasOneUse())
8543     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8544       return Result;
8545
8546   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8547   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8548   // PHI)... break the cycle.
8549   if (PN.hasOneUse()) {
8550     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8551     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8552       std::set<PHINode*> PotentiallyDeadPHIs;
8553       PotentiallyDeadPHIs.insert(&PN);
8554       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8555         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8556     }
8557    
8558     // If this phi has a single use, and if that use just computes a value for
8559     // the next iteration of a loop, delete the phi.  This occurs with unused
8560     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8561     // common case here is good because the only other things that catch this
8562     // are induction variable analysis (sometimes) and ADCE, which is only run
8563     // late.
8564     if (PHIUser->hasOneUse() &&
8565         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8566         PHIUser->use_back() == &PN) {
8567       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8568     }
8569   }
8570
8571   return 0;
8572 }
8573
8574 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8575                                    Instruction *InsertPoint,
8576                                    InstCombiner *IC) {
8577   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8578   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8579   // We must cast correctly to the pointer type. Ensure that we
8580   // sign extend the integer value if it is smaller as this is
8581   // used for address computation.
8582   Instruction::CastOps opcode = 
8583      (VTySize < PtrSize ? Instruction::SExt :
8584       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8585   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8586 }
8587
8588
8589 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8590   Value *PtrOp = GEP.getOperand(0);
8591   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
8592   // If so, eliminate the noop.
8593   if (GEP.getNumOperands() == 1)
8594     return ReplaceInstUsesWith(GEP, PtrOp);
8595
8596   if (isa<UndefValue>(GEP.getOperand(0)))
8597     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8598
8599   bool HasZeroPointerIndex = false;
8600   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8601     HasZeroPointerIndex = C->isNullValue();
8602
8603   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8604     return ReplaceInstUsesWith(GEP, PtrOp);
8605
8606   // Eliminate unneeded casts for indices.
8607   bool MadeChange = false;
8608   gep_type_iterator GTI = gep_type_begin(GEP);
8609   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8610     if (isa<SequentialType>(*GTI)) {
8611       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8612         if (CI->getOpcode() == Instruction::ZExt ||
8613             CI->getOpcode() == Instruction::SExt) {
8614           const Type *SrcTy = CI->getOperand(0)->getType();
8615           // We can eliminate a cast from i32 to i64 iff the target 
8616           // is a 32-bit pointer target.
8617           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8618             MadeChange = true;
8619             GEP.setOperand(i, CI->getOperand(0));
8620           }
8621         }
8622       }
8623       // If we are using a wider index than needed for this platform, shrink it
8624       // to what we need.  If the incoming value needs a cast instruction,
8625       // insert it.  This explicit cast can make subsequent optimizations more
8626       // obvious.
8627       Value *Op = GEP.getOperand(i);
8628       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8629         if (Constant *C = dyn_cast<Constant>(Op)) {
8630           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8631           MadeChange = true;
8632         } else {
8633           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8634                                 GEP);
8635           GEP.setOperand(i, Op);
8636           MadeChange = true;
8637         }
8638     }
8639   if (MadeChange) return &GEP;
8640
8641   // Combine Indices - If the source pointer to this getelementptr instruction
8642   // is a getelementptr instruction, combine the indices of the two
8643   // getelementptr instructions into a single instruction.
8644   //
8645   SmallVector<Value*, 8> SrcGEPOperands;
8646   if (User *Src = dyn_castGetElementPtr(PtrOp))
8647     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8648
8649   if (!SrcGEPOperands.empty()) {
8650     // Note that if our source is a gep chain itself that we wait for that
8651     // chain to be resolved before we perform this transformation.  This
8652     // avoids us creating a TON of code in some cases.
8653     //
8654     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8655         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8656       return 0;   // Wait until our source is folded to completion.
8657
8658     SmallVector<Value*, 8> Indices;
8659
8660     // Find out whether the last index in the source GEP is a sequential idx.
8661     bool EndsWithSequential = false;
8662     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8663            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8664       EndsWithSequential = !isa<StructType>(*I);
8665
8666     // Can we combine the two pointer arithmetics offsets?
8667     if (EndsWithSequential) {
8668       // Replace: gep (gep %P, long B), long A, ...
8669       // With:    T = long A+B; gep %P, T, ...
8670       //
8671       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8672       if (SO1 == Constant::getNullValue(SO1->getType())) {
8673         Sum = GO1;
8674       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8675         Sum = SO1;
8676       } else {
8677         // If they aren't the same type, convert both to an integer of the
8678         // target's pointer size.
8679         if (SO1->getType() != GO1->getType()) {
8680           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8681             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8682           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8683             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8684           } else {
8685             unsigned PS = TD->getPointerSize();
8686             if (TD->getTypeSize(SO1->getType()) == PS) {
8687               // Convert GO1 to SO1's type.
8688               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8689
8690             } else if (TD->getTypeSize(GO1->getType()) == PS) {
8691               // Convert SO1 to GO1's type.
8692               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8693             } else {
8694               const Type *PT = TD->getIntPtrType();
8695               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8696               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8697             }
8698           }
8699         }
8700         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8701           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8702         else {
8703           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8704           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8705         }
8706       }
8707
8708       // Recycle the GEP we already have if possible.
8709       if (SrcGEPOperands.size() == 2) {
8710         GEP.setOperand(0, SrcGEPOperands[0]);
8711         GEP.setOperand(1, Sum);
8712         return &GEP;
8713       } else {
8714         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8715                        SrcGEPOperands.end()-1);
8716         Indices.push_back(Sum);
8717         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8718       }
8719     } else if (isa<Constant>(*GEP.idx_begin()) &&
8720                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8721                SrcGEPOperands.size() != 1) {
8722       // Otherwise we can do the fold if the first index of the GEP is a zero
8723       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8724                      SrcGEPOperands.end());
8725       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8726     }
8727
8728     if (!Indices.empty())
8729       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8730                                    Indices.size(), GEP.getName());
8731
8732   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8733     // GEP of global variable.  If all of the indices for this GEP are
8734     // constants, we can promote this to a constexpr instead of an instruction.
8735
8736     // Scan for nonconstants...
8737     SmallVector<Constant*, 8> Indices;
8738     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8739     for (; I != E && isa<Constant>(*I); ++I)
8740       Indices.push_back(cast<Constant>(*I));
8741
8742     if (I == E) {  // If they are all constants...
8743       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8744                                                     &Indices[0],Indices.size());
8745
8746       // Replace all uses of the GEP with the new constexpr...
8747       return ReplaceInstUsesWith(GEP, CE);
8748     }
8749   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8750     if (!isa<PointerType>(X->getType())) {
8751       // Not interesting.  Source pointer must be a cast from pointer.
8752     } else if (HasZeroPointerIndex) {
8753       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8754       // into     : GEP [10 x ubyte]* X, long 0, ...
8755       //
8756       // This occurs when the program declares an array extern like "int X[];"
8757       //
8758       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8759       const PointerType *XTy = cast<PointerType>(X->getType());
8760       if (const ArrayType *XATy =
8761           dyn_cast<ArrayType>(XTy->getElementType()))
8762         if (const ArrayType *CATy =
8763             dyn_cast<ArrayType>(CPTy->getElementType()))
8764           if (CATy->getElementType() == XATy->getElementType()) {
8765             // At this point, we know that the cast source type is a pointer
8766             // to an array of the same type as the destination pointer
8767             // array.  Because the array type is never stepped over (there
8768             // is a leading zero) we can fold the cast into this GEP.
8769             GEP.setOperand(0, X);
8770             return &GEP;
8771           }
8772     } else if (GEP.getNumOperands() == 2) {
8773       // Transform things like:
8774       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8775       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8776       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8777       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8778       if (isa<ArrayType>(SrcElTy) &&
8779           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8780           TD->getTypeSize(ResElTy)) {
8781         Value *V = InsertNewInstBefore(
8782                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8783                                      GEP.getOperand(1), GEP.getName()), GEP);
8784         // V and GEP are both pointer types --> BitCast
8785         return new BitCastInst(V, GEP.getType());
8786       }
8787       
8788       // Transform things like:
8789       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8790       //   (where tmp = 8*tmp2) into:
8791       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8792       
8793       if (isa<ArrayType>(SrcElTy) &&
8794           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8795         uint64_t ArrayEltSize =
8796             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8797         
8798         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8799         // allow either a mul, shift, or constant here.
8800         Value *NewIdx = 0;
8801         ConstantInt *Scale = 0;
8802         if (ArrayEltSize == 1) {
8803           NewIdx = GEP.getOperand(1);
8804           Scale = ConstantInt::get(NewIdx->getType(), 1);
8805         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8806           NewIdx = ConstantInt::get(CI->getType(), 1);
8807           Scale = CI;
8808         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8809           if (Inst->getOpcode() == Instruction::Shl &&
8810               isa<ConstantInt>(Inst->getOperand(1))) {
8811             unsigned ShAmt =
8812               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
8813             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
8814             NewIdx = Inst->getOperand(0);
8815           } else if (Inst->getOpcode() == Instruction::Mul &&
8816                      isa<ConstantInt>(Inst->getOperand(1))) {
8817             Scale = cast<ConstantInt>(Inst->getOperand(1));
8818             NewIdx = Inst->getOperand(0);
8819           }
8820         }
8821
8822         // If the index will be to exactly the right offset with the scale taken
8823         // out, perform the transformation.
8824         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8825           if (isa<ConstantInt>(Scale))
8826             Scale = ConstantInt::get(Scale->getType(),
8827                                       Scale->getZExtValue() / ArrayEltSize);
8828           if (Scale->getZExtValue() != 1) {
8829             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8830                                                        true /*SExt*/);
8831             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8832             NewIdx = InsertNewInstBefore(Sc, GEP);
8833           }
8834
8835           // Insert the new GEP instruction.
8836           Instruction *NewGEP =
8837             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8838                                   NewIdx, GEP.getName());
8839           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8840           // The NewGEP must be pointer typed, so must the old one -> BitCast
8841           return new BitCastInst(NewGEP, GEP.getType());
8842         }
8843       }
8844     }
8845   }
8846
8847   return 0;
8848 }
8849
8850 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8851   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8852   if (AI.isArrayAllocation())    // Check C != 1
8853     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8854       const Type *NewTy = 
8855         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8856       AllocationInst *New = 0;
8857
8858       // Create and insert the replacement instruction...
8859       if (isa<MallocInst>(AI))
8860         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8861       else {
8862         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8863         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8864       }
8865
8866       InsertNewInstBefore(New, AI);
8867
8868       // Scan to the end of the allocation instructions, to skip over a block of
8869       // allocas if possible...
8870       //
8871       BasicBlock::iterator It = New;
8872       while (isa<AllocationInst>(*It)) ++It;
8873
8874       // Now that I is pointing to the first non-allocation-inst in the block,
8875       // insert our getelementptr instruction...
8876       //
8877       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8878       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8879                                        New->getName()+".sub", It);
8880
8881       // Now make everything use the getelementptr instead of the original
8882       // allocation.
8883       return ReplaceInstUsesWith(AI, V);
8884     } else if (isa<UndefValue>(AI.getArraySize())) {
8885       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8886     }
8887
8888   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8889   // Note that we only do this for alloca's, because malloc should allocate and
8890   // return a unique pointer, even for a zero byte allocation.
8891   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8892       TD->getTypeSize(AI.getAllocatedType()) == 0)
8893     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8894
8895   return 0;
8896 }
8897
8898 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8899   Value *Op = FI.getOperand(0);
8900
8901   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8902   if (CastInst *CI = dyn_cast<CastInst>(Op))
8903     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8904       FI.setOperand(0, CI->getOperand(0));
8905       return &FI;
8906     }
8907
8908   // free undef -> unreachable.
8909   if (isa<UndefValue>(Op)) {
8910     // Insert a new store to null because we cannot modify the CFG here.
8911     new StoreInst(ConstantInt::getTrue(),
8912                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8913     return EraseInstFromFunction(FI);
8914   }
8915
8916   // If we have 'free null' delete the instruction.  This can happen in stl code
8917   // when lots of inlining happens.
8918   if (isa<ConstantPointerNull>(Op))
8919     return EraseInstFromFunction(FI);
8920
8921   return 0;
8922 }
8923
8924
8925 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8926 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8927   User *CI = cast<User>(LI.getOperand(0));
8928   Value *CastOp = CI->getOperand(0);
8929
8930   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8931   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8932     const Type *SrcPTy = SrcTy->getElementType();
8933
8934     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8935          isa<VectorType>(DestPTy)) {
8936       // If the source is an array, the code below will not succeed.  Check to
8937       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8938       // constants.
8939       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8940         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8941           if (ASrcTy->getNumElements() != 0) {
8942             Value *Idxs[2];
8943             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8944             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8945             SrcTy = cast<PointerType>(CastOp->getType());
8946             SrcPTy = SrcTy->getElementType();
8947           }
8948
8949       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8950             isa<VectorType>(SrcPTy)) &&
8951           // Do not allow turning this into a load of an integer, which is then
8952           // casted to a pointer, this pessimizes pointer analysis a lot.
8953           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8954           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8955                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8956
8957         // Okay, we are casting from one integer or pointer type to another of
8958         // the same size.  Instead of casting the pointer before the load, cast
8959         // the result of the loaded value.
8960         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8961                                                              CI->getName(),
8962                                                          LI.isVolatile()),LI);
8963         // Now cast the result of the load.
8964         return new BitCastInst(NewLoad, LI.getType());
8965       }
8966     }
8967   }
8968   return 0;
8969 }
8970
8971 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8972 /// from this value cannot trap.  If it is not obviously safe to load from the
8973 /// specified pointer, we do a quick local scan of the basic block containing
8974 /// ScanFrom, to determine if the address is already accessed.
8975 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8976   // If it is an alloca or global variable, it is always safe to load from.
8977   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8978
8979   // Otherwise, be a little bit agressive by scanning the local block where we
8980   // want to check to see if the pointer is already being loaded or stored
8981   // from/to.  If so, the previous load or store would have already trapped,
8982   // so there is no harm doing an extra load (also, CSE will later eliminate
8983   // the load entirely).
8984   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8985
8986   while (BBI != E) {
8987     --BBI;
8988
8989     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8990       if (LI->getOperand(0) == V) return true;
8991     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8992       if (SI->getOperand(1) == V) return true;
8993
8994   }
8995   return false;
8996 }
8997
8998 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8999   Value *Op = LI.getOperand(0);
9000
9001   // load (cast X) --> cast (load X) iff safe
9002   if (isa<CastInst>(Op))
9003     if (Instruction *Res = InstCombineLoadCast(*this, LI))
9004       return Res;
9005
9006   // None of the following transforms are legal for volatile loads.
9007   if (LI.isVolatile()) return 0;
9008   
9009   if (&LI.getParent()->front() != &LI) {
9010     BasicBlock::iterator BBI = &LI; --BBI;
9011     // If the instruction immediately before this is a store to the same
9012     // address, do a simple form of store->load forwarding.
9013     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9014       if (SI->getOperand(1) == LI.getOperand(0))
9015         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9016     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9017       if (LIB->getOperand(0) == LI.getOperand(0))
9018         return ReplaceInstUsesWith(LI, LIB);
9019   }
9020
9021   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9022     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
9023         isa<UndefValue>(GEPI->getOperand(0))) {
9024       // Insert a new store to null instruction before the load to indicate
9025       // that this code is not reachable.  We do this instead of inserting
9026       // an unreachable instruction directly because we cannot modify the
9027       // CFG.
9028       new StoreInst(UndefValue::get(LI.getType()),
9029                     Constant::getNullValue(Op->getType()), &LI);
9030       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9031     }
9032
9033   if (Constant *C = dyn_cast<Constant>(Op)) {
9034     // load null/undef -> undef
9035     if ((C->isNullValue() || isa<UndefValue>(C))) {
9036       // Insert a new store to null instruction before the load to indicate that
9037       // this code is not reachable.  We do this instead of inserting an
9038       // unreachable instruction directly because we cannot modify the CFG.
9039       new StoreInst(UndefValue::get(LI.getType()),
9040                     Constant::getNullValue(Op->getType()), &LI);
9041       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9042     }
9043
9044     // Instcombine load (constant global) into the value loaded.
9045     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9046       if (GV->isConstant() && !GV->isDeclaration())
9047         return ReplaceInstUsesWith(LI, GV->getInitializer());
9048
9049     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9050     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9051       if (CE->getOpcode() == Instruction::GetElementPtr) {
9052         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9053           if (GV->isConstant() && !GV->isDeclaration())
9054             if (Constant *V = 
9055                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9056               return ReplaceInstUsesWith(LI, V);
9057         if (CE->getOperand(0)->isNullValue()) {
9058           // Insert a new store to null instruction before the load to indicate
9059           // that this code is not reachable.  We do this instead of inserting
9060           // an unreachable instruction directly because we cannot modify the
9061           // CFG.
9062           new StoreInst(UndefValue::get(LI.getType()),
9063                         Constant::getNullValue(Op->getType()), &LI);
9064           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9065         }
9066
9067       } else if (CE->isCast()) {
9068         if (Instruction *Res = InstCombineLoadCast(*this, LI))
9069           return Res;
9070       }
9071   }
9072
9073   if (Op->hasOneUse()) {
9074     // Change select and PHI nodes to select values instead of addresses: this
9075     // helps alias analysis out a lot, allows many others simplifications, and
9076     // exposes redundancy in the code.
9077     //
9078     // Note that we cannot do the transformation unless we know that the
9079     // introduced loads cannot trap!  Something like this is valid as long as
9080     // the condition is always false: load (select bool %C, int* null, int* %G),
9081     // but it would not be valid if we transformed it to load from null
9082     // unconditionally.
9083     //
9084     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9085       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9086       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9087           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9088         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9089                                      SI->getOperand(1)->getName()+".val"), LI);
9090         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9091                                      SI->getOperand(2)->getName()+".val"), LI);
9092         return new SelectInst(SI->getCondition(), V1, V2);
9093       }
9094
9095       // load (select (cond, null, P)) -> load P
9096       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9097         if (C->isNullValue()) {
9098           LI.setOperand(0, SI->getOperand(2));
9099           return &LI;
9100         }
9101
9102       // load (select (cond, P, null)) -> load P
9103       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9104         if (C->isNullValue()) {
9105           LI.setOperand(0, SI->getOperand(1));
9106           return &LI;
9107         }
9108     }
9109   }
9110   return 0;
9111 }
9112
9113 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9114 /// when possible.
9115 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9116   User *CI = cast<User>(SI.getOperand(1));
9117   Value *CastOp = CI->getOperand(0);
9118
9119   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9120   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9121     const Type *SrcPTy = SrcTy->getElementType();
9122
9123     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9124       // If the source is an array, the code below will not succeed.  Check to
9125       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9126       // constants.
9127       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9128         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9129           if (ASrcTy->getNumElements() != 0) {
9130             Value* Idxs[2];
9131             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9132             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9133             SrcTy = cast<PointerType>(CastOp->getType());
9134             SrcPTy = SrcTy->getElementType();
9135           }
9136
9137       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9138           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9139                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9140
9141         // Okay, we are casting from one integer or pointer type to another of
9142         // the same size.  Instead of casting the pointer before 
9143         // the store, cast the value to be stored.
9144         Value *NewCast;
9145         Value *SIOp0 = SI.getOperand(0);
9146         Instruction::CastOps opcode = Instruction::BitCast;
9147         const Type* CastSrcTy = SIOp0->getType();
9148         const Type* CastDstTy = SrcPTy;
9149         if (isa<PointerType>(CastDstTy)) {
9150           if (CastSrcTy->isInteger())
9151             opcode = Instruction::IntToPtr;
9152         } else if (isa<IntegerType>(CastDstTy)) {
9153           if (isa<PointerType>(SIOp0->getType()))
9154             opcode = Instruction::PtrToInt;
9155         }
9156         if (Constant *C = dyn_cast<Constant>(SIOp0))
9157           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9158         else
9159           NewCast = IC.InsertNewInstBefore(
9160             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9161             SI);
9162         return new StoreInst(NewCast, CastOp);
9163       }
9164     }
9165   }
9166   return 0;
9167 }
9168
9169 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9170   Value *Val = SI.getOperand(0);
9171   Value *Ptr = SI.getOperand(1);
9172
9173   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9174     EraseInstFromFunction(SI);
9175     ++NumCombined;
9176     return 0;
9177   }
9178   
9179   // If the RHS is an alloca with a single use, zapify the store, making the
9180   // alloca dead.
9181   if (Ptr->hasOneUse()) {
9182     if (isa<AllocaInst>(Ptr)) {
9183       EraseInstFromFunction(SI);
9184       ++NumCombined;
9185       return 0;
9186     }
9187     
9188     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9189       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9190           GEP->getOperand(0)->hasOneUse()) {
9191         EraseInstFromFunction(SI);
9192         ++NumCombined;
9193         return 0;
9194       }
9195   }
9196
9197   // Do really simple DSE, to catch cases where there are several consequtive
9198   // stores to the same location, separated by a few arithmetic operations. This
9199   // situation often occurs with bitfield accesses.
9200   BasicBlock::iterator BBI = &SI;
9201   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9202        --ScanInsts) {
9203     --BBI;
9204     
9205     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9206       // Prev store isn't volatile, and stores to the same location?
9207       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9208         ++NumDeadStore;
9209         ++BBI;
9210         EraseInstFromFunction(*PrevSI);
9211         continue;
9212       }
9213       break;
9214     }
9215     
9216     // If this is a load, we have to stop.  However, if the loaded value is from
9217     // the pointer we're loading and is producing the pointer we're storing,
9218     // then *this* store is dead (X = load P; store X -> P).
9219     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9220       if (LI == Val && LI->getOperand(0) == Ptr) {
9221         EraseInstFromFunction(SI);
9222         ++NumCombined;
9223         return 0;
9224       }
9225       // Otherwise, this is a load from some other location.  Stores before it
9226       // may not be dead.
9227       break;
9228     }
9229     
9230     // Don't skip over loads or things that can modify memory.
9231     if (BBI->mayWriteToMemory())
9232       break;
9233   }
9234   
9235   
9236   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9237
9238   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9239   if (isa<ConstantPointerNull>(Ptr)) {
9240     if (!isa<UndefValue>(Val)) {
9241       SI.setOperand(0, UndefValue::get(Val->getType()));
9242       if (Instruction *U = dyn_cast<Instruction>(Val))
9243         AddToWorkList(U);  // Dropped a use.
9244       ++NumCombined;
9245     }
9246     return 0;  // Do not modify these!
9247   }
9248
9249   // store undef, Ptr -> noop
9250   if (isa<UndefValue>(Val)) {
9251     EraseInstFromFunction(SI);
9252     ++NumCombined;
9253     return 0;
9254   }
9255
9256   // If the pointer destination is a cast, see if we can fold the cast into the
9257   // source instead.
9258   if (isa<CastInst>(Ptr))
9259     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9260       return Res;
9261   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9262     if (CE->isCast())
9263       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9264         return Res;
9265
9266   
9267   // If this store is the last instruction in the basic block, and if the block
9268   // ends with an unconditional branch, try to move it to the successor block.
9269   BBI = &SI; ++BBI;
9270   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9271     if (BI->isUnconditional()) {
9272       // Check to see if the successor block has exactly two incoming edges.  If
9273       // so, see if the other predecessor contains a store to the same location.
9274       // if so, insert a PHI node (if needed) and move the stores down.
9275       BasicBlock *Dest = BI->getSuccessor(0);
9276
9277       pred_iterator PI = pred_begin(Dest);
9278       BasicBlock *Other = 0;
9279       if (*PI != BI->getParent())
9280         Other = *PI;
9281       ++PI;
9282       if (PI != pred_end(Dest)) {
9283         if (*PI != BI->getParent())
9284           if (Other)
9285             Other = 0;
9286           else
9287             Other = *PI;
9288         if (++PI != pred_end(Dest))
9289           Other = 0;
9290       }
9291       if (Other) {  // If only one other pred...
9292         BBI = Other->getTerminator();
9293         // Make sure this other block ends in an unconditional branch and that
9294         // there is an instruction before the branch.
9295         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9296             BBI != Other->begin()) {
9297           --BBI;
9298           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9299           
9300           // If this instruction is a store to the same location.
9301           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9302             // Okay, we know we can perform this transformation.  Insert a PHI
9303             // node now if we need it.
9304             Value *MergedVal = OtherStore->getOperand(0);
9305             if (MergedVal != SI.getOperand(0)) {
9306               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9307               PN->reserveOperandSpace(2);
9308               PN->addIncoming(SI.getOperand(0), SI.getParent());
9309               PN->addIncoming(OtherStore->getOperand(0), Other);
9310               MergedVal = InsertNewInstBefore(PN, Dest->front());
9311             }
9312             
9313             // Advance to a place where it is safe to insert the new store and
9314             // insert it.
9315             BBI = Dest->begin();
9316             while (isa<PHINode>(BBI)) ++BBI;
9317             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9318                                               OtherStore->isVolatile()), *BBI);
9319
9320             // Nuke the old stores.
9321             EraseInstFromFunction(SI);
9322             EraseInstFromFunction(*OtherStore);
9323             ++NumCombined;
9324             return 0;
9325           }
9326         }
9327       }
9328     }
9329   
9330   return 0;
9331 }
9332
9333
9334 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9335   // Change br (not X), label True, label False to: br X, label False, True
9336   Value *X = 0;
9337   BasicBlock *TrueDest;
9338   BasicBlock *FalseDest;
9339   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9340       !isa<Constant>(X)) {
9341     // Swap Destinations and condition...
9342     BI.setCondition(X);
9343     BI.setSuccessor(0, FalseDest);
9344     BI.setSuccessor(1, TrueDest);
9345     return &BI;
9346   }
9347
9348   // Cannonicalize fcmp_one -> fcmp_oeq
9349   FCmpInst::Predicate FPred; Value *Y;
9350   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9351                              TrueDest, FalseDest)))
9352     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9353          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9354       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9355       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9356       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9357       NewSCC->takeName(I);
9358       // Swap Destinations and condition...
9359       BI.setCondition(NewSCC);
9360       BI.setSuccessor(0, FalseDest);
9361       BI.setSuccessor(1, TrueDest);
9362       RemoveFromWorkList(I);
9363       I->eraseFromParent();
9364       AddToWorkList(NewSCC);
9365       return &BI;
9366     }
9367
9368   // Cannonicalize icmp_ne -> icmp_eq
9369   ICmpInst::Predicate IPred;
9370   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9371                       TrueDest, FalseDest)))
9372     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9373          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9374          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9375       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9376       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9377       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9378       NewSCC->takeName(I);
9379       // Swap Destinations and condition...
9380       BI.setCondition(NewSCC);
9381       BI.setSuccessor(0, FalseDest);
9382       BI.setSuccessor(1, TrueDest);
9383       RemoveFromWorkList(I);
9384       I->eraseFromParent();;
9385       AddToWorkList(NewSCC);
9386       return &BI;
9387     }
9388
9389   return 0;
9390 }
9391
9392 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9393   Value *Cond = SI.getCondition();
9394   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9395     if (I->getOpcode() == Instruction::Add)
9396       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9397         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9398         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9399           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9400                                                 AddRHS));
9401         SI.setOperand(0, I->getOperand(0));
9402         AddToWorkList(I);
9403         return &SI;
9404       }
9405   }
9406   return 0;
9407 }
9408
9409 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9410 /// is to leave as a vector operation.
9411 static bool CheapToScalarize(Value *V, bool isConstant) {
9412   if (isa<ConstantAggregateZero>(V)) 
9413     return true;
9414   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9415     if (isConstant) return true;
9416     // If all elts are the same, we can extract.
9417     Constant *Op0 = C->getOperand(0);
9418     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9419       if (C->getOperand(i) != Op0)
9420         return false;
9421     return true;
9422   }
9423   Instruction *I = dyn_cast<Instruction>(V);
9424   if (!I) return false;
9425   
9426   // Insert element gets simplified to the inserted element or is deleted if
9427   // this is constant idx extract element and its a constant idx insertelt.
9428   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9429       isa<ConstantInt>(I->getOperand(2)))
9430     return true;
9431   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9432     return true;
9433   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9434     if (BO->hasOneUse() &&
9435         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9436          CheapToScalarize(BO->getOperand(1), isConstant)))
9437       return true;
9438   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9439     if (CI->hasOneUse() &&
9440         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9441          CheapToScalarize(CI->getOperand(1), isConstant)))
9442       return true;
9443   
9444   return false;
9445 }
9446
9447 /// Read and decode a shufflevector mask.
9448 ///
9449 /// It turns undef elements into values that are larger than the number of
9450 /// elements in the input.
9451 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9452   unsigned NElts = SVI->getType()->getNumElements();
9453   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9454     return std::vector<unsigned>(NElts, 0);
9455   if (isa<UndefValue>(SVI->getOperand(2)))
9456     return std::vector<unsigned>(NElts, 2*NElts);
9457
9458   std::vector<unsigned> Result;
9459   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9460   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9461     if (isa<UndefValue>(CP->getOperand(i)))
9462       Result.push_back(NElts*2);  // undef -> 8
9463     else
9464       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9465   return Result;
9466 }
9467
9468 /// FindScalarElement - Given a vector and an element number, see if the scalar
9469 /// value is already around as a register, for example if it were inserted then
9470 /// extracted from the vector.
9471 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9472   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9473   const VectorType *PTy = cast<VectorType>(V->getType());
9474   unsigned Width = PTy->getNumElements();
9475   if (EltNo >= Width)  // Out of range access.
9476     return UndefValue::get(PTy->getElementType());
9477   
9478   if (isa<UndefValue>(V))
9479     return UndefValue::get(PTy->getElementType());
9480   else if (isa<ConstantAggregateZero>(V))
9481     return Constant::getNullValue(PTy->getElementType());
9482   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9483     return CP->getOperand(EltNo);
9484   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9485     // If this is an insert to a variable element, we don't know what it is.
9486     if (!isa<ConstantInt>(III->getOperand(2))) 
9487       return 0;
9488     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9489     
9490     // If this is an insert to the element we are looking for, return the
9491     // inserted value.
9492     if (EltNo == IIElt) 
9493       return III->getOperand(1);
9494     
9495     // Otherwise, the insertelement doesn't modify the value, recurse on its
9496     // vector input.
9497     return FindScalarElement(III->getOperand(0), EltNo);
9498   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9499     unsigned InEl = getShuffleMask(SVI)[EltNo];
9500     if (InEl < Width)
9501       return FindScalarElement(SVI->getOperand(0), InEl);
9502     else if (InEl < Width*2)
9503       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9504     else
9505       return UndefValue::get(PTy->getElementType());
9506   }
9507   
9508   // Otherwise, we don't know.
9509   return 0;
9510 }
9511
9512 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9513
9514   // If packed val is undef, replace extract with scalar undef.
9515   if (isa<UndefValue>(EI.getOperand(0)))
9516     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9517
9518   // If packed val is constant 0, replace extract with scalar 0.
9519   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9520     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9521   
9522   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9523     // If packed val is constant with uniform operands, replace EI
9524     // with that operand
9525     Constant *op0 = C->getOperand(0);
9526     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9527       if (C->getOperand(i) != op0) {
9528         op0 = 0; 
9529         break;
9530       }
9531     if (op0)
9532       return ReplaceInstUsesWith(EI, op0);
9533   }
9534   
9535   // If extracting a specified index from the vector, see if we can recursively
9536   // find a previously computed scalar that was inserted into the vector.
9537   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9538     // This instruction only demands the single element from the input vector.
9539     // If the input vector has a single use, simplify it based on this use
9540     // property.
9541     uint64_t IndexVal = IdxC->getZExtValue();
9542     if (EI.getOperand(0)->hasOneUse()) {
9543       uint64_t UndefElts;
9544       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9545                                                 1 << IndexVal,
9546                                                 UndefElts)) {
9547         EI.setOperand(0, V);
9548         return &EI;
9549       }
9550     }
9551     
9552     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9553       return ReplaceInstUsesWith(EI, Elt);
9554   }
9555   
9556   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9557     if (I->hasOneUse()) {
9558       // Push extractelement into predecessor operation if legal and
9559       // profitable to do so
9560       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9561         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9562         if (CheapToScalarize(BO, isConstantElt)) {
9563           ExtractElementInst *newEI0 = 
9564             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9565                                    EI.getName()+".lhs");
9566           ExtractElementInst *newEI1 =
9567             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9568                                    EI.getName()+".rhs");
9569           InsertNewInstBefore(newEI0, EI);
9570           InsertNewInstBefore(newEI1, EI);
9571           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9572         }
9573       } else if (isa<LoadInst>(I)) {
9574         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9575                                       PointerType::get(EI.getType()), EI);
9576         GetElementPtrInst *GEP = 
9577           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9578         InsertNewInstBefore(GEP, EI);
9579         return new LoadInst(GEP);
9580       }
9581     }
9582     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9583       // Extracting the inserted element?
9584       if (IE->getOperand(2) == EI.getOperand(1))
9585         return ReplaceInstUsesWith(EI, IE->getOperand(1));
9586       // If the inserted and extracted elements are constants, they must not
9587       // be the same value, extract from the pre-inserted value instead.
9588       if (isa<Constant>(IE->getOperand(2)) &&
9589           isa<Constant>(EI.getOperand(1))) {
9590         AddUsesToWorkList(EI);
9591         EI.setOperand(0, IE->getOperand(0));
9592         return &EI;
9593       }
9594     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9595       // If this is extracting an element from a shufflevector, figure out where
9596       // it came from and extract from the appropriate input element instead.
9597       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9598         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9599         Value *Src;
9600         if (SrcIdx < SVI->getType()->getNumElements())
9601           Src = SVI->getOperand(0);
9602         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9603           SrcIdx -= SVI->getType()->getNumElements();
9604           Src = SVI->getOperand(1);
9605         } else {
9606           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9607         }
9608         return new ExtractElementInst(Src, SrcIdx);
9609       }
9610     }
9611   }
9612   return 0;
9613 }
9614
9615 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9616 /// elements from either LHS or RHS, return the shuffle mask and true. 
9617 /// Otherwise, return false.
9618 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9619                                          std::vector<Constant*> &Mask) {
9620   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9621          "Invalid CollectSingleShuffleElements");
9622   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9623
9624   if (isa<UndefValue>(V)) {
9625     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9626     return true;
9627   } else if (V == LHS) {
9628     for (unsigned i = 0; i != NumElts; ++i)
9629       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9630     return true;
9631   } else if (V == RHS) {
9632     for (unsigned i = 0; i != NumElts; ++i)
9633       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9634     return true;
9635   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9636     // If this is an insert of an extract from some other vector, include it.
9637     Value *VecOp    = IEI->getOperand(0);
9638     Value *ScalarOp = IEI->getOperand(1);
9639     Value *IdxOp    = IEI->getOperand(2);
9640     
9641     if (!isa<ConstantInt>(IdxOp))
9642       return false;
9643     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9644     
9645     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
9646       // Okay, we can handle this if the vector we are insertinting into is
9647       // transitively ok.
9648       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9649         // If so, update the mask to reflect the inserted undef.
9650         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9651         return true;
9652       }      
9653     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9654       if (isa<ConstantInt>(EI->getOperand(1)) &&
9655           EI->getOperand(0)->getType() == V->getType()) {
9656         unsigned ExtractedIdx =
9657           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9658         
9659         // This must be extracting from either LHS or RHS.
9660         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9661           // Okay, we can handle this if the vector we are insertinting into is
9662           // transitively ok.
9663           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9664             // If so, update the mask to reflect the inserted value.
9665             if (EI->getOperand(0) == LHS) {
9666               Mask[InsertedIdx & (NumElts-1)] = 
9667                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9668             } else {
9669               assert(EI->getOperand(0) == RHS);
9670               Mask[InsertedIdx & (NumElts-1)] = 
9671                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9672               
9673             }
9674             return true;
9675           }
9676         }
9677       }
9678     }
9679   }
9680   // TODO: Handle shufflevector here!
9681   
9682   return false;
9683 }
9684
9685 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9686 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9687 /// that computes V and the LHS value of the shuffle.
9688 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9689                                      Value *&RHS) {
9690   assert(isa<VectorType>(V->getType()) && 
9691          (RHS == 0 || V->getType() == RHS->getType()) &&
9692          "Invalid shuffle!");
9693   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9694
9695   if (isa<UndefValue>(V)) {
9696     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9697     return V;
9698   } else if (isa<ConstantAggregateZero>(V)) {
9699     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9700     return V;
9701   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9702     // If this is an insert of an extract from some other vector, include it.
9703     Value *VecOp    = IEI->getOperand(0);
9704     Value *ScalarOp = IEI->getOperand(1);
9705     Value *IdxOp    = IEI->getOperand(2);
9706     
9707     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9708       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9709           EI->getOperand(0)->getType() == V->getType()) {
9710         unsigned ExtractedIdx =
9711           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9712         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9713         
9714         // Either the extracted from or inserted into vector must be RHSVec,
9715         // otherwise we'd end up with a shuffle of three inputs.
9716         if (EI->getOperand(0) == RHS || RHS == 0) {
9717           RHS = EI->getOperand(0);
9718           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9719           Mask[InsertedIdx & (NumElts-1)] = 
9720             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9721           return V;
9722         }
9723         
9724         if (VecOp == RHS) {
9725           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9726           // Everything but the extracted element is replaced with the RHS.
9727           for (unsigned i = 0; i != NumElts; ++i) {
9728             if (i != InsertedIdx)
9729               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9730           }
9731           return V;
9732         }
9733         
9734         // If this insertelement is a chain that comes from exactly these two
9735         // vectors, return the vector and the effective shuffle.
9736         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9737           return EI->getOperand(0);
9738         
9739       }
9740     }
9741   }
9742   // TODO: Handle shufflevector here!
9743   
9744   // Otherwise, can't do anything fancy.  Return an identity vector.
9745   for (unsigned i = 0; i != NumElts; ++i)
9746     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9747   return V;
9748 }
9749
9750 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9751   Value *VecOp    = IE.getOperand(0);
9752   Value *ScalarOp = IE.getOperand(1);
9753   Value *IdxOp    = IE.getOperand(2);
9754   
9755   // If the inserted element was extracted from some other vector, and if the 
9756   // indexes are constant, try to turn this into a shufflevector operation.
9757   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9758     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9759         EI->getOperand(0)->getType() == IE.getType()) {
9760       unsigned NumVectorElts = IE.getType()->getNumElements();
9761       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9762       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9763       
9764       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9765         return ReplaceInstUsesWith(IE, VecOp);
9766       
9767       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
9768         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9769       
9770       // If we are extracting a value from a vector, then inserting it right
9771       // back into the same place, just use the input vector.
9772       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9773         return ReplaceInstUsesWith(IE, VecOp);      
9774       
9775       // We could theoretically do this for ANY input.  However, doing so could
9776       // turn chains of insertelement instructions into a chain of shufflevector
9777       // instructions, and right now we do not merge shufflevectors.  As such,
9778       // only do this in a situation where it is clear that there is benefit.
9779       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9780         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
9781         // the values of VecOp, except then one read from EIOp0.
9782         // Build a new shuffle mask.
9783         std::vector<Constant*> Mask;
9784         if (isa<UndefValue>(VecOp))
9785           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9786         else {
9787           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9788           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9789                                                        NumVectorElts));
9790         } 
9791         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9792         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9793                                      ConstantVector::get(Mask));
9794       }
9795       
9796       // If this insertelement isn't used by some other insertelement, turn it
9797       // (and any insertelements it points to), into one big shuffle.
9798       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9799         std::vector<Constant*> Mask;
9800         Value *RHS = 0;
9801         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9802         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9803         // We now have a shuffle of LHS, RHS, Mask.
9804         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9805       }
9806     }
9807   }
9808
9809   return 0;
9810 }
9811
9812
9813 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9814   Value *LHS = SVI.getOperand(0);
9815   Value *RHS = SVI.getOperand(1);
9816   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9817
9818   bool MadeChange = false;
9819   
9820   // Undefined shuffle mask -> undefined value.
9821   if (isa<UndefValue>(SVI.getOperand(2)))
9822     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9823   
9824   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9825   // the undef, change them to undefs.
9826   if (isa<UndefValue>(SVI.getOperand(1))) {
9827     // Scan to see if there are any references to the RHS.  If so, replace them
9828     // with undef element refs and set MadeChange to true.
9829     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9830       if (Mask[i] >= e && Mask[i] != 2*e) {
9831         Mask[i] = 2*e;
9832         MadeChange = true;
9833       }
9834     }
9835     
9836     if (MadeChange) {
9837       // Remap any references to RHS to use LHS.
9838       std::vector<Constant*> Elts;
9839       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9840         if (Mask[i] == 2*e)
9841           Elts.push_back(UndefValue::get(Type::Int32Ty));
9842         else
9843           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9844       }
9845       SVI.setOperand(2, ConstantVector::get(Elts));
9846     }
9847   }
9848   
9849   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9850   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9851   if (LHS == RHS || isa<UndefValue>(LHS)) {
9852     if (isa<UndefValue>(LHS) && LHS == RHS) {
9853       // shuffle(undef,undef,mask) -> undef.
9854       return ReplaceInstUsesWith(SVI, LHS);
9855     }
9856     
9857     // Remap any references to RHS to use LHS.
9858     std::vector<Constant*> Elts;
9859     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9860       if (Mask[i] >= 2*e)
9861         Elts.push_back(UndefValue::get(Type::Int32Ty));
9862       else {
9863         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9864             (Mask[i] <  e && isa<UndefValue>(LHS)))
9865           Mask[i] = 2*e;     // Turn into undef.
9866         else
9867           Mask[i] &= (e-1);  // Force to LHS.
9868         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9869       }
9870     }
9871     SVI.setOperand(0, SVI.getOperand(1));
9872     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9873     SVI.setOperand(2, ConstantVector::get(Elts));
9874     LHS = SVI.getOperand(0);
9875     RHS = SVI.getOperand(1);
9876     MadeChange = true;
9877   }
9878   
9879   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9880   bool isLHSID = true, isRHSID = true;
9881     
9882   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9883     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9884     // Is this an identity shuffle of the LHS value?
9885     isLHSID &= (Mask[i] == i);
9886       
9887     // Is this an identity shuffle of the RHS value?
9888     isRHSID &= (Mask[i]-e == i);
9889   }
9890
9891   // Eliminate identity shuffles.
9892   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9893   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9894   
9895   // If the LHS is a shufflevector itself, see if we can combine it with this
9896   // one without producing an unusual shuffle.  Here we are really conservative:
9897   // we are absolutely afraid of producing a shuffle mask not in the input
9898   // program, because the code gen may not be smart enough to turn a merged
9899   // shuffle into two specific shuffles: it may produce worse code.  As such,
9900   // we only merge two shuffles if the result is one of the two input shuffle
9901   // masks.  In this case, merging the shuffles just removes one instruction,
9902   // which we know is safe.  This is good for things like turning:
9903   // (splat(splat)) -> splat.
9904   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9905     if (isa<UndefValue>(RHS)) {
9906       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9907
9908       std::vector<unsigned> NewMask;
9909       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9910         if (Mask[i] >= 2*e)
9911           NewMask.push_back(2*e);
9912         else
9913           NewMask.push_back(LHSMask[Mask[i]]);
9914       
9915       // If the result mask is equal to the src shuffle or this shuffle mask, do
9916       // the replacement.
9917       if (NewMask == LHSMask || NewMask == Mask) {
9918         std::vector<Constant*> Elts;
9919         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9920           if (NewMask[i] >= e*2) {
9921             Elts.push_back(UndefValue::get(Type::Int32Ty));
9922           } else {
9923             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9924           }
9925         }
9926         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9927                                      LHSSVI->getOperand(1),
9928                                      ConstantVector::get(Elts));
9929       }
9930     }
9931   }
9932
9933   return MadeChange ? &SVI : 0;
9934 }
9935
9936
9937
9938
9939 /// TryToSinkInstruction - Try to move the specified instruction from its
9940 /// current block into the beginning of DestBlock, which can only happen if it's
9941 /// safe to move the instruction past all of the instructions between it and the
9942 /// end of its block.
9943 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9944   assert(I->hasOneUse() && "Invariants didn't hold!");
9945
9946   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9947   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9948
9949   // Do not sink alloca instructions out of the entry block.
9950   if (isa<AllocaInst>(I) && I->getParent() ==
9951         &DestBlock->getParent()->getEntryBlock())
9952     return false;
9953
9954   // We can only sink load instructions if there is nothing between the load and
9955   // the end of block that could change the value.
9956   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9957     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9958          Scan != E; ++Scan)
9959       if (Scan->mayWriteToMemory())
9960         return false;
9961   }
9962
9963   BasicBlock::iterator InsertPos = DestBlock->begin();
9964   while (isa<PHINode>(InsertPos)) ++InsertPos;
9965
9966   I->moveBefore(InsertPos);
9967   ++NumSunkInst;
9968   return true;
9969 }
9970
9971
9972 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9973 /// all reachable code to the worklist.
9974 ///
9975 /// This has a couple of tricks to make the code faster and more powerful.  In
9976 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9977 /// them to the worklist (this significantly speeds up instcombine on code where
9978 /// many instructions are dead or constant).  Additionally, if we find a branch
9979 /// whose condition is a known constant, we only visit the reachable successors.
9980 ///
9981 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9982                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9983                                        InstCombiner &IC,
9984                                        const TargetData *TD) {
9985   // We have now visited this block!  If we've already been here, bail out.
9986   if (!Visited.insert(BB)) return;
9987     
9988   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9989     Instruction *Inst = BBI++;
9990     
9991     // DCE instruction if trivially dead.
9992     if (isInstructionTriviallyDead(Inst)) {
9993       ++NumDeadInst;
9994       DOUT << "IC: DCE: " << *Inst;
9995       Inst->eraseFromParent();
9996       continue;
9997     }
9998     
9999     // ConstantProp instruction if trivially constant.
10000     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10001       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10002       Inst->replaceAllUsesWith(C);
10003       ++NumConstProp;
10004       Inst->eraseFromParent();
10005       continue;
10006     }
10007     
10008     IC.AddToWorkList(Inst);
10009   }
10010
10011   // Recursively visit successors.  If this is a branch or switch on a constant,
10012   // only visit the reachable successor.
10013   TerminatorInst *TI = BB->getTerminator();
10014   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10015     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10016       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10017       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
10018       return;
10019     }
10020   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10021     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10022       // See if this is an explicit destination.
10023       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10024         if (SI->getCaseValue(i) == Cond) {
10025           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
10026           return;
10027         }
10028       
10029       // Otherwise it is the default destination.
10030       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
10031       return;
10032     }
10033   }
10034   
10035   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10036     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
10037 }
10038
10039 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10040   bool Changed = false;
10041   TD = &getAnalysis<TargetData>();
10042   
10043   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10044              << F.getNameStr() << "\n");
10045
10046   {
10047     // Do a depth-first traversal of the function, populate the worklist with
10048     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10049     // track of which blocks we visit.
10050     SmallPtrSet<BasicBlock*, 64> Visited;
10051     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10052
10053     // Do a quick scan over the function.  If we find any blocks that are
10054     // unreachable, remove any instructions inside of them.  This prevents
10055     // the instcombine code from having to deal with some bad special cases.
10056     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10057       if (!Visited.count(BB)) {
10058         Instruction *Term = BB->getTerminator();
10059         while (Term != BB->begin()) {   // Remove instrs bottom-up
10060           BasicBlock::iterator I = Term; --I;
10061
10062           DOUT << "IC: DCE: " << *I;
10063           ++NumDeadInst;
10064
10065           if (!I->use_empty())
10066             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10067           I->eraseFromParent();
10068         }
10069       }
10070   }
10071
10072   while (!Worklist.empty()) {
10073     Instruction *I = RemoveOneFromWorkList();
10074     if (I == 0) continue;  // skip null values.
10075
10076     // Check to see if we can DCE the instruction.
10077     if (isInstructionTriviallyDead(I)) {
10078       // Add operands to the worklist.
10079       if (I->getNumOperands() < 4)
10080         AddUsesToWorkList(*I);
10081       ++NumDeadInst;
10082
10083       DOUT << "IC: DCE: " << *I;
10084
10085       I->eraseFromParent();
10086       RemoveFromWorkList(I);
10087       continue;
10088     }
10089
10090     // Instruction isn't dead, see if we can constant propagate it.
10091     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10092       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10093
10094       // Add operands to the worklist.
10095       AddUsesToWorkList(*I);
10096       ReplaceInstUsesWith(*I, C);
10097
10098       ++NumConstProp;
10099       I->eraseFromParent();
10100       RemoveFromWorkList(I);
10101       continue;
10102     }
10103
10104     // See if we can trivially sink this instruction to a successor basic block.
10105     if (I->hasOneUse()) {
10106       BasicBlock *BB = I->getParent();
10107       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10108       if (UserParent != BB) {
10109         bool UserIsSuccessor = false;
10110         // See if the user is one of our successors.
10111         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10112           if (*SI == UserParent) {
10113             UserIsSuccessor = true;
10114             break;
10115           }
10116
10117         // If the user is one of our immediate successors, and if that successor
10118         // only has us as a predecessors (we'd have to split the critical edge
10119         // otherwise), we can keep going.
10120         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10121             next(pred_begin(UserParent)) == pred_end(UserParent))
10122           // Okay, the CFG is simple enough, try to sink this instruction.
10123           Changed |= TryToSinkInstruction(I, UserParent);
10124       }
10125     }
10126
10127     // Now that we have an instruction, try combining it to simplify it...
10128     if (Instruction *Result = visit(*I)) {
10129       ++NumCombined;
10130       // Should we replace the old instruction with a new one?
10131       if (Result != I) {
10132         DOUT << "IC: Old = " << *I
10133              << "    New = " << *Result;
10134
10135         // Everything uses the new instruction now.
10136         I->replaceAllUsesWith(Result);
10137
10138         // Push the new instruction and any users onto the worklist.
10139         AddToWorkList(Result);
10140         AddUsersToWorkList(*Result);
10141
10142         // Move the name to the new instruction first.
10143         Result->takeName(I);
10144
10145         // Insert the new instruction into the basic block...
10146         BasicBlock *InstParent = I->getParent();
10147         BasicBlock::iterator InsertPos = I;
10148
10149         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10150           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10151             ++InsertPos;
10152
10153         InstParent->getInstList().insert(InsertPos, Result);
10154
10155         // Make sure that we reprocess all operands now that we reduced their
10156         // use counts.
10157         AddUsesToWorkList(*I);
10158
10159         // Instructions can end up on the worklist more than once.  Make sure
10160         // we do not process an instruction that has been deleted.
10161         RemoveFromWorkList(I);
10162
10163         // Erase the old instruction.
10164         InstParent->getInstList().erase(I);
10165       } else {
10166         DOUT << "IC: MOD = " << *I;
10167
10168         // If the instruction was modified, it's possible that it is now dead.
10169         // if so, remove it.
10170         if (isInstructionTriviallyDead(I)) {
10171           // Make sure we process all operands now that we are reducing their
10172           // use counts.
10173           AddUsesToWorkList(*I);
10174
10175           // Instructions may end up in the worklist more than once.  Erase all
10176           // occurrences of this instruction.
10177           RemoveFromWorkList(I);
10178           I->eraseFromParent();
10179         } else {
10180           AddToWorkList(I);
10181           AddUsersToWorkList(*I);
10182         }
10183       }
10184       Changed = true;
10185     }
10186   }
10187
10188   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10189   return Changed;
10190 }
10191
10192
10193 bool InstCombiner::runOnFunction(Function &F) {
10194   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10195   
10196   bool EverMadeChange = false;
10197
10198   // Iterate while there is work to do.
10199   unsigned Iteration = 0;
10200   while (DoOneIteration(F, Iteration++)) 
10201     EverMadeChange = true;
10202   return EverMadeChange;
10203 }
10204
10205 FunctionPass *llvm::createInstructionCombiningPass() {
10206   return new InstCombiner();
10207 }
10208